text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import {focusSafely} from './focusSafely';
import {isElementVisible} from './isElementVisible';
import React, {ReactNode, RefObject, useContext, useEffect, useRef} from 'react';
import {useLayoutEffect} from '@react-aria/utils';
// import {FocusScope, useFocusScope} from 'react-events/focus-scope';
// export {FocusScope};
interface FocusScopeProps {
/** The contents of the focus scope. */
children: ReactNode,
/**
* Whether to contain focus inside the scope, so users cannot
* move focus outside, for example in a modal dialog.
*/
contain?: boolean,
/**
* Whether to restore focus back to the element that was focused
* when the focus scope mounted, after the focus scope unmounts.
*/
restoreFocus?: boolean,
/** Whether to auto focus the first focusable element in the focus scope on mount. */
autoFocus?: boolean
}
interface FocusManagerOptions {
/** The element to start searching from. The currently focused element by default. */
from?: HTMLElement,
/** Whether to only include tabbable elements, or all focusable elements. */
tabbable?: boolean,
/** Whether focus should wrap around when it reaches the end of the scope. */
wrap?: boolean
}
interface FocusManager {
/** Moves focus to the next focusable or tabbable element in the focus scope. */
focusNext(opts?: FocusManagerOptions): HTMLElement,
/** Moves focus to the previous focusable or tabbable element in the focus scope. */
focusPrevious(opts?: FocusManagerOptions): HTMLElement,
/** Moves focus to the first focusable or tabbable element in the focus scope. */
focusFirst(opts?: FocusManagerOptions): HTMLElement,
/** Moves focus to the last focusable or tabbable element in the focus scope. */
focusLast(opts?: FocusManagerOptions): HTMLElement
}
type ScopeRef = RefObject<HTMLElement[]>;
interface IFocusContext {
scopeRef: ScopeRef,
focusManager: FocusManager
}
const FocusContext = React.createContext<IFocusContext>(null);
let activeScope: ScopeRef = null;
let scopes: Map<ScopeRef, ScopeRef | null> = new Map();
// This is a hacky DOM-based implementation of a FocusScope until this RFC lands in React:
// https://github.com/reactjs/rfcs/pull/109
// For now, it relies on the DOM tree order rather than the React tree order, and is probably
// less optimized for performance.
/**
* A FocusScope manages focus for its descendants. It supports containing focus inside
* the scope, restoring focus to the previously focused element on unmount, and auto
* focusing children on mount. It also acts as a container for a programmatic focus
* management interface that can be used to move focus forward and back in response
* to user events.
*/
export function FocusScope(props: FocusScopeProps) {
let {children, contain, restoreFocus, autoFocus} = props;
let startRef = useRef<HTMLSpanElement>();
let endRef = useRef<HTMLSpanElement>();
let scopeRef = useRef<HTMLElement[]>([]);
let ctx = useContext(FocusContext);
let parentScope = ctx?.scopeRef;
useLayoutEffect(() => {
// Find all rendered nodes between the sentinels and add them to the scope.
let node = startRef.current.nextSibling;
let nodes = [];
while (node && node !== endRef.current) {
nodes.push(node);
node = node.nextSibling;
}
scopeRef.current = nodes;
}, [children, parentScope]);
useLayoutEffect(() => {
scopes.set(scopeRef, parentScope);
return () => {
// Restore the active scope on unmount if this scope or a descendant scope is active.
// Parent effect cleanups run before children, so we need to check if the
// parent scope actually still exists before restoring the active scope to it.
if (
(scopeRef === activeScope || isAncestorScope(scopeRef, activeScope)) &&
(!parentScope || scopes.has(parentScope))
) {
activeScope = parentScope;
}
scopes.delete(scopeRef);
};
}, [scopeRef, parentScope]);
useFocusContainment(scopeRef, contain);
useRestoreFocus(scopeRef, restoreFocus, contain);
useAutoFocus(scopeRef, autoFocus);
let focusManager = createFocusManagerForScope(scopeRef);
return (
<FocusContext.Provider value={{scopeRef, focusManager}}>
<span data-focus-scope-start hidden ref={startRef} />
{children}
<span data-focus-scope-end hidden ref={endRef} />
</FocusContext.Provider>
);
}
/**
* Returns a FocusManager interface for the parent FocusScope.
* A FocusManager can be used to programmatically move focus within
* a FocusScope, e.g. in response to user events like keyboard navigation.
*/
export function useFocusManager(): FocusManager {
return useContext(FocusContext)?.focusManager;
}
function createFocusManagerForScope(scopeRef: React.RefObject<HTMLElement[]>): FocusManager {
return {
focusNext(opts: FocusManagerOptions = {}) {
let scope = scopeRef.current;
let {from, tabbable, wrap} = opts;
let node = from || document.activeElement;
let sentinel = scope[0].previousElementSibling;
let walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable}, scope);
walker.currentNode = isElementInScope(node, scope) ? node : sentinel;
let nextNode = walker.nextNode() as HTMLElement;
if (!nextNode && wrap) {
walker.currentNode = sentinel;
nextNode = walker.nextNode() as HTMLElement;
}
if (nextNode) {
focusElement(nextNode, true);
}
return nextNode;
},
focusPrevious(opts: FocusManagerOptions = {}) {
let scope = scopeRef.current;
let {from, tabbable, wrap} = opts;
let node = from || document.activeElement;
let sentinel = scope[scope.length - 1].nextElementSibling;
let walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable}, scope);
walker.currentNode = isElementInScope(node, scope) ? node : sentinel;
let previousNode = walker.previousNode() as HTMLElement;
if (!previousNode && wrap) {
walker.currentNode = sentinel;
previousNode = walker.previousNode() as HTMLElement;
}
if (previousNode) {
focusElement(previousNode, true);
}
return previousNode;
},
focusFirst(opts = {}) {
let scope = scopeRef.current;
let {tabbable} = opts;
let walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable}, scope);
walker.currentNode = scope[0].previousElementSibling;
let nextNode = walker.nextNode() as HTMLElement;
if (nextNode) {
focusElement(nextNode, true);
}
return nextNode;
},
focusLast(opts = {}) {
let scope = scopeRef.current;
let {tabbable} = opts;
let walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable}, scope);
walker.currentNode = scope[scope.length - 1].nextElementSibling;
let previousNode = walker.previousNode() as HTMLElement;
if (previousNode) {
focusElement(previousNode, true);
}
return previousNode;
}
};
}
const focusableElements = [
'input:not([disabled]):not([type=hidden])',
'select:not([disabled])',
'textarea:not([disabled])',
'button:not([disabled])',
'a[href]',
'area[href]',
'summary',
'iframe',
'object',
'embed',
'audio[controls]',
'video[controls]',
'[contenteditable]'
];
const FOCUSABLE_ELEMENT_SELECTOR = focusableElements.join(':not([hidden]),') + ',[tabindex]:not([disabled]):not([hidden])';
focusableElements.push('[tabindex]:not([tabindex="-1"]):not([disabled])');
const TABBABLE_ELEMENT_SELECTOR = focusableElements.join(':not([hidden]):not([tabindex="-1"]),');
function getScopeRoot(scope: HTMLElement[]) {
return scope[0].parentElement;
}
function useFocusContainment(scopeRef: RefObject<HTMLElement[]>, contain: boolean) {
let focusedNode = useRef<HTMLElement>();
let raf = useRef(null);
useLayoutEffect(() => {
let scope = scopeRef.current;
if (!contain) {
return;
}
// Handle the Tab key to contain focus within the scope
let onKeyDown = (e) => {
if (e.key !== 'Tab' || e.altKey || e.ctrlKey || e.metaKey || scopeRef !== activeScope) {
return;
}
let focusedElement = document.activeElement as HTMLElement;
let scope = scopeRef.current;
if (!isElementInScope(focusedElement, scope)) {
return;
}
let walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable: true}, scope);
walker.currentNode = focusedElement;
let nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as HTMLElement;
if (!nextElement) {
walker.currentNode = e.shiftKey ? scope[scope.length - 1].nextElementSibling : scope[0].previousElementSibling;
nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as HTMLElement;
}
e.preventDefault();
if (nextElement) {
focusElement(nextElement, true);
}
};
let onFocus = (e) => {
// If focusing an element in a child scope of the currently active scope, the child becomes active.
// Moving out of the active scope to an ancestor is not allowed.
if (!activeScope || isAncestorScope(activeScope, scopeRef)) {
activeScope = scopeRef;
focusedNode.current = e.target;
} else if (scopeRef === activeScope && !isElementInChildScope(e.target, scopeRef)) {
// If a focus event occurs outside the active scope (e.g. user tabs from browser location bar),
// restore focus to the previously focused node or the first tabbable element in the active scope.
if (focusedNode.current) {
focusedNode.current.focus();
} else if (activeScope) {
focusFirstInScope(activeScope.current);
}
} else if (scopeRef === activeScope) {
focusedNode.current = e.target;
}
};
let onBlur = (e) => {
// Firefox doesn't shift focus back to the Dialog properly without this
raf.current = requestAnimationFrame(() => {
// Use document.activeElement instead of e.relatedTarget so we can tell if user clicked into iframe
if (scopeRef === activeScope && !isElementInChildScope(document.activeElement, scopeRef)) {
activeScope = scopeRef;
focusedNode.current = e.target;
focusedNode.current.focus();
}
});
};
document.addEventListener('keydown', onKeyDown, false);
document.addEventListener('focusin', onFocus, false);
scope.forEach(element => element.addEventListener('focusin', onFocus, false));
scope.forEach(element => element.addEventListener('focusout', onBlur, false));
return () => {
document.removeEventListener('keydown', onKeyDown, false);
document.removeEventListener('focusin', onFocus, false);
scope.forEach(element => element.removeEventListener('focusin', onFocus, false));
scope.forEach(element => element.removeEventListener('focusout', onBlur, false));
};
}, [scopeRef, contain]);
// eslint-disable-next-line arrow-body-style
useEffect(() => {
return () => cancelAnimationFrame(raf.current);
}, [raf]);
}
function isElementInAnyScope(element: Element) {
for (let scope of scopes.keys()) {
if (isElementInScope(element, scope.current)) {
return true;
}
}
return false;
}
function isElementInScope(element: Element, scope: HTMLElement[]) {
return scope.some(node => node.contains(element));
}
function isElementInChildScope(element: Element, scope: ScopeRef) {
// node.contains in isElementInScope covers child scopes that are also DOM children,
// but does not cover child scopes in portals.
for (let s of scopes.keys()) {
if ((s === scope || isAncestorScope(scope, s)) && isElementInScope(element, s.current)) {
return true;
}
}
return false;
}
function isAncestorScope(ancestor: ScopeRef, scope: ScopeRef) {
let parent = scopes.get(scope);
if (!parent) {
return false;
}
if (parent === ancestor) {
return true;
}
return isAncestorScope(ancestor, parent);
}
function focusElement(element: HTMLElement | null, scroll = false) {
if (element != null && !scroll) {
try {
focusSafely(element);
} catch (err) {
// ignore
}
} else if (element != null) {
try {
element.focus();
} catch (err) {
// ignore
}
}
}
function focusFirstInScope(scope: HTMLElement[]) {
let sentinel = scope[0].previousElementSibling;
let walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable: true}, scope);
walker.currentNode = sentinel;
focusElement(walker.nextNode() as HTMLElement);
}
function useAutoFocus(scopeRef: RefObject<HTMLElement[]>, autoFocus: boolean) {
const autoFocusRef = React.useRef(autoFocus);
useEffect(() => {
if (autoFocusRef.current) {
activeScope = scopeRef;
if (!isElementInScope(document.activeElement, activeScope.current)) {
focusFirstInScope(scopeRef.current);
}
}
autoFocusRef.current = false;
}, []);
}
function useRestoreFocus(scopeRef: RefObject<HTMLElement[]>, restoreFocus: boolean, contain: boolean) {
// useLayoutEffect instead of useEffect so the active element is saved synchronously instead of asynchronously.
useLayoutEffect(() => {
if (!restoreFocus) {
return;
}
let scope = scopeRef.current;
let nodeToRestore = document.activeElement as HTMLElement;
// Handle the Tab key so that tabbing out of the scope goes to the next element
// after the node that had focus when the scope mounted. This is important when
// using portals for overlays, so that focus goes to the expected element when
// tabbing out of the overlay.
let onKeyDown = (e: KeyboardEvent) => {
if (e.key !== 'Tab' || e.altKey || e.ctrlKey || e.metaKey) {
return;
}
let focusedElement = document.activeElement as HTMLElement;
if (!isElementInScope(focusedElement, scope)) {
return;
}
// Create a DOM tree walker that matches all tabbable elements
let walker = getFocusableTreeWalker(document.body, {tabbable: true});
// Find the next tabbable element after the currently focused element
walker.currentNode = focusedElement;
let nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as HTMLElement;
if (!document.body.contains(nodeToRestore) || nodeToRestore === document.body) {
nodeToRestore = null;
}
// If there is no next element, or it is outside the current scope, move focus to the
// next element after the node to restore to instead.
if ((!nextElement || !isElementInScope(nextElement, scope)) && nodeToRestore) {
walker.currentNode = nodeToRestore;
// Skip over elements within the scope, in case the scope immediately follows the node to restore.
do {
nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as HTMLElement;
} while (isElementInScope(nextElement, scope));
e.preventDefault();
e.stopPropagation();
if (nextElement) {
focusElement(nextElement, true);
} else {
// If there is no next element and the nodeToRestore isn't within a FocusScope (i.e. we are leaving the top level focus scope)
// then move focus to the body.
// Otherwise restore focus to the nodeToRestore (e.g menu within a popover -> tabbing to close the menu should move focus to menu trigger)
if (!isElementInAnyScope(nodeToRestore)) {
focusedElement.blur();
} else {
focusElement(nodeToRestore, true);
}
}
}
};
if (!contain) {
document.addEventListener('keydown', onKeyDown, true);
}
return () => {
if (!contain) {
document.removeEventListener('keydown', onKeyDown, true);
}
if (restoreFocus && nodeToRestore && isElementInScope(document.activeElement, scope)) {
requestAnimationFrame(() => {
if (document.body.contains(nodeToRestore)) {
focusElement(nodeToRestore);
}
});
}
};
}, [scopeRef, restoreFocus, contain]);
}
/**
* Create a [TreeWalker]{@link https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker}
* that matches all focusable/tabbable elements.
*/
export function getFocusableTreeWalker(root: HTMLElement, opts?: FocusManagerOptions, scope?: HTMLElement[]) {
let selector = opts?.tabbable ? TABBABLE_ELEMENT_SELECTOR : FOCUSABLE_ELEMENT_SELECTOR;
let walker = document.createTreeWalker(
root,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
// Skip nodes inside the starting node.
if (opts?.from?.contains(node)) {
return NodeFilter.FILTER_REJECT;
}
if ((node as HTMLElement).matches(selector)
&& isElementVisible(node as HTMLElement)
&& (!scope || isElementInScope(node as HTMLElement, scope))) {
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_SKIP;
}
}
);
if (opts?.from) {
walker.currentNode = opts.from;
}
return walker;
}
/**
* Creates a FocusManager object that can be used to move focus within an element.
*/
export function createFocusManager(ref: RefObject<HTMLElement>): FocusManager {
return {
focusNext(opts: FocusManagerOptions = {}) {
let root = ref.current;
let {from, tabbable, wrap} = opts;
let node = from || document.activeElement;
let walker = getFocusableTreeWalker(root, {tabbable});
if (root.contains(node)) {
walker.currentNode = node;
}
let nextNode = walker.nextNode() as HTMLElement;
if (!nextNode && wrap) {
walker.currentNode = root;
nextNode = walker.nextNode() as HTMLElement;
}
if (nextNode) {
focusElement(nextNode, true);
}
return nextNode;
},
focusPrevious(opts: FocusManagerOptions = {}) {
let root = ref.current;
let {from, tabbable, wrap} = opts;
let node = from || document.activeElement;
let walker = getFocusableTreeWalker(root, {tabbable});
if (root.contains(node)) {
walker.currentNode = node;
} else {
let next = last(walker);
if (next) {
focusElement(next, true);
}
return next;
}
let previousNode = walker.previousNode() as HTMLElement;
if (!previousNode && wrap) {
walker.currentNode = root;
previousNode = last(walker);
}
if (previousNode) {
focusElement(previousNode, true);
}
return previousNode;
},
focusFirst(opts = {}) {
let root = ref.current;
let {tabbable} = opts;
let walker = getFocusableTreeWalker(root, {tabbable});
let nextNode = walker.nextNode() as HTMLElement;
if (nextNode) {
focusElement(nextNode, true);
}
return nextNode;
},
focusLast(opts = {}) {
let root = ref.current;
let {tabbable} = opts;
let walker = getFocusableTreeWalker(root, {tabbable});
let next = last(walker);
if (next) {
focusElement(next, true);
}
return next;
}
};
}
function last(walker: TreeWalker) {
let next: HTMLElement;
let last: HTMLElement;
do {
last = walker.lastChild() as HTMLElement;
if (last) {
next = last;
}
} while (last);
return next;
} | the_stack |
import { guid } from "@atomist/automation-client/lib/internal/util/string";
import { logger } from "@atomist/automation-client/lib/util/logger";
import * as fs from "fs-extra";
import * as stringify from "json-stringify-safe";
import * as _ from "lodash";
import * as os from "os";
import * as path from "path";
import { minimalClone } from "../../../api-helper/goal/minimalClone";
import {
spawnLog,
SpawnLogOptions,
SpawnLogResult,
} from "../../../api-helper/misc/child_process";
import { ExecuteGoal } from "../../../api/goal/GoalInvocation";
import { ImplementationRegistration } from "../../../api/goal/GoalWithFulfillment";
import {
Container,
ContainerInput,
ContainerOutput,
ContainerProjectHome,
ContainerRegistration,
ContainerScheduler,
GoalContainer,
GoalContainerSpec,
} from "./container";
import { prepareSecrets } from "./provider";
import {
containerEnvVars,
prepareInputAndOutput,
processResult,
} from "./util";
/**
* Extension to GoalContainer to specify additional docker options
*/
export type DockerGoalContainer = GoalContainer & { dockerOptions?: string[] };
/**
* Additional options for Docker CLI implementation of container goals.
*/
export interface DockerContainerRegistration extends ContainerRegistration {
/**
* Containers to run for this goal. The goal result is based on
* the exit status of the first element of the `containers` array.
* The other containers are considered "sidecar" containers
* provided functionality that the main container needs to
* function. The working directory of the first container is set
* to [[ContainerProjectHome]], which contains the project upon
* which the goal should operate.
*
* This extends the base containers property to be able to pass
* additional dockerOptions to a single container, eg.
* '--link=mongo:mongo'.
*/
containers: DockerGoalContainer[];
/**
* Additional Docker CLI command-line options. Command-line
* options provided here will be appended to the default set of
* options used when executing `docker run`. For example, if your
* main container must run in its default working directory, you
* can include `"--workdir="` in the `dockerOptions` array.
*/
dockerOptions?: string[];
}
export const dockerContainerScheduler: ContainerScheduler = (goal, registration: DockerContainerRegistration) => {
goal.addFulfillment({
goalExecutor: executeDockerJob(goal, registration),
...registration as ImplementationRegistration,
});
};
interface SpawnedContainer {
name: string;
promise: Promise<SpawnLogResult>;
}
/**
* Execute container goal using Docker CLI. Wait on completion of
* first container, then kill all the rest.
*/
export function executeDockerJob(goal: Container, registration: DockerContainerRegistration): ExecuteGoal {
// tslint:disable-next-line:cyclomatic-complexity
return async gi => {
const { goalEvent, progressLog, configuration } = gi;
const goalName = goalEvent.uniqueName.split("#")[0].toLowerCase();
const namePrefix = "sdm-";
const nameSuffix = `-${goalEvent.goalSetId.slice(0, 7)}-${goalName}`;
const tmpDir = path.join(dockerTmpDir(), goalEvent.repo.owner, goalEvent.repo.name, goalEvent.goalSetId);
const containerDir = path.join(tmpDir, `${namePrefix}tmp-${guid()}${nameSuffix}`);
return configuration.sdm.projectLoader.doWithProject({
...gi,
readOnly: false,
cloneDir: containerDir,
cloneOptions: minimalClone(goalEvent.push, { detachHead: true }),
},
// tslint:disable-next-line:cyclomatic-complexity
async project => {
const spec: GoalContainerSpec = {
...registration,
...(!!registration.callback ? await registration.callback(_.cloneDeep(registration), project, goal, goalEvent, gi) : {}),
};
if (!spec.containers || spec.containers.length < 1) {
throw new Error("No containers defined in GoalContainerSpec");
}
const inputDir = path.join(tmpDir, `${namePrefix}tmp-${guid()}${nameSuffix}`);
const outputDir = path.join(tmpDir, `${namePrefix}tmp-${guid()}${nameSuffix}`);
try {
await prepareInputAndOutput(inputDir, outputDir, gi);
} catch (e) {
const message = `Failed to prepare input and output for goal ${goalName}: ${e.message}`;
progressLog.write(message);
return { code: 1, message };
}
const spawnOpts = {
log: progressLog,
cwd: containerDir,
};
const network = `${namePrefix}network-${guid()}${nameSuffix}`;
let networkCreateRes: SpawnLogResult;
try {
networkCreateRes = await spawnLog("docker", ["network", "create", network], spawnOpts);
} catch (e) {
networkCreateRes = {
cmdString: `'docker' 'network' 'create' '${network}'`,
code: 128,
error: e,
output: [undefined, "", e.message],
pid: -1,
signal: undefined,
status: 128,
stdout: "",
stderr: e.message,
};
}
if (networkCreateRes.code) {
let message = `Failed to create Docker network '${network}'` +
((networkCreateRes.error) ? `: ${networkCreateRes.error.message}` : "");
progressLog.write(message);
try {
await dockerCleanup({ spawnOpts });
} catch (e) {
networkCreateRes.code++;
message += `; ${e.message}`;
}
return { code: networkCreateRes.code, message };
}
const atomistEnvs = (await containerEnvVars(gi.goalEvent, gi)).map(env => `--env=${env.name}=${env.value}`);
const spawnedContainers: SpawnedContainer[] = [];
const failures: string[] = [];
for (const container of spec.containers) {
let secrets = {
env: [],
files: [],
};
try {
secrets = await prepareSecrets(container, gi);
if (!!secrets?.files) {
const secretPath = path.join(inputDir, ".secrets");
await fs.ensureDir(secretPath);
for (const file of secrets.files) {
const secretFile = path.join(secretPath, guid());
file.hostPath = secretFile;
await fs.writeFile(secretFile, file.value);
}
}
} catch (e) {
failures.push(e.message);
}
const containerName = `${namePrefix}${container.name}${nameSuffix}`;
let containerArgs: string[];
try {
containerArgs = containerDockerOptions(container, registration);
} catch (e) {
progressLog.write(e.message);
failures.push(e.message);
break;
}
const dockerArgs = [
"run",
"--tty",
"--rm",
`--name=${containerName}`,
`--volume=${containerDir}:${ContainerProjectHome}`,
`--volume=${inputDir}:${ContainerInput}`,
`--volume=${outputDir}:${ContainerOutput}`,
...secrets.files.map(f => `--volume=${f.hostPath}:${f.mountPath}`),
`--network=${network}`,
`--network-alias=${container.name}`,
...containerArgs,
...(registration.dockerOptions || []),
...((container as DockerGoalContainer).dockerOptions || []),
...atomistEnvs,
...secrets.env.map(e => `--env=${e.name}=${e.value}`),
container.image,
...(container.args || []),
];
if (spawnedContainers.length < 1) {
dockerArgs.splice(5, 0, `--workdir=${ContainerProjectHome}`);
}
const promise = spawnLog("docker", dockerArgs, spawnOpts);
spawnedContainers.push({ name: containerName, promise });
}
if (failures.length > 0) {
try {
await dockerCleanup({
network,
spawnOpts,
containers: spawnedContainers,
});
} catch (e) {
failures.push(e.message);
}
return {
code: failures.length,
message: `Failed to spawn Docker containers: ${failures.join("; ")}`,
};
}
const main = spawnedContainers[0];
try {
const result = await main.promise;
if (result.code) {
const msg = `Docker container '${main.name}' failed` + ((result.error) ? `: ${result.error.message}` : "");
progressLog.write(msg);
failures.push(msg);
}
} catch (e) {
const message = `Failed to execute main Docker container '${main.name}': ${e.message}`;
progressLog.write(message);
failures.push(message);
}
const outputFile = path.join(outputDir, "result.json");
let outputResult;
if ((await fs.pathExists(outputFile)) && failures.length === 0) {
try {
outputResult = await processResult(await fs.readJson(outputFile), gi);
} catch (e) {
const message = `Failed to read output from Docker container '${main.name}': ${e.message}`;
progressLog.write(message);
failures.push(message);
}
}
const sidecars = spawnedContainers.slice(1);
try {
await dockerCleanup({
network,
spawnOpts,
containers: sidecars,
});
} catch (e) {
failures.push(e.message);
}
if (failures.length === 0 && !!outputResult) {
return outputResult;
} else {
return {
code: failures.length,
message: (failures.length > 0) ? failures.join("; ") : "Successfully completed container job",
};
}
});
};
}
/**
* Generate container specific Docker command-line options.
*
* @param container Goal container spec
* @param registration Container goal registration object
* @return Docker command-line entrypoint, env, p, and volume options
*/
export function containerDockerOptions(container: GoalContainer, registration: ContainerRegistration): string[] {
const entryPoint: string[] = [];
if (container.command && container.command.length > 0) {
// Docker CLI entrypoint must be a binary...
entryPoint.push(`--entrypoint=${container.command[0]}`);
// ...so prepend any other command elements to args array
if (container.args) {
container.args.splice(0, 0, ...container.command.slice(1));
} else {
container.args = container.command.slice(1);
}
}
const envs = (container.env || []).map(env => `--env=${env.name}=${env.value}`);
const ports = (container.ports || []).map(port => `-p=${port.containerPort}`);
const volumes: string[] = [];
for (const vm of (container.volumeMounts || [])) {
const volume = (registration.volumes || []).find(v => v.name === vm.name);
if (!volume) {
const msg = `Container '${container.name}' references volume '${vm.name}' which not provided in goal registration ` +
`volumes: ${stringify(registration.volumes)}`;
logger.error(msg);
throw new Error(msg);
}
volumes.push(`--volume=${volume.hostPath.path}:${vm.mountPath}`);
}
return [
...entryPoint,
...envs,
...ports,
...volumes,
];
}
/**
* Use a temporary under the home directory so Docker can use it as a
* volume mount.
*/
export function dockerTmpDir(): string {
return path.join(os.homedir(), ".atomist", "tmp");
}
/**
* Docker elements to cleanup after execution.
*/
interface CleanupOptions {
/**
* Options to use when calling spawnLog. Also provides the
* progress log.
*/
spawnOpts: SpawnLogOptions;
/** Containers to kill by name, if provided. */
containers?: SpawnedContainer[];
/**
* Name of Docker network created for this goal execution. If
* provided, it will be removed.
*/
network?: string;
}
/**
* Kill running Docker containers, then delete network, and
* remove directory container directory. If the copy fails, it throws
* an error. Other errors are logged and ignored.
*
* @param opts See [[CleanupOptions]]
*/
async function dockerCleanup(opts: CleanupOptions): Promise<void> {
if (opts.containers) {
await dockerKill(opts.containers, opts.spawnOpts);
}
if (opts.network) {
const networkDeleteRes = await spawnLog("docker", ["network", "rm", opts.network], opts.spawnOpts);
if (networkDeleteRes.code) {
const msg = `Failed to delete Docker network '${opts.network}'` +
((networkDeleteRes.error) ? `: ${networkDeleteRes.error.message}` : "");
opts.spawnOpts.log.write(msg);
}
}
}
/**
* Kill Docker containers. Any errors are caught and logged, but not
* re-thrown.
*
* @param containers Containers to kill, they will be killed by name
* @param opts Options to use when calling spawnLog
*/
async function dockerKill(containers: SpawnedContainer[], opts: SpawnLogOptions): Promise<void> {
try {
const killPromises: Array<Promise<SpawnLogResult>> = [];
for (const container of containers) {
killPromises.push(spawnLog("docker", ["kill", container.name], opts));
}
await Promise.all(killPromises);
} catch (e) {
const message = `Failed to kill Docker containers: ${e.message}`;
opts.log.write(message);
}
} | the_stack |
import React, { Fragment } from 'react';
import { DocumentNode, GraphQLError } from 'graphql';
import gql from 'graphql-tag';
import { act } from 'react-dom/test-utils';
import { render, waitFor } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';
import {
ApolloClient,
ApolloError,
NetworkStatus,
TypedDocumentNode,
WatchQueryFetchPolicy,
} from '../../../core';
import { InMemoryCache } from '../../../cache';
import { ApolloProvider } from '../../context';
import { Observable, Reference, concatPagination } from '../../../utilities';
import { ApolloLink } from '../../../link/core';
import { itAsync, MockLink, MockedProvider, mockSingleLink } from '../../../testing';
import { useQuery } from '../useQuery';
import { useMutation } from '../useMutation';
describe('useQuery Hook', () => {
describe('General use', () => {
it('should handle a simple query', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: "world" } },
},
];
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world" });
});
it('should read and write results from the cache', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: "world" } },
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, rerender, waitForNextUpdate } = renderHook(
() => useQuery(query),
{ wrapper }
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world" });
rerender();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world" });
});
it('should preserve functions between renders', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: "world" } },
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query),
{ wrapper },
);
expect(result.current.loading).toBe(true);
const {
refetch,
fetchMore,
startPolling,
stopPolling,
subscribeToMore,
} = result.current;
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(refetch).toBe(result.current.refetch);
expect(fetchMore).toBe(result.current.fetchMore);
expect(startPolling).toBe(result.current.startPolling);
expect(stopPolling).toBe(result.current.stopPolling);
expect(subscribeToMore).toBe(result.current.subscribeToMore);
});
it('should set called to true by default', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: "world" } },
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, unmount } = renderHook(
() => useQuery(query),
{ wrapper },
);
expect(result.current.called).toBe(true);
unmount();
});
it('should work with variables', async () => {
const query = gql`
query ($id: Int) {
hello(id: $id)
}
`;
const mocks = [
{
request: { query, variables: { id: 1 } },
result: { data: { hello: "world 1" } },
},
{
request: { query, variables: { id: 2 } },
result: { data: { hello: "world 2" } },
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, rerender, waitForNextUpdate } = renderHook(
({ id }) => useQuery(query, { variables: { id }}),
{ wrapper, initialProps: { id: 1 } },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 1" });
rerender({ id: 2 });
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 2" });
});
it('should return the same results for the same variables', async () => {
const query = gql`
query ($id: Int) {
hello(id: $id)
}
`;
const mocks = [
{
request: { query, variables: { id: 1 } },
result: { data: { hello: "world 1" } },
},
{
request: { query, variables: { id: 2 } },
result: { data: { hello: "world 2" } },
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, rerender, waitForNextUpdate } = renderHook(
({ id }) => useQuery(query, { variables: { id } }),
{ wrapper, initialProps: { id: 1 } },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 1" });
rerender({ id: 2 });
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 2" });
rerender({ id: 2 });
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 2" });
});
it('should work with variables 2', async () => {
const query = gql`
query ($name: String) {
names(name: $name)
}
`;
const mocks = [
{
request: { query, variables: { name: "" } },
result: { data: { names: ["Alice", "Bob", "Eve"] } },
},
{
request: { query, variables: { name: "z" } },
result: { data: { names: [] } },
},
{
request: { query, variables: { name: "zz" } },
result: { data: { names: [] } },
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, rerender, waitForNextUpdate } = renderHook(
({ name }) => useQuery(query, { variables: { name } }),
{ wrapper, initialProps: { name: "" } },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ names: ["Alice", "Bob", "Eve"] });
rerender({ name: 'z' });
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ names: [] });
rerender({ name: 'zz' });
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ names: [] });
});
// An unsuccessful attempt to reproduce https://github.com/apollographql/apollo-client/issues/9135.
it('should not return stale variables when stored in state', async () => {
const query = gql`
query myQuery($name: String) {
hello(name: $name)
}
`;
const mutation = gql`
mutation myMutation($name: String) {
updateName(name: $name)
}
`;
const mocks = [
{
request: { query, variables: { name: "world 1" } },
result: { data: { hello: "world 1" } },
},
{
request: { query: mutation, variables: { name: "world 2" } },
result: { data: { updateName: true } },
},
{
request: { query, variables: { name: "world 2" } },
result: { data: { hello: "world 2" } },
},
];
const cache = new InMemoryCache();
let setName: any;
const { result, waitForNextUpdate } = renderHook(
() => {
const [name, setName1] = React.useState("world 1");
setName = setName1;
return [
useQuery(query, { variables: { name }}),
useMutation(mutation, {
update(cache, { data }) {
cache.writeQuery({
query,
data: { hello: data.updateGreeting },
});
},
}),
] as const;
},
{
wrapper: ({ children }) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
),
},
);
expect(result.current[0].loading).toBe(true);
expect(result.current[0].data).toBe(undefined);
expect(result.current[0].variables).toEqual({ name: "world 1" });
await waitForNextUpdate();
expect(result.current[0].loading).toBe(false);
expect(result.current[0].data).toEqual({ hello: "world 1" });
expect(result.current[0].variables).toEqual({ name: "world 1" });
const mutate = result.current[1][0];
act(() => {
mutate({ variables: { name: "world 2" } });
setName("world 2");
});
expect(result.current[0].loading).toBe(true);
expect(result.current[0].data).toBe(undefined);
expect(result.current[0].variables).toEqual({ name: "world 2" });
await waitForNextUpdate();
expect(result.current[0].loading).toBe(false);
expect(result.current[0].data).toEqual({ hello: "world 2" });
expect(result.current[0].variables).toEqual({ name: "world 2" });
});
// TODO: Rewrite this test
itAsync('should not error when forcing an update with React >= 16.13.0', (resolve, reject) => {
const CAR_QUERY: DocumentNode = gql`
query {
cars {
make
model
vin
}
}
`;
const CAR_RESULT_DATA = {
cars: [
{
make: 'Audi',
model: 'RS8',
vin: 'DOLLADOLLABILL',
__typename: 'Car'
}
]
};
let wasUpdateErrorLogged = false;
const consoleError = console.error;
console.error = (msg: string) => {
console.log(msg);
wasUpdateErrorLogged = msg.indexOf('Cannot update a component') > -1;
};
const CAR_MOCKS = [1, 2, 3, 4, 5, 6].map(something => ({
request: {
query: CAR_QUERY,
variables: { something }
},
result: { data: CAR_RESULT_DATA },
}));
let renderCount = 0;
const InnerComponent = ({ something }: any) => {
const { loading, data } = useQuery(CAR_QUERY, {
fetchPolicy: 'network-only',
variables: { something }
});
renderCount += 1;
if (loading) return null;
expect(wasUpdateErrorLogged).toBeFalsy();
expect(data).toEqual(CAR_RESULT_DATA);
return null;
};
function WrapperComponent({ something }: any) {
const { loading } = useQuery(CAR_QUERY, {
variables: { something }
});
return loading ? null : <InnerComponent something={something + 1} />;
}
render(
<MockedProvider link={new MockLink(CAR_MOCKS).setOnError(reject)}>
<Fragment>
<WrapperComponent something={1} />
<WrapperComponent something={3} />
<WrapperComponent something={5} />
</Fragment>
</MockedProvider>
);
waitFor(() => {
expect(renderCount).toBe(6);
}).finally(() => {
console.error = consoleError;
}).then(resolve, reject);
});
it('should tear down the query on unmount', async () => {
const query = gql`{ hello }`;
const client = new ApolloClient({
link: new ApolloLink(() => Observable.of({ data: { hello: 'world' } })),
cache: new InMemoryCache(),
});
const wrapper = ({ children }: any) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
);
const { unmount } = renderHook(
() => useQuery(query),
{ wrapper },
);
expect(client.getObservableQueries().size).toBe(1);
unmount();
expect(client.getObservableQueries().size).toBe(0);
});
it('should work with ssr: false', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: "world" } },
},
];
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { ssr: false }),
{
wrapper: ({ children }) => (
<MockedProvider mocks={mocks}>{children}</MockedProvider>
),
},
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world" });
});
it('should keep `no-cache` results when the tree is re-rendered', async () => {
const query1 = gql`
query people {
allPeople(first: 1) {
people {
name
}
}
}
`;
const query2 = gql`
query Things {
allThings {
thing {
description
}
}
}
`;
const allPeopleData = {
allPeople: { people: [{ name: 'Luke Skywalker' }] },
};
const allThingsData = {
allThings: {
thing: [{ description: 'Thing 1' }, { description: 'Thing 2' }],
},
};
const link = mockSingleLink(
{
request: { query: query1 },
result: { data: allPeopleData },
},
{
request: { query: query2 },
result: { data: allThingsData },
delay: 50,
},
);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
const { result, rerender, waitForNextUpdate } = renderHook(
() => [
useQuery(query1, { fetchPolicy: "no-cache" }),
useQuery(query2),
],
{
wrapper: ({ children }) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
),
},
);
expect(result.current[0].loading).toBe(true);
expect(result.current[0].data).toBe(undefined);
expect(result.current[1].loading).toBe(true);
expect(result.current[1].data).toBe(undefined);
await waitForNextUpdate();
expect(result.current[0].loading).toBe(false);
expect(result.current[0].data).toEqual(allPeopleData);
expect(result.current[1].loading).toBe(true);
expect(result.current[1].data).toBe(undefined);
await waitForNextUpdate();
expect(result.current[0].loading).toBe(false);
expect(result.current[0].data).toEqual(allPeopleData);
expect(result.current[1].loading).toBe(false);
expect(result.current[1].data).toEqual(allThingsData);
rerender();
expect(result.current[0].loading).toBe(false);
expect(result.current[0].data).toEqual(allPeopleData);
expect(result.current[1].loading).toBe(false);
expect(result.current[1].data).toEqual(allThingsData);
});
it('changing queries', async () => {
const query1 = gql`query { hello }`;
const query2 = gql`query { hello, name }`;
const mocks = [
{
request: { query: query1 },
result: { data: { hello: "world" } },
},
{
request: { query: query2 },
result: { data: { hello: "world", name: "world" } },
},
];
const cache = new InMemoryCache();
const { result, rerender, waitForNextUpdate } = renderHook(
({ query }) => useQuery(query, { pollInterval: 10 }),
{
wrapper: ({ children }) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
),
initialProps: { query: query1 },
},
);
expect(result.current.loading).toBe(true);
rerender({ query: query2 });
expect(result.current.loading).toBe(true);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual(mocks[1].result.data);
});
it('`cache-and-network` fetch policy', async () => {
const query = gql`{ hello }`;
const cache = new InMemoryCache();
const link = mockSingleLink(
{
request: { query },
result: { data: { hello: 'from link' } },
delay: 20,
},
);
const client = new ApolloClient({
link,
cache,
});
cache.writeQuery({ query, data: { hello: 'from cache' }});
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { fetchPolicy: 'cache-and-network' }),
{
wrapper: ({ children }) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
),
},
);
// TODO: FIXME
expect(result.current.loading).toBe(true);
expect(result.current.data).toEqual({ hello: 'from cache' });
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'from link' });
});
it('should not use the cache when using `network-only`', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: 'from link' } },
},
];
const cache = new InMemoryCache();
cache.writeQuery({
query,
data: { hello: 'from cache' },
});
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { fetchPolicy: 'network-only' }),
{
wrapper: ({ children }) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
),
},
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBeUndefined();
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'from link' });
});
it('should use the cache when in ssrMode and fetchPolicy is `network-only`', async () => {
const query = gql`query { hello }`;
const link = mockSingleLink(
{
request: { query },
result: { data: { hello: 'from link' } },
},
);
const cache = new InMemoryCache();
cache.writeQuery({
query,
data: { hello: 'from cache' },
});
const client = new ApolloClient({ link, cache, ssrMode: true, });
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { fetchPolicy: 'network-only' }),
{
wrapper: ({ children }) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
),
},
);
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'from cache' });
await expect(waitForNextUpdate({ timeout: 20 }))
.rejects.toThrow('Timed out');
});
it('should not hang when ssrMode is true but the cache is not populated for some reason', async () => {
const query = gql`query { hello }`;
const link = mockSingleLink(
{
request: { query },
result: { data: { hello: 'from link' } },
},
);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
ssrMode: true,
});
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query),
{
wrapper: ({ children }) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
),
},
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBeUndefined();
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'from link' });
});
});
describe('polling', () => {
it('should support polling', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: "world 1" } },
},
{
request: { query },
result: { data: { hello: "world 2" } },
},
{
request: { query },
result: { data: { hello: "world 3" } },
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { pollInterval: 10 }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 1" });
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 2" });
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 3" });
result.current.stopPolling();
await expect(waitForNextUpdate({ timeout: 20 })).rejects.toThrow('Timed out');
});
it('should start polling when skip goes from true to false', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: "world 1" } },
delay: 10,
},
{
request: { query },
result: { data: { hello: "world 2" } },
delay: 10,
},
{
request: { query },
result: { data: { hello: "world 3" } },
delay: 10,
},
];
const cache = new InMemoryCache();
const { result, rerender, waitForNextUpdate } = renderHook(
({ skip }) => useQuery(query, { pollInterval: 10, skip }),
{
wrapper: ({ children }) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
),
initialProps: { skip: undefined } as any
},
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 1" });
rerender({ skip: true });
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
await expect(waitForNextUpdate({ timeout: 20 })).rejects.toThrow('Timed out');
rerender({ skip: false });
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 1" });
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 2" });
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 3" });
});
it('should stop polling when component unmounts', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: "world 1" } },
},
{
request: { query },
result: { data: { hello: "world 2" } },
},
{
request: { query },
result: { data: { hello: "world 3" } },
},
];
const cache = new InMemoryCache();
const link = new MockLink(mocks);
const requestSpy = jest.spyOn(link, 'request');
const onErrorFn = jest.fn();
link.setOnError(onErrorFn);
const wrapper = ({ children }: any) => (
<MockedProvider link={link} cache={cache}>{children}</MockedProvider>
);
const { result, waitForNextUpdate, unmount } = renderHook(
() => useQuery(query, { pollInterval: 10 }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 1" });
unmount();
await expect(waitForNextUpdate({ timeout: 20 })).rejects.toThrow('Timed out');
expect(requestSpy).toHaveBeenCalledTimes(1);
expect(onErrorFn).toHaveBeenCalledTimes(0);
});
it('should stop polling when component is unmounted in Strict Mode', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: "world 1" } },
delay: 10,
},
{
request: { query },
result: { data: { hello: "world 2" } },
delay: 10,
},
{
request: { query },
result: { data: { hello: "world 3" } },
delay: 10,
},
];
const cache = new InMemoryCache();
const link = new MockLink(mocks);
const requestSpy = jest.spyOn(link, 'request');
const onErrorFn = jest.fn();
link.setOnError(onErrorFn);
const wrapper = ({ children }: any) => (
<React.StrictMode>
<MockedProvider link={link} cache={cache}>{children}</MockedProvider>
</React.StrictMode>
);
const { result, waitForNextUpdate, unmount } = renderHook(
() => useQuery(query, { pollInterval: 10 }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 1" });
unmount();
await expect(waitForNextUpdate({ timeout: 20 })).rejects.toThrow('Timed out');
expect(requestSpy).toHaveBeenCalledTimes(1);
expect(onErrorFn).toHaveBeenCalledTimes(0);
});
it('should start and stop polling in Strict Mode', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: "world 1" } },
},
{
request: { query },
result: { data: { hello: "world 2" } },
},
];
const cache = new InMemoryCache();
const link = new MockLink(mocks);
const requestSpy = jest.spyOn(link, 'request');
const onErrorFn = jest.fn();
link.setOnError(onErrorFn);
const wrapper = ({ children }: any) => (
<React.StrictMode>
<MockedProvider link={link} cache={cache}>{children}</MockedProvider>
</React.StrictMode>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { pollInterval: 20 }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 1" });
result.current.stopPolling();
const nextUpdate = waitForNextUpdate();
await expect(waitForNextUpdate({ timeout: 20 })).rejects.toThrow('Timed out');
result.current.startPolling(20);
expect(requestSpy).toHaveBeenCalledTimes(1);
expect(onErrorFn).toHaveBeenCalledTimes(0);
await nextUpdate;
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: "world 2" });
expect(requestSpy).toHaveBeenCalledTimes(2);
expect(onErrorFn).toHaveBeenCalledTimes(0);
});
it('should not throw an error if stopPolling is called manually', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: {
data: { hello: 'world' },
}
}
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, waitForNextUpdate, unmount } = renderHook(
() => useQuery(query),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world' });
unmount();
result.current.stopPolling();
});
});
describe('Error handling', () => {
it('should pass along GraphQL errors', async () => {
const query = gql`
query TestQuery {
rates(currency: "USD") {
rate
}
}
`;
const mocks = [
{
request: { query },
result: {
errors: [new GraphQLError('error')]
}
}
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('error');
});
it('should only call onError callbacks once', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: {
errors: [new GraphQLError('error')],
},
},
{
request: { query },
result: {
data: { hello: 'world' },
},
delay: 10,
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const onError = jest.fn();
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
onError,
notifyOnNetworkStatusChange: true,
}),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('error');
await new Promise((resolve) => setTimeout(resolve));
expect(onError).toHaveBeenCalledTimes(1);
result.current.refetch();
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world' });
expect(onError).toHaveBeenCalledTimes(1);
});
it('should persist errors on re-render if they are still valid', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: {
errors: [new GraphQLError('error')]
}
}
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, rerender, waitForNextUpdate } = renderHook(
() => useQuery(query),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('error');
rerender();
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('error');
await expect(waitForNextUpdate({ timeout: 20 })).rejects.toThrow('Timed out');
});
it('should persist errors on re-render with inline onError/onCompleted callbacks', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: {
errors: [new GraphQLError('error')]
}
}
];
const cache = new InMemoryCache();
const link = new MockLink(mocks);
const onErrorFn = jest.fn();
link.setOnError(onErrorFn);
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} link={link} cache={cache}>
{children}
</MockedProvider>
);
const { result, rerender, waitForNextUpdate } = renderHook(
() => useQuery(query, { onError: () => {}, onCompleted: () => {} }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('error');
rerender();
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('error');
expect(onErrorFn).toHaveBeenCalledTimes(0);
await expect(waitForNextUpdate({ timeout: 20 })).rejects.toThrow('Timed out');
});
it('should not persist errors when variables change', async () => {
const query = gql`
query hello($id: ID) {
hello(id: $id)
}
`;
const mocks = [
{
request: {
query,
variables: { id: 1 },
},
result: {
errors: [new GraphQLError('error')]
},
},
{
request: {
query,
variables: { id: 2 },
},
result: {
data: { hello: 'world 2' },
},
},
{
request: {
query,
variables: { id: 1 },
},
result: {
data: { hello: 'world 1' },
},
},
];
const { result, rerender, waitForNextUpdate } = renderHook(
({ id }) => useQuery(query, { variables: { id } }),
{
wrapper: ({ children }) => (
<MockedProvider mocks={mocks}>
{children}
</MockedProvider>
),
initialProps: { id: 1 },
},
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('error');
rerender({ id: 2 });
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world 2' });
expect(result.current.error).toBe(undefined);
rerender({ id: 1 });
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world 1' });
expect(result.current.error).toBe(undefined);
});
it('should render multiple errors when refetching', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: {
errors: [new GraphQLError('error 1')]
}
},
{
request: { query },
result: {
errors: [new GraphQLError('error 2')]
},
delay: 10,
}
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { notifyOnNetworkStatusChange: true }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('error 1');
const catchFn = jest.fn();
result.current.refetch().catch(catchFn);
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('error 2');
expect(catchFn.mock.calls.length).toBe(1);
expect(catchFn.mock.calls[0].length).toBe(1);
expect(catchFn.mock.calls[0][0]).toBeInstanceOf(ApolloError);
expect(catchFn.mock.calls[0][0].message).toBe('error 2');
});
it('should render the same error on refetch', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: {
errors: [new GraphQLError('same error')]
}
},
{
request: { query },
result: {
errors: [new GraphQLError('same error')]
}
}
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { notifyOnNetworkStatusChange: true }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('same error');
const catchFn = jest.fn();
await act(async () => {
await result.current.refetch().catch(catchFn);
});
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('same error');
expect(catchFn.mock.calls.length).toBe(1);
expect(catchFn.mock.calls[0].length).toBe(1);
expect(catchFn.mock.calls[0][0]).toBeInstanceOf(ApolloError);
expect(catchFn.mock.calls[0][0].message).toBe('same error');
});
it('should render data and errors with refetch', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: {
errors: [new GraphQLError('same error')],
},
},
{
request: { query },
result: {
data: { hello: 'world' },
},
delay: 10,
},
{
request: { query },
result: {
errors: [new GraphQLError('same error')],
},
delay: 10,
}
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { notifyOnNetworkStatusChange: true }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('same error');
result.current.refetch();
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world' });
expect(result.current.error).toBe(undefined);
const catchFn = jest.fn();
result.current.refetch().catch(catchFn);
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.data).toEqual({ hello: 'world' });
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
// TODO: Is this correct behavior here?
expect(result.current.data).toEqual({ hello: 'world' });
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.error!.message).toBe('same error');
expect(catchFn.mock.calls.length).toBe(1);
expect(catchFn.mock.calls[0].length).toBe(1);
expect(catchFn.mock.calls[0][0]).toBeInstanceOf(ApolloError);
expect(catchFn.mock.calls[0][0].message).toBe('same error');
});
it('should call onCompleted when variables change', async () => {
const query = gql`
query people($first: Int) {
allPeople(first: $first) {
people {
name
}
}
}
`;
const data1 = { allPeople: { people: [{ name: 'Luke Skywalker' }] } };
const data2 = { allPeople: { people: [{ name: 'Han Solo' }] } };
const mocks = [
{
request: { query, variables: { first: 1 } },
result: { data: data1 },
},
{
request: { query, variables: { first: 2 } },
result: { data: data2 },
},
];
const onCompleted = jest.fn();
const { result, rerender, waitForNextUpdate } = renderHook(
({ variables }) => useQuery(query, { variables, onCompleted }),
{
wrapper: ({ children }) => (
<MockedProvider mocks={mocks}>
{children}
</MockedProvider>
),
initialProps: {
variables: { first: 1 },
},
},
);
expect(result.current.loading).toBe(true);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual(data1);
rerender({ variables: { first: 2 } });
expect(result.current.loading).toBe(true);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual(data2);
rerender({ variables: { first: 1 } });
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual(data1);
expect(onCompleted).toHaveBeenCalledTimes(3);
});
});
describe('Pagination', () => {
const query = gql`
query letters($limit: Int) {
letters(limit: $limit) {
name
position
}
}
`;
const ab = [
{ name: 'A', position: 1 },
{ name: 'B', position: 2 },
];
const cd = [
{ name: 'C', position: 3 },
{ name: 'D', position: 4 },
];
const mocks = [
{
request: { query, variables: { limit: 2 } },
result: {
data: {
letters: ab,
},
},
},
{
request: { query, variables: { limit: 2 } },
result: {
data: {
letters: cd,
},
},
delay: 10,
},
];
it('should fetchMore with updateQuery', async () => {
// TODO: Calling fetchMore with an updateQuery callback is deprecated
const warnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { variables: { limit: 2 } }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.networkStatus).toBe(NetworkStatus.loading);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
expect(result.current.data).toEqual({ letters: ab });
act(() => void result.current.fetchMore({
variables: { limit: 2 },
updateQuery: (prev, { fetchMoreResult }) => ({
letters: prev.letters.concat(fetchMoreResult.letters),
}),
}));
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
expect(result.current.data).toEqual({ letters: ab.concat(cd) });
warnSpy.mockRestore();
});
it('should fetchMore with updateQuery and notifyOnNetworkStatusChange', async () => {
// TODO: Calling fetchMore with an updateQuery callback is deprecated
const warnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
variables: { limit: 2 },
notifyOnNetworkStatusChange: true,
}),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.networkStatus).toBe(NetworkStatus.loading);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
expect(result.current.data).toEqual({ letters: ab });
act(() => void result.current.fetchMore({
variables: { limit: 2 },
updateQuery: (prev, { fetchMoreResult }) => ({
letters: prev.letters.concat(fetchMoreResult.letters),
}),
}));
expect(result.current.loading).toBe(true);
expect(result.current.networkStatus).toBe(NetworkStatus.fetchMore);
expect(result.current.data).toEqual({ letters: ab });
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
expect(result.current.data).toEqual({ letters: ab.concat(cd) });
warnSpy.mockRestore();
});
it('fetchMore with concatPagination', async () => {
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
letters: concatPagination(),
},
},
},
});
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { variables: { limit: 2 } }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.networkStatus).toBe(NetworkStatus.loading);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
expect(result.current.data).toEqual({ letters: ab });
result.current.fetchMore({ variables: { limit: 2 } });
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
expect(result.current.data).toEqual({ letters: ab.concat(cd) });
});
it('fetchMore with concatPagination and notifyOnNetworkStatusChange', async () => {
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
letters: concatPagination(),
},
},
},
});
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
variables: { limit: 2 },
notifyOnNetworkStatusChange: true,
}),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.networkStatus).toBe(NetworkStatus.loading);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
expect(result.current.data).toEqual({ letters: ab });
act(() => void result.current.fetchMore({ variables: { limit: 2 } }));
expect(result.current.loading).toBe(true);
expect(result.current.networkStatus).toBe(NetworkStatus.fetchMore);
expect(result.current.data).toEqual({ letters: ab });
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
expect(result.current.data).toEqual({ letters: ab.concat(cd) });
});
it("regression test for issue #8600", async () => {
const cache = new InMemoryCache({
typePolicies: {
Country: {
fields: {
cities: {
keyArgs: ['size'],
merge(existing, incoming, { args }) {
if (!args) return incoming
const items = existing ? existing.slice(0) : []
const offset = args.offset ?? 0
for (let i = 0; i < incoming.length; ++i) {
items[offset + i] = incoming[i]
}
return items
},
},
},
},
CityInfo: {
merge: true,
},
},
});
const GET_COUNTRIES = gql`
query GetCountries {
countries {
id
...WithSmallCities
...WithAirQuality
}
}
fragment WithSmallCities on Country {
biggestCity {
id
}
smallCities: cities(size: SMALL) {
id
}
}
fragment WithAirQuality on Country {
biggestCity {
id
info {
airQuality
}
}
}
`;
const countries = [
{
__typename: 'Country',
id: 123,
biggestCity: {
__typename: 'City',
id: 234,
info: {
__typename: 'CityInfo',
airQuality: 0,
},
},
smallCities: [
{ __typename: 'City', id: 345 },
],
},
];
const wrapper = ({ children }: any) => (
<MockedProvider mocks={[
{
request: { query: GET_COUNTRIES },
result: { data: { countries } },
},
]} cache={cache}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(GET_COUNTRIES),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBeUndefined();
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ countries });
});
});
describe('Refetching', () => {
it('refetching with different variables', async () => {
const query = gql`
query ($id: Int) {
hello(id: $id)
}
`;
const mocks = [
{
request: { query, variables: { id: 1 } },
result: { data: { hello: 'world 1' } },
},
{
request: { query, variables: { id: 2 } },
result: { data: { hello: 'world 2' } },
delay: 10,
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
variables: { id: 1 },
notifyOnNetworkStatusChange: true,
}),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world 1' });
result.current.refetch({ id: 2 });
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world 2' });
});
it('refetching after an error', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: 'world 1' } },
},
{
request: { query },
error: new Error('This is an error!'),
delay: 10,
},
{
request: { query },
result: { data: { hello: 'world 2' } },
delay: 10,
},
];
const cache = new InMemoryCache();
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
notifyOnNetworkStatusChange: true,
}),
{
wrapper: ({ children }) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
),
},
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toEqual({ hello: 'world 1' });
result.current.refetch();
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toEqual({ hello: 'world 1' });
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBeInstanceOf(ApolloError);
expect(result.current.data).toEqual({ hello: 'world 1' });
result.current.refetch();
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toEqual({ hello: 'world 1' });
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toEqual({ hello: 'world 2' });
});
describe('refetchWritePolicy', () => {
const query = gql`
query GetPrimes ($min: number, $max: number) {
primes(min: $min, max: $max)
}
`;
const mocks = [
{
request: {
query,
variables: { min: 0, max: 12 },
},
result: {
data: {
primes: [2, 3, 5, 7, 11],
}
}
},
{
request: {
query,
variables: { min: 12, max: 30 },
},
result: {
data: {
primes: [13, 17, 19, 23, 29],
}
},
delay: 10,
},
];
it('should support explicit "overwrite"', async () => {
const mergeParams: [any, any][] = [];
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
primes: {
keyArgs: false,
merge(existing, incoming) {
mergeParams.push([existing, incoming]);
return existing ? existing.concat(incoming) : incoming;
},
},
},
},
},
});
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
variables: { min: 0, max: 12 },
notifyOnNetworkStatusChange: true,
// This is the key line in this test.
refetchWritePolicy: 'overwrite',
}),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toBe(undefined);
expect(typeof result.current.refetch).toBe('function');
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBeUndefined();
expect(result.current.data).toEqual({ primes: [2, 3, 5, 7, 11] });
expect(mergeParams).toEqual([
[void 0, [2, 3, 5, 7, 11]],
]);
const thenFn = jest.fn();
result.current.refetch({ min: 12, max: 30 }).then(thenFn);
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toEqual({
// We get the stale data because we configured keyArgs: false.
primes: [2, 3, 5, 7, 11],
});
// This networkStatus is setVariables instead of refetch because we
// called refetch with new variables.
expect(result.current.networkStatus).toBe(NetworkStatus.setVariables);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toEqual({ primes: [13, 17, 19, 23, 29] });
expect(mergeParams).toEqual([
[undefined, [2, 3, 5, 7, 11]],
// Without refetchWritePolicy: "overwrite", this array will be
// all 10 primes (2 through 29) together.
[undefined, [13, 17, 19, 23, 29]],
]);
expect(thenFn).toHaveBeenCalledTimes(1);
expect(thenFn).toHaveBeenCalledWith({
loading: false,
networkStatus: NetworkStatus.ready,
data: { primes: [13, 17, 19, 23, 29] },
});
});
it('should support explicit "merge"', async () => {
const mergeParams: [any, any][] = [];
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
primes: {
keyArgs: false,
merge(existing, incoming) {
mergeParams.push([existing, incoming]);
return existing ? [...existing, ...incoming] : incoming;
},
},
},
},
},
});
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
variables: { min: 0, max: 12 },
notifyOnNetworkStatusChange: true,
// This is the key line in this test.
refetchWritePolicy: 'merge',
}),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toBe(undefined);
expect(typeof result.current.refetch).toBe('function');
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBeUndefined();
expect(result.current.data).toEqual({ primes: [2, 3, 5, 7, 11] });
expect(mergeParams).toEqual([
[undefined, [2, 3, 5, 7, 11]],
]);
const thenFn = jest.fn();
result.current.refetch({ min: 12, max: 30 }).then(thenFn);
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toEqual({
// We get the stale data because we configured keyArgs: false.
primes: [2, 3, 5, 7, 11],
});
// This networkStatus is setVariables instead of refetch because we
// called refetch with new variables.
expect(result.current.networkStatus).toBe(NetworkStatus.setVariables);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toEqual({
primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29],
});
expect(mergeParams).toEqual([
[void 0, [2, 3, 5, 7, 11]],
// This indicates concatenation happened.
[[2, 3, 5, 7, 11], [13, 17, 19, 23, 29]],
]);
expect(mergeParams).toEqual([
[undefined, [2, 3, 5, 7, 11]],
// Without refetchWritePolicy: "overwrite", this array will be
// all 10 primes (2 through 29) together.
[[2, 3, 5, 7, 11], [13, 17, 19, 23, 29]],
]);
expect(thenFn).toHaveBeenCalledTimes(1);
expect(thenFn).toHaveBeenCalledWith({
loading: false,
networkStatus: NetworkStatus.ready,
data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },
});
});
it('should assume default refetchWritePolicy value is "overwrite"', async () => {
const mergeParams: [any, any][] = [];
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
primes: {
keyArgs: false,
merge(existing, incoming) {
mergeParams.push([existing, incoming]);
return existing ? existing.concat(incoming) : incoming;
},
},
},
},
},
});
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>{children}</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
variables: { min: 0, max: 12 },
notifyOnNetworkStatusChange: true,
// Intentionally not passing refetchWritePolicy.
}),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toBe(undefined);
expect(typeof result.current.refetch).toBe('function');
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBeUndefined();
expect(result.current.data).toEqual({ primes: [2, 3, 5, 7, 11] });
expect(mergeParams).toEqual([
[void 0, [2, 3, 5, 7, 11]],
]);
const thenFn = jest.fn();
result.current.refetch({ min: 12, max: 30 }).then(thenFn);
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toEqual({
// We get the stale data because we configured keyArgs: false.
primes: [2, 3, 5, 7, 11],
});
// This networkStatus is setVariables instead of refetch because we
// called refetch with new variables.
expect(result.current.networkStatus).toBe(NetworkStatus.setVariables);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toEqual({ primes: [13, 17, 19, 23, 29] });
expect(mergeParams).toEqual([
[undefined, [2, 3, 5, 7, 11]],
// Without refetchWritePolicy: "overwrite", this array will be
// all 10 primes (2 through 29) together.
[undefined, [13, 17, 19, 23, 29]],
]);
expect(thenFn).toHaveBeenCalledTimes(1);
expect(thenFn).toHaveBeenCalledWith({
loading: false,
networkStatus: NetworkStatus.ready,
data: { primes: [13, 17, 19, 23, 29] },
});
});
});
});
describe('Callbacks', () => {
it('onCompleted is called once with cached data', async () => {
const query = gql`{ hello }`;
const cache = new InMemoryCache();
cache.writeQuery({
query,
data: { hello: 'world' },
});
const wrapper = ({ children }: any) => (
<MockedProvider mocks={[]} cache={cache}>
{children}
</MockedProvider>
);
const onCompleted = jest.fn();
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
fetchPolicy: 'cache-only',
onCompleted,
}),
{ wrapper },
);
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world' });
expect(onCompleted).toHaveBeenCalledTimes(1);
expect(onCompleted).toHaveBeenCalledWith({ hello: 'world' });
await expect(waitForNextUpdate({ timeout: 20 })).rejects.toThrow('Timed out');
expect(onCompleted).toHaveBeenCalledTimes(1);
});
it('onCompleted is called once despite state changes', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: 'world' } },
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
);
const onCompleted = jest.fn();
const { result, rerender, waitForNextUpdate } = renderHook(
() => useQuery(query, {
onCompleted,
}),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world' });
expect(onCompleted).toHaveBeenCalledTimes(1);
expect(onCompleted).toHaveBeenCalledWith({ hello: 'world' });
rerender();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world' });
expect(onCompleted).toHaveBeenCalledTimes(1);
expect(onCompleted).toHaveBeenCalledWith({ hello: 'world' });
expect(onCompleted).toHaveBeenCalledTimes(1);
});
it('should not call onCompleted if skip is true', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: 'world' } },
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
);
const onCompleted = jest.fn();
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
skip: true,
onCompleted,
}),
{ wrapper },
);
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
await expect(waitForNextUpdate({ timeout: 20 })).rejects.toThrow('Timed out');
expect(onCompleted).toHaveBeenCalledTimes(0);
});
it('should not make extra network requests when `onCompleted` is defined with a `network-only` fetch policy', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: 'world' } },
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
);
const onCompleted = jest.fn();
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
fetchPolicy: 'network-only',
onCompleted,
}),
{ wrapper },
);
expect(result.current.loading).toBe(true);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world' });
expect(onCompleted).toHaveBeenCalledTimes(1);
await expect(waitForNextUpdate({ timeout: 20 })).rejects.toThrow('Timed out');
expect(onCompleted).toHaveBeenCalledTimes(1);
});
it('onCompleted should work with polling', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: 'world 1' } },
},
{
request: { query },
result: { data: { hello: 'world 2' } },
},
{
request: { query },
result: { data: { hello: 'world 3' } },
},
];
const cache = new InMemoryCache();
const onCompleted = jest.fn();
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
onCompleted,
pollInterval: 10,
}),
{
wrapper: ({ children }) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
),
},
);
expect(result.current.loading).toBe(true);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world 1' });
expect(onCompleted).toHaveBeenCalledTimes(1);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world 2' });
expect(onCompleted).toHaveBeenCalledTimes(2);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world 3' });
expect(onCompleted).toHaveBeenCalledTimes(3);
});
});
describe('Optimistic data', () => {
it('should display rolled back optimistic data when an error occurs', async () => {
const query = gql`
query AllCars {
cars {
id
make
model
}
}
`;
const carsData = {
cars: [
{
id: 1,
make: 'Audi',
model: 'RS8',
__typename: 'Car'
}
]
};
const mutation = gql`
mutation AddCar {
addCar {
id
make
model
}
}
`;
const carData = {
id: 2,
make: 'Ford',
model: 'Pinto',
__typename: 'Car'
};
const allCarsData = {
cars: [
carsData.cars[0],
carData
]
};
const mocks = [
{
request: { query },
result: { data: carsData },
},
{
request: { query: mutation },
error: new Error('Oh no!'),
delay: 500,
}
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
);
const onError = jest.fn();
const { result, waitForNextUpdate } = renderHook(
() => ({
mutation: useMutation(mutation, {
optimisticResponse: { addCar: carData },
update(cache, { data }) {
cache.modify({
fields: {
cars(existing, { readField }) {
const newCarRef = cache.writeFragment({
data: data!.addCar,
fragment: gql`fragment NewCar on Car {
id
make
model
}`,
});
if (existing.some(
(ref: Reference) => readField('id', ref) === data!.addCar.id
)) {
return existing;
}
return [...existing, newCarRef];
},
},
});
},
onError,
}),
query: useQuery(query),
}),
{ wrapper },
);
expect(result.current.query.loading).toBe(true);
const mutate = result.current.mutation[0];
await waitForNextUpdate();
expect(result.current.query.loading).toBe(false);
expect(result.current.query.data).toEqual(carsData);
act(() => void mutate());
// The mutation ran and is loading the result. The query stays at not
// loading as nothing has changed for the query, but optimistic data is
// rendered.
expect(result.current.mutation[1].loading).toBe(true);
expect(result.current.query.loading).toBe(false);
expect(result.current.query.data).toEqual(allCarsData);
await waitForNextUpdate();
// TODO: There is a missing update here because mutation and query update
// in the same microtask loop.
const previous = result.all[result.all.length - 2];
if (previous instanceof Error) {
throw previous;
}
// The mutation ran and is loading the result. The query stays at
// not loading as nothing has changed for the query.
expect(previous.mutation[1].loading).toBe(true);
expect(previous.query.loading).toBe(false);
// The mutation has completely finished, leaving the query with access to
// the original cache data.
expect(result.current.mutation[1].loading).toBe(false);
expect(result.current.query.loading).toBe(false);
expect(result.current.query.data).toEqual(carsData);
expect(onError).toHaveBeenCalledTimes(1);
expect(onError.mock.calls[0][0].message).toBe('Oh no!');
});
});
describe('Partial refetch', () => {
it('should attempt a refetch when data is missing and partialRefetch is true', async () => {
const errorSpy = jest.spyOn(console, 'error')
.mockImplementation(() => {});
const query = gql`{ hello }`;
const link = mockSingleLink(
{
request: { query },
result: { data: {} },
delay: 20,
},
{
request: { query },
result: { data: { hello: "world" } },
delay: 20,
}
);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
partialRefetch: true,
notifyOnNetworkStatusChange: true,
}),
{
wrapper: ({ children }) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
),
},
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
expect(result.current.networkStatus).toBe(NetworkStatus.loading);
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
expect(result.current.networkStatus).toBe(NetworkStatus.refetch);
expect(errorSpy).toHaveBeenCalledTimes(1);
expect(errorSpy.mock.calls[0][0]).toMatch('Missing field');
errorSpy.mockRestore();
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world' });
expect(result.current.error).toBe(undefined);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
});
it('should attempt a refetch when data is missing and partialRefetch is true 2', async () => {
const query = gql`
query people {
allPeople(first: 1) {
people {
name
}
}
}
`;
const data = {
allPeople: { people: [{ name: 'Luke Skywalker' }] },
};
const errorSpy = jest.spyOn(console, 'error')
.mockImplementation(() => {});
const link = mockSingleLink(
{ request: { query }, result: { data: {} }, delay: 20 },
{ request: { query }, result: { data }, delay: 20 }
);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
partialRefetch: true,
notifyOnNetworkStatusChange: true,
}),
{
wrapper: ({ children }) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
),
},
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
expect(result.current.networkStatus).toBe(NetworkStatus.loading);
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
expect(result.current.networkStatus).toBe(NetworkStatus.refetch);
expect(errorSpy).toHaveBeenCalledTimes(1);
expect(errorSpy.mock.calls[0][0]).toMatch('Missing field');
errorSpy.mockRestore();
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual(data);
expect(result.current.error).toBe(undefined);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
});
it('should attempt a refetch when data is missing, partialRefetch is true and addTypename is false for the cache', async () => {
const errorSpy = jest.spyOn(console, 'error')
.mockImplementation(() => {});
const query = gql`{ hello }`;
const link = mockSingleLink(
{
request: { query },
result: { data: {} },
delay: 20,
},
{
request: { query },
result: { data: { hello: "world" } },
delay: 20,
}
);
const client = new ApolloClient({
link,
// THIS LINE IS THE ONLY DIFFERENCE FOR THIS TEST
cache: new InMemoryCache({ addTypename: false }),
});
const wrapper = ({ children }: any) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, {
partialRefetch: true,
notifyOnNetworkStatusChange: true,
}),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
expect(result.current.networkStatus).toBe(NetworkStatus.loading);
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toBe(undefined);
expect(result.current.networkStatus).toBe(NetworkStatus.refetch);
expect(errorSpy).toHaveBeenCalledTimes(1);
expect(errorSpy.mock.calls[0][0]).toMatch('Missing field');
errorSpy.mockRestore();
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world' });
expect(result.current.error).toBe(undefined);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
});
});
describe('Client Resolvers', () => {
it('should receive up to date @client(always: true) fields on entity update', async () => {
const query = gql`
query GetClientData($id: ID) {
clientEntity(id: $id) @client(always: true) {
id
title
titleLength @client(always: true)
}
}
`;
const mutation = gql`
mutation AddOrUpdate {
addOrUpdate(id: $id, title: $title) @client
}
`;
const fragment = gql`
fragment ClientDataFragment on ClientData {
id
title
}
`;
const client = new ApolloClient({
cache: new InMemoryCache(),
link: new ApolloLink(() => Observable.of({ data: {} })),
resolvers: {
ClientData: {
titleLength(data) {
return data.title.length
}
},
Query: {
clientEntity(_root, {id}, {cache}) {
return cache.readFragment({
id: cache.identify({id, __typename: "ClientData"}),
fragment,
});
},
},
Mutation: {
addOrUpdate(_root, {id, title}, {cache}) {
return cache.writeFragment({
id: cache.identify({id, __typename: "ClientData"}),
fragment,
data: {id, title, __typename: "ClientData"},
});
},
},
},
});
const entityId = 1;
const shortTitle = 'Short';
const longerTitle = 'A little longer';
client.mutate({
mutation,
variables: {
id: entityId,
title: shortTitle,
},
});
const wrapper = ({ children }: any) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { variables: { id: entityId } }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({
clientEntity: {
id: entityId,
title: shortTitle,
titleLength: shortTitle.length,
__typename: 'ClientData',
},
});
setTimeout(() => {
client.mutate({
mutation,
variables: {
id: entityId,
title: longerTitle,
}
});
});
await waitForNextUpdate();
expect(result.current.data).toEqual({
clientEntity: {
id: entityId,
title: longerTitle,
titleLength: longerTitle.length,
__typename: "ClientData",
},
});
});
});
describe('Skipping', () => {
const query = gql`query greeting($someVar: Boolean) { hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: 'world' } },
},
{
request: {
query,
variables: { someVar: true },
},
result: { data: { hello: 'world' } },
},
];
it('should skip running a query when `skip` is `true`', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: 'world' } },
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
);
const { result, rerender, waitForNextUpdate } = renderHook(
({ skip }) => useQuery(query, { skip }),
{ wrapper, initialProps: { skip: true } },
);
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
await expect(waitForNextUpdate({ timeout: 20 })).rejects.toThrow('Timed out');
rerender({ skip: false });
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBeFalsy();
expect(result.current.data).toEqual({ hello: 'world' });
});
it('should not make network requests when `skip` is `true`', async () => {
const linkFn = jest.fn();
const link = new ApolloLink((o, f) => {
linkFn();
return f ? f(o) : null;
}).concat(mockSingleLink(...mocks));
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
const wrapper = ({ children }: any) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
);
const { result, rerender, waitForNextUpdate } = renderHook(
({ skip, variables }) => useQuery(query, { skip, variables }),
{ wrapper, initialProps: { skip: false, variables: undefined as any } },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world' });
rerender({ skip: true, variables: { someVar: true } });
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
expect(linkFn).toHaveBeenCalledTimes(1);
});
it('should tear down the query if `skip` is `true`', async () => {
const client = new ApolloClient({
link: new ApolloLink(() => Observable.of({ data: { hello: 'world' } })),
cache: new InMemoryCache(),
});
const wrapper = ({ children }: any) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
);
const { unmount } = renderHook(
() => useQuery(query, { skip: true }),
{ wrapper },
);
expect(client.getObservableQueries('all').size).toBe(1);
unmount();
expect(client.getObservableQueries('all').size).toBe(0);
});
it('should treat fetchPolicy standby like skip', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: 'world' } },
},
];
const { result, rerender, waitForNextUpdate } = renderHook(
({ fetchPolicy }) => useQuery(query, { fetchPolicy }),
{
wrapper: ({ children }) => (
<MockedProvider mocks={mocks}>
{children}
</MockedProvider>
),
initialProps: { fetchPolicy: 'standby' as any },
},
);
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
await expect(waitForNextUpdate({ timeout: 20 })).rejects.toThrow('Timed out');
rerender({ fetchPolicy: 'cache-first' });
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBeFalsy();
expect(result.current.data).toEqual({ hello: 'world' });
});
it('should not refetch when skip is true', async () => {
const query = gql`{ hello }`;
const link = new ApolloLink(() => Observable.of({
data: { hello: 'world' },
}));
const requestSpy = jest.spyOn(link, 'request');
const client = new ApolloClient({
cache: new InMemoryCache(),
link,
});
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { skip: true }),
{
wrapper: ({ children }) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
),
},
);
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
await expect(waitForNextUpdate({ timeout: 20 }))
.rejects.toThrow('Timed out');
result.current.refetch();
await expect(waitForNextUpdate({ timeout: 20 }))
.rejects.toThrow('Timed out');
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(undefined);
expect(requestSpy).toHaveBeenCalledTimes(0);
requestSpy.mockRestore();
});
});
describe('Missing Fields', () => {
it('should log debug messages about MissingFieldErrors from the cache', async () => {
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
const carQuery: DocumentNode = gql`
query cars($id: Int) {
cars(id: $id) {
id
make
model
vin
__typename
}
}
`;
const carData = {
cars: [
{
id: 1,
make: 'Audi',
model: 'RS8',
vine: 'DOLLADOLLABILL',
__typename: 'Car'
}
]
};
const mocks = [
{
request: { query: carQuery, variables: { id: 1 } },
result: { data: carData }
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(carQuery, { variables: { id: 1 } }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.error).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual(carData);
expect(result.current.error).toBeUndefined();
expect(errorSpy).toHaveBeenCalledTimes(1);
expect(errorSpy).toHaveBeenLastCalledWith(
`Missing field 'vin' while writing result ${JSON.stringify({
id: 1,
make: "Audi",
model: "RS8",
vine: "DOLLADOLLABILL",
__typename: "Car"
}, null, 2)}`
);
errorSpy.mockRestore();
});
it('should return partial cache data when `returnPartialData` is true', async () => {
const cache = new InMemoryCache();
const client = new ApolloClient({
cache,
link: ApolloLink.empty(),
});
const fullQuery = gql`
query {
cars {
make
model
repairs {
date
description
}
}
}
`;
cache.writeQuery({
query: fullQuery,
data: {
cars: [
{
__typename: 'Car',
make: 'Ford',
model: 'Mustang',
vin: 'PONY123',
repairs: [
{
__typename: 'Repair',
date: '2019-05-08',
description: 'Could not get after it.',
},
],
},
],
},
});
const partialQuery = gql`
query {
cars {
repairs {
date
cost
}
}
}
`;
const { result } = renderHook(
() => useQuery(partialQuery, { returnPartialData: true }),
{
wrapper: ({ children }) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
),
},
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toEqual({
cars: [
{
__typename: 'Car',
repairs: [
{
__typename: 'Repair',
date: '2019-05-08',
},
],
},
],
});
});
it('should not return partial cache data when `returnPartialData` is false', () => {
const cache = new InMemoryCache();
const client = new ApolloClient({
cache,
link: ApolloLink.empty(),
});
const fullQuery = gql`
query {
cars {
make
model
repairs {
date
description
}
}
}
`;
cache.writeQuery({
query: fullQuery,
data: {
cars: [
{
__typename: 'Car',
make: 'Ford',
model: 'Mustang',
vin: 'PONY123',
repairs: [
{
__typename: 'Repair',
date: '2019-05-08',
description: 'Could not get after it.',
},
],
},
],
},
});
const partialQuery = gql`
query {
cars {
repairs {
date
cost
}
}
}
`;
const { result } = renderHook(
() => useQuery(partialQuery, { returnPartialData: false }),
{
wrapper: ({ children }) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
),
},
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
});
});
describe('Previous data', () => {
it('should persist previous data when a query is re-run', async () => {
const query = gql`
query car {
car {
id
make
}
}
`;
const data1 = {
car: {
id: 1,
make: 'Venturi',
__typename: 'Car',
}
};
const data2 = {
car: {
id: 2,
make: 'Wiesmann',
__typename: 'Car',
}
};
const mocks = [
{ request: { query }, result: { data: data1 } },
{ request: { query }, result: { data: data2 }, delay: 10 },
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { notifyOnNetworkStatusChange: true }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.previousData).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual(data1);
expect(result.current.previousData).toBe(undefined);
setTimeout(() => result.current.refetch());
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.data).toEqual(data1);
expect(result.current.previousData).toEqual(data1);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual(data2);
expect(result.current.previousData).toEqual(data1);
});
it('should persist result.previousData across multiple results', async () => {
const query: TypedDocumentNode<{
car: {
id: string;
make: string;
};
}, {
vin?: string;
}> = gql`
query car($vin: String) {
car(vin: $vin) {
id
make
}
}
`;
const data1 = {
car: {
id: 1,
make: 'Venturi',
__typename: 'Car',
},
};
const data2 = {
car: {
id: 2,
make: 'Wiesmann',
__typename: 'Car',
},
};
const data3 = {
car: {
id: 3,
make: 'Beetle',
__typename: 'Car',
},
};
const mocks = [
{ request: { query }, result: { data: data1 } },
{ request: { query }, result: { data: data2 }, delay: 100 },
{
request: {
query,
variables: { vin: "ABCDEFG0123456789" },
},
result: { data: data3 },
},
];
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} cache={cache}>
{children}
</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query, { notifyOnNetworkStatusChange: true }),
{ wrapper },
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
expect(result.current.previousData).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual(data1);
expect(result.current.previousData).toBe(undefined);
setTimeout(() => result.current.refetch());
await waitForNextUpdate();
expect(result.current.loading).toBe(true);
expect(result.current.data).toEqual(data1);
expect(result.current.previousData).toEqual(data1);
result.current.refetch({ vin: "ABCDEFG0123456789" });
expect(result.current.loading).toBe(true);
expect(result.current.data).toEqual(data1);
expect(result.current.previousData).toEqual(data1);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual(data3);
expect(result.current.previousData).toEqual(data1);
});
it("should be cleared when variables change causes cache miss", async () => {
const peopleData = [
{ id: 1, name: 'John Smith', gender: 'male' },
{ id: 2, name: 'Sara Smith', gender: 'female' },
{ id: 3, name: 'Budd Deey', gender: 'nonbinary' },
{ id: 4, name: 'Johnny Appleseed', gender: 'male' },
{ id: 5, name: 'Ada Lovelace', gender: 'female' },
];
const link = new ApolloLink(operation => {
return new Observable(observer => {
const { gender } = operation.variables;
new Promise(resolve => setTimeout(resolve, 300)).then(() => {
observer.next({
data: {
people: gender === "all" ? peopleData :
gender ? peopleData.filter(
person => person.gender === gender
) : peopleData,
}
});
observer.complete();
});
});
});
type Person = {
__typename: string;
id: string;
name: string;
};
const query: TypedDocumentNode<{
people: Person[];
}> = gql`
query AllPeople($gender: String!) {
people(gender: $gender) {
id
name
}
}
`;
const cache = new InMemoryCache();
const wrapper = ({ children }: any) => (
<MockedProvider link={link} cache={cache}>
{children}
</MockedProvider>
);
const { result, rerender, waitForNextUpdate } = renderHook(
({ gender }) => useQuery(query, {
variables: { gender },
fetchPolicy: 'network-only',
}),
{ wrapper, initialProps: { gender: 'all' } },
);
expect(result.current.loading).toBe(true);
expect(result.current.networkStatus).toBe(NetworkStatus.loading);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
expect(result.current.data).toEqual({
people: peopleData.map(({ gender, ...person }) => person),
});
rerender({ gender: 'female' });
expect(result.current.loading).toBe(true);
expect(result.current.networkStatus).toBe(NetworkStatus.setVariables);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
expect(result.current.data).toEqual({
people: peopleData
.filter((person) => person.gender === 'female')
.map(({ gender, ...person }) => person),
});
rerender({ gender: 'nonbinary' });
expect(result.current.loading).toBe(true);
expect(result.current.networkStatus).toBe(NetworkStatus.setVariables);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.networkStatus).toBe(NetworkStatus.ready);
expect(result.current.data).toEqual({
people: peopleData
.filter((person) => person.gender === 'nonbinary')
.map(({ gender, ...person }) => person),
});
});
});
describe('defaultOptions', () => {
it('should allow polling options to be passed to the client', async () => {
const query = gql`{ hello }`;
const cache = new InMemoryCache();
const link = mockSingleLink(
{
request: { query },
result: { data: { hello: "world 1" } },
},
{
request: { query },
result: { data: { hello: "world 2" } },
},
{
request: { query },
result: { data: { hello: "world 3" } },
},
);
const client = new ApolloClient({
defaultOptions: {
watchQuery: {
pollInterval: 10,
},
},
cache,
link,
});
const { result, waitForNextUpdate } = renderHook(
() => useQuery(query),
{
wrapper: ({ children }) => (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
),
},
);
expect(result.current.loading).toBe(true);
expect(result.current.data).toBe(undefined);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world 1' });
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world 2' });
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ hello: 'world 3' });
});
});
describe('canonical cache results', () => {
it('can be disabled via useQuery options', async () => {
const cache = new InMemoryCache({
canonizeResults: true,
typePolicies: {
Result: {
keyFields: false,
},
},
});
const query = gql`
query {
results {
value
}
}
`;
const results = [
{ __typename: "Result", value: 0 },
{ __typename: "Result", value: 1 },
{ __typename: "Result", value: 1 },
{ __typename: "Result", value: 2 },
{ __typename: "Result", value: 3 },
{ __typename: "Result", value: 5 },
];
cache.writeQuery({
query,
data: { results },
})
const wrapper = ({ children }: any) => (
<MockedProvider cache={cache}>
{children}
</MockedProvider>
);
const { result, rerender, waitForNextUpdate } = renderHook(
({ canonizeResults }) => useQuery(query, {
fetchPolicy: 'cache-only',
canonizeResults,
}),
{ wrapper, initialProps: { canonizeResults: false } },
);
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ results });
expect(result.current.data.results.length).toBe(6);
let resultSet = new Set(result.current.data.results);
// Since canonization is not happening, the duplicate 1 results are
// returned as distinct objects.
expect(resultSet.size).toBe(6);
let values: number[] = [];
resultSet.forEach((result: any) => values.push(result.value));
expect(values).toEqual([0, 1, 1, 2, 3, 5]);
rerender({ canonizeResults: true });
act(() => {
results.push({
__typename: "Result",
value: 8,
});
// Append another element to the results array, invalidating the
// array itself, triggering another render (below).
cache.writeQuery({
query,
overwrite: true,
data: { results },
});
});
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual({ results });
expect(result.current.data.results.length).toBe(7);
resultSet = new Set(result.current.data.results);
// Since canonization is happening now, the duplicate 1 results are
// returned as identical (===) objects.
expect(resultSet.size).toBe(6);
values = [];
resultSet.forEach((result: any) => values.push(result.value));
expect(values).toEqual([0, 1, 2, 3, 5, 8]);
});
});
describe("multiple useQuery calls per component", () => {
type ABFields = {
id: number;
name: string;
};
const aQuery: TypedDocumentNode<{
a: ABFields;
}> = gql`query A { a { id name }}`;
const bQuery: TypedDocumentNode<{
b: ABFields;
}> = gql`query B { b { id name }}`;
const aData = {
a: {
__typename: "A",
id: 65,
name: "ay",
},
};
const bData = {
b: {
__typename: "B",
id: 66,
name: "bee",
},
};
function makeClient() {
return new ApolloClient({
cache: new InMemoryCache,
link: new ApolloLink(operation => new Observable(observer => {
switch (operation.operationName) {
case "A":
setTimeout(() => {
observer.next({ data: aData });
observer.complete();
});
break;
case "B":
setTimeout(() => {
observer.next({ data: bData });
observer.complete();
}, 10);
break;
}
})),
});
}
async function check(
aFetchPolicy: WatchQueryFetchPolicy,
bFetchPolicy: WatchQueryFetchPolicy,
) {
const client = makeClient();
const { result } = renderHook(
() => ({
a: useQuery(aQuery, { fetchPolicy: aFetchPolicy }),
b: useQuery(bQuery, { fetchPolicy: bFetchPolicy }),
}),
{
wrapper: ({ children }) => (
<ApolloProvider client={client}>{children}</ApolloProvider>
),
},
);
expect(result.current.a.loading).toBe(true);
expect(result.current.b.loading).toBe(true);
expect(result.current.a.data).toBe(undefined);
expect(result.current.b.data).toBe(undefined);
await waitFor(() => {
expect(result.current.a.loading).toBe(false);
expect(result.current.b.loading).toBe(false);
});
expect(result.current.a.data).toEqual(aData);
expect(result.current.b.data).toEqual(bData);
}
it("cache-first for both", () => check(
"cache-first",
"cache-first",
));
it("cache-first first, cache-and-network second", () => check(
"cache-first",
"cache-and-network",
));
it("cache-first first, network-only second", () => check(
"cache-first",
"network-only",
));
it("cache-and-network for both", () => check(
"cache-and-network",
"cache-and-network",
));
it("cache-and-network first, cache-first second", () => check(
"cache-and-network",
"cache-first",
));
it("cache-and-network first, network-only second", () => check(
"cache-and-network",
"network-only",
));
it("network-only for both", () => check(
"network-only",
"network-only",
));
it("network-only first, cache-first second", () => check(
"network-only",
"cache-first",
));
it("network-only first, cache-and-network second", () => check(
"network-only",
"cache-and-network",
));
});
}); | the_stack |
import {
ArgumentValue,
CdmArgumentDefinition,
CdmParameterDefinition,
CdmTraitDefinition,
ParameterCollection,
ParameterValue,
ResolvedTrait,
resolveOptions,
spewCatcher
} from '../internal';
/**
* @internal
*/
export class ResolvedTraitSet {
public get size(): number {
// let bodyCode = () =>
{
if (this.set) {
return this.set.length;
}
return 0;
}
// return p.measure(bodyCode);
}
public get first(): ResolvedTrait {
// let bodyCode = () =>
{
if (this.set) {
return this.set[0];
}
return undefined;
}
// return p.measure(bodyCode);
}
public set: ResolvedTrait[];
public resOpt: resolveOptions;
public hasElevated: boolean;
private readonly lookupByTrait: Map<CdmTraitDefinition, ResolvedTrait>;
constructor(resOpt: resolveOptions) {
// let bodyCode = () =>
{
this.resOpt = resOpt;
this.set = [];
this.lookupByTrait = new Map<CdmTraitDefinition, ResolvedTrait>();
this.hasElevated = false;
}
// return p.measure(bodyCode);
}
public merge(toMerge: ResolvedTrait, copyOnWrite: boolean): ResolvedTraitSet {
// let bodyCode = () =>
{
let traitSetResult: ResolvedTraitSet = this;
const trait: CdmTraitDefinition = toMerge.trait;
let av: ArgumentValue[];
let wasSet: boolean[];
if (toMerge.parameterValues) {
av = toMerge.parameterValues.values;
wasSet = toMerge.parameterValues.wasSet;
}
if (!this.hasElevated) {
this.hasElevated = trait.elevated;
}
if (traitSetResult.lookupByTrait.has(trait)) {
let rtOld: ResolvedTrait = traitSetResult.lookupByTrait.get(trait);
let avOld: ArgumentValue[];
if (rtOld.parameterValues) {
avOld = rtOld.parameterValues.values;
}
if (av && avOld) {
// the new values take precedence
const l: number = av.length;
for (let i: number = 0; i < l; i++) {
if (av[i] !== avOld[i]) {
if (copyOnWrite) {
traitSetResult = traitSetResult.shallowCopyWithException(trait);
rtOld = traitSetResult.lookupByTrait.get(trait);
avOld = rtOld.parameterValues.values;
copyOnWrite = false;
}
avOld[i] = ParameterValue.fetchReplacementValue(this.resOpt, avOld[i], av[i], wasSet[i]);
}
}
}
} else {
if (copyOnWrite) {
traitSetResult = traitSetResult.shallowCopy();
}
toMerge = toMerge.copy();
traitSetResult.set.push(toMerge);
traitSetResult.lookupByTrait.set(trait, toMerge);
}
return traitSetResult;
}
// return p.measure(bodyCode);
}
public mergeSet(toMerge: ResolvedTraitSet, elevatedOnly: boolean = false): ResolvedTraitSet {
// let bodyCode = () =>
{
let copyOnWrite: boolean = true;
let traitSetResult: ResolvedTraitSet = this;
if (toMerge) {
const l: number = toMerge.set.length;
for (let i: number = 0; i < l; i++) {
const rt: ResolvedTrait = toMerge.set[i];
if (!elevatedOnly || rt.trait.elevated) {
const traitSetMerge: ResolvedTraitSet = traitSetResult.merge(rt, copyOnWrite);
if (traitSetMerge !== traitSetResult) {
traitSetResult = traitSetMerge;
copyOnWrite = false;
}
}
}
}
return traitSetResult;
}
// return p.measure(bodyCode);
}
public get(trait: CdmTraitDefinition): ResolvedTrait {
// let bodyCode = () =>
{
if (this.lookupByTrait.has(trait)) {
return this.lookupByTrait.get(trait);
}
return undefined;
}
// return p.measure(bodyCode);
}
public find(resOpt: resolveOptions, traitName: string): ResolvedTrait {
// let bodyCode = () =>
{
const l: number = this.set.length;
for (let i: number = 0; i < l; i++) {
const rt: ResolvedTrait = this.set[i];
if (rt.trait.isDerivedFrom(traitName, resOpt)) {
return rt;
}
}
return undefined;
}
// return p.measure(bodyCode);
}
public remove(resOpt: resolveOptions, traitName: string): boolean {
const rt: ResolvedTrait = this.find(resOpt, traitName);
if (rt != null) {
this.lookupByTrait.delete(rt.trait);
const index:number = this.set.indexOf(rt);
if (index > -1) {
this.set.splice(index, 1);
}
return true;
}
return false;
}
public deepCopy(): ResolvedTraitSet {
// let bodyCode = () =>
{
const copy: ResolvedTraitSet = new ResolvedTraitSet(this.resOpt);
const l: number = this.set.length;
for (let i: number = 0; i < l; i++) {
const rt: ResolvedTrait = this.set[i].copy();
copy.set.push(rt);
copy.lookupByTrait.set(rt.trait, rt);
}
copy.hasElevated = this.hasElevated;
return copy;
}
// return p.measure(bodyCode);
}
public shallowCopyWithException(just: CdmTraitDefinition): ResolvedTraitSet {
// let bodyCode = () =>
{
const copy: ResolvedTraitSet = new ResolvedTraitSet(this.resOpt);
const l: number = this.set.length;
for (let i: number = 0; i < l; i++) {
let rt: ResolvedTrait = this.set[i];
if (rt.trait === just) {
rt = rt.copy();
}
copy.set.push(rt);
copy.lookupByTrait.set(rt.trait, rt);
}
copy.hasElevated = this.hasElevated;
return copy;
}
// return p.measure(bodyCode);
}
public shallowCopy(): ResolvedTraitSet {
// let bodyCode = () =>
{
const copy: ResolvedTraitSet = new ResolvedTraitSet(this.resOpt);
if (this.set) {
const l: number = this.set.length;
for (let i: number = 0; i < l; i++) {
const rt: ResolvedTrait = this.set[i];
copy.set.push(rt);
copy.lookupByTrait.set(rt.trait, rt);
}
}
copy.hasElevated = this.hasElevated;
return copy;
}
// return p.measure(bodyCode);
}
public collectTraitNames(): Set<string> {
// let bodyCode = () =>
{
const collection: Set<string> = new Set<string>();
if (this.set) {
const l: number = this.set.length;
for (let i: number = 0; i < l; i++) {
const rt: ResolvedTrait = this.set[i];
rt.collectTraitNames(this.resOpt, collection);
}
}
return collection;
}
// return p.measure(bodyCode);
}
public setParameterValueFromArgument(trait: CdmTraitDefinition, arg: CdmArgumentDefinition): void {
// let bodyCode = () =>
{
const resTrait: ResolvedTrait = this.get(trait);
if (resTrait && resTrait.parameterValues) {
const av: ArgumentValue[] = resTrait.parameterValues.values;
const newVal: ArgumentValue = arg.getValue();
// get the value index from the parameter collection given the parameter that this argument is setting
let paramDef: CdmParameterDefinition = arg.getParameterDef();
if (paramDef)
{
resTrait.parameterValues.setParameterValue(this.resOpt, paramDef.getName(), newVal);
}
else
{
// debug
paramDef = arg.getParameterDef();
}
}
}
// return p.measure(bodyCode);
}
public setTraitParameterValue(resOpt: resolveOptions, toTrait: CdmTraitDefinition,
paramName: string, value: ArgumentValue): ResolvedTraitSet {
// let bodyCode = () =>
{
const altered: ResolvedTraitSet = this.shallowCopyWithException(toTrait);
const currTrait: ResolvedTrait = altered.get(toTrait);
if (currTrait) {
currTrait.parameterValues
.setParameterValue(this.resOpt, paramName, value);
}
return altered;
}
// return p.measure(bodyCode);
}
public replaceTraitParameterValue(resOpt: resolveOptions, toTrait: string, paramName: string,
valueWhen: ArgumentValue, valueNew: ArgumentValue): ResolvedTraitSet {
// let bodyCode = () =>
{
let traitSetResult: ResolvedTraitSet = this as ResolvedTraitSet;
const l: number = traitSetResult.set.length;
for (let i: number = 0; i < l; i++) {
let rt: ResolvedTrait = traitSetResult.set[i];
if (rt && rt.trait.isDerivedFrom(toTrait, this.resOpt)) {
if (rt.parameterValues) {
const pc: ParameterCollection = rt.parameterValues.pc;
let av: ArgumentValue[] = rt.parameterValues.values;
const idx: number = pc.fetchParameterIndex(paramName);
if (idx !== undefined && av[idx] === valueWhen) {
// copy the set and make a deep copy of the trait being set
traitSetResult = this.shallowCopyWithException(rt.trait);
// assume these are all still true for this copy
rt = traitSetResult.set[i];
av = rt.parameterValues.values;
av[idx] = ParameterValue.fetchReplacementValue(this.resOpt, av[idx], valueNew, true);
break;
}
}
}
}
return traitSetResult;
}
// return p.measure(bodyCode);
}
public spew(resOpt: resolveOptions, to: spewCatcher, indent: string, nameSort: boolean): void {
// let bodyCode = () =>
{
const l: number = this.set.length;
let list: ResolvedTrait[] = this.set;
if (nameSort) {
list = list.sort((lhs: ResolvedTrait, rhs: ResolvedTrait) => lhs.traitName.localeCompare(rhs.traitName));
}
for (let i: number = 0; i < l; i++) {
// comment this line to simplify spew results to stop at attribute names
list[i].spew(resOpt, to, indent);
}
}
// return p.measure(bodyCode);
}
} | the_stack |
declare module Atomic {
// enum FrustumPlane
export type FrustumPlane = number;
export var PLANE_NEAR: FrustumPlane;
export var PLANE_LEFT: FrustumPlane;
export var PLANE_RIGHT: FrustumPlane;
export var PLANE_UP: FrustumPlane;
export var PLANE_DOWN: FrustumPlane;
export var PLANE_FAR: FrustumPlane;
// enum Intersection
export type Intersection = number;
export var OUTSIDE: Intersection;
export var INTERSECTS: Intersection;
export var INSIDE: Intersection;
// enum InterpolationMode
export type InterpolationMode = number;
export var BEZIER_CURVE: InterpolationMode;
// enum VariantType
export type VariantType = number;
export var VAR_NONE: VariantType;
export var VAR_INT: VariantType;
export var VAR_BOOL: VariantType;
export var VAR_FLOAT: VariantType;
export var VAR_VECTOR2: VariantType;
export var VAR_VECTOR3: VariantType;
export var VAR_VECTOR4: VariantType;
export var VAR_QUATERNION: VariantType;
export var VAR_COLOR: VariantType;
export var VAR_STRING: VariantType;
export var VAR_BUFFER: VariantType;
export var VAR_VOIDPTR: VariantType;
export var VAR_RESOURCEREF: VariantType;
export var VAR_RESOURCEREFLIST: VariantType;
export var VAR_VARIANTVECTOR: VariantType;
export var VAR_VARIANTMAP: VariantType;
export var VAR_INTRECT: VariantType;
export var VAR_INTVECTOR2: VariantType;
export var VAR_PTR: VariantType;
export var VAR_MATRIX3: VariantType;
export var VAR_MATRIX3X4: VariantType;
export var VAR_MATRIX4: VariantType;
export var VAR_DOUBLE: VariantType;
export var MAX_VAR_TYPES: VariantType;
// enum WrapMode
export type WrapMode = number;
export var WM_LOOP: WrapMode;
export var WM_ONCE: WrapMode;
export var WM_CLAMP: WrapMode;
// enum CreateMode
export type CreateMode = number;
export var REPLICATED: CreateMode;
export var LOCAL: CreateMode;
// enum TransformSpace
export type TransformSpace = number;
export var TS_LOCAL: TransformSpace;
export var TS_PARENT: TransformSpace;
export var TS_WORLD: TransformSpace;
// enum LoadMode
export type LoadMode = number;
export var LOAD_RESOURCES_ONLY: LoadMode;
export var LOAD_SCENE: LoadMode;
export var LOAD_SCENE_AND_RESOURCES: LoadMode;
// enum InterpMethod
export type InterpMethod = number;
export var IM_LINEAR: InterpMethod;
export var IM_SPLINE: InterpMethod;
// enum UpdateGeometryType
export type UpdateGeometryType = number;
export var UPDATE_NONE: UpdateGeometryType;
export var UPDATE_MAIN_THREAD: UpdateGeometryType;
export var UPDATE_WORKER_THREAD: UpdateGeometryType;
// enum PrimitiveType
export type PrimitiveType = number;
export var TRIANGLE_LIST: PrimitiveType;
export var LINE_LIST: PrimitiveType;
export var POINT_LIST: PrimitiveType;
export var TRIANGLE_STRIP: PrimitiveType;
export var LINE_STRIP: PrimitiveType;
export var TRIANGLE_FAN: PrimitiveType;
// enum GeometryType
export type GeometryType = number;
export var GEOM_STATIC: GeometryType;
export var GEOM_SKINNED: GeometryType;
export var GEOM_INSTANCED: GeometryType;
export var GEOM_BILLBOARD: GeometryType;
export var GEOM_STATIC_NOINSTANCING: GeometryType;
export var MAX_GEOMETRYTYPES: GeometryType;
// enum BlendMode
export type BlendMode = number;
export var BLEND_REPLACE: BlendMode;
export var BLEND_ADD: BlendMode;
export var BLEND_MULTIPLY: BlendMode;
export var BLEND_ALPHA: BlendMode;
export var BLEND_ADDALPHA: BlendMode;
export var BLEND_PREMULALPHA: BlendMode;
export var BLEND_INVDESTALPHA: BlendMode;
export var BLEND_SUBTRACT: BlendMode;
export var BLEND_SUBTRACTALPHA: BlendMode;
export var MAX_BLENDMODES: BlendMode;
// enum CompareMode
export type CompareMode = number;
export var CMP_ALWAYS: CompareMode;
export var CMP_EQUAL: CompareMode;
export var CMP_NOTEQUAL: CompareMode;
export var CMP_LESS: CompareMode;
export var CMP_LESSEQUAL: CompareMode;
export var CMP_GREATER: CompareMode;
export var CMP_GREATEREQUAL: CompareMode;
export var MAX_COMPAREMODES: CompareMode;
// enum CullMode
export type CullMode = number;
export var CULL_NONE: CullMode;
export var CULL_CCW: CullMode;
export var CULL_CW: CullMode;
export var MAX_CULLMODES: CullMode;
// enum FillMode
export type FillMode = number;
export var FILL_SOLID: FillMode;
export var FILL_WIREFRAME: FillMode;
export var FILL_POINT: FillMode;
// enum StencilOp
export type StencilOp = number;
export var OP_KEEP: StencilOp;
export var OP_ZERO: StencilOp;
export var OP_REF: StencilOp;
export var OP_INCR: StencilOp;
export var OP_DECR: StencilOp;
// enum LockState
export type LockState = number;
export var LOCK_NONE: LockState;
export var LOCK_HARDWARE: LockState;
export var LOCK_SHADOW: LockState;
export var LOCK_SCRATCH: LockState;
// enum VertexElement
export type VertexElement = number;
export var ELEMENT_POSITION: VertexElement;
export var ELEMENT_NORMAL: VertexElement;
export var ELEMENT_COLOR: VertexElement;
export var ELEMENT_TEXCOORD1: VertexElement;
export var ELEMENT_TEXCOORD2: VertexElement;
export var ELEMENT_CUBETEXCOORD1: VertexElement;
export var ELEMENT_CUBETEXCOORD2: VertexElement;
export var ELEMENT_TANGENT: VertexElement;
export var ELEMENT_BLENDWEIGHTS: VertexElement;
export var ELEMENT_BLENDINDICES: VertexElement;
export var ELEMENT_INSTANCEMATRIX1: VertexElement;
export var ELEMENT_INSTANCEMATRIX2: VertexElement;
export var ELEMENT_INSTANCEMATRIX3: VertexElement;
export var MAX_VERTEX_ELEMENTS: VertexElement;
// enum TextureFilterMode
export type TextureFilterMode = number;
export var FILTER_NEAREST: TextureFilterMode;
export var FILTER_BILINEAR: TextureFilterMode;
export var FILTER_TRILINEAR: TextureFilterMode;
export var FILTER_ANISOTROPIC: TextureFilterMode;
export var FILTER_DEFAULT: TextureFilterMode;
export var MAX_FILTERMODES: TextureFilterMode;
// enum TextureAddressMode
export type TextureAddressMode = number;
export var ADDRESS_WRAP: TextureAddressMode;
export var ADDRESS_MIRROR: TextureAddressMode;
export var ADDRESS_CLAMP: TextureAddressMode;
export var ADDRESS_BORDER: TextureAddressMode;
export var MAX_ADDRESSMODES: TextureAddressMode;
// enum TextureCoordinate
export type TextureCoordinate = number;
export var COORD_U: TextureCoordinate;
export var COORD_V: TextureCoordinate;
export var COORD_W: TextureCoordinate;
export var MAX_COORDS: TextureCoordinate;
// enum TextureUsage
export type TextureUsage = number;
export var TEXTURE_STATIC: TextureUsage;
export var TEXTURE_DYNAMIC: TextureUsage;
export var TEXTURE_RENDERTARGET: TextureUsage;
export var TEXTURE_DEPTHSTENCIL: TextureUsage;
// enum CubeMapFace
export type CubeMapFace = number;
export var FACE_POSITIVE_X: CubeMapFace;
export var FACE_NEGATIVE_X: CubeMapFace;
export var FACE_POSITIVE_Y: CubeMapFace;
export var FACE_NEGATIVE_Y: CubeMapFace;
export var FACE_POSITIVE_Z: CubeMapFace;
export var FACE_NEGATIVE_Z: CubeMapFace;
export var MAX_CUBEMAP_FACES: CubeMapFace;
// enum CubeMapLayout
export type CubeMapLayout = number;
export var CML_HORIZONTAL: CubeMapLayout;
export var CML_HORIZONTALNVIDIA: CubeMapLayout;
export var CML_HORIZONTALCROSS: CubeMapLayout;
export var CML_VERTICALCROSS: CubeMapLayout;
export var CML_BLENDER: CubeMapLayout;
// enum RenderSurfaceUpdateMode
export type RenderSurfaceUpdateMode = number;
export var SURFACE_MANUALUPDATE: RenderSurfaceUpdateMode;
export var SURFACE_UPDATEVISIBLE: RenderSurfaceUpdateMode;
export var SURFACE_UPDATEALWAYS: RenderSurfaceUpdateMode;
// enum ShaderType
export type ShaderType = number;
export var VS: ShaderType;
export var PS: ShaderType;
// enum ShaderParameterGroup
export type ShaderParameterGroup = number;
export var SP_FRAME: ShaderParameterGroup;
export var SP_CAMERA: ShaderParameterGroup;
export var SP_ZONE: ShaderParameterGroup;
export var SP_LIGHT: ShaderParameterGroup;
export var SP_MATERIAL: ShaderParameterGroup;
export var SP_OBJECT: ShaderParameterGroup;
export var SP_CUSTOM: ShaderParameterGroup;
export var MAX_SHADER_PARAMETER_GROUPS: ShaderParameterGroup;
// enum TextureUnit
export type TextureUnit = number;
export var TU_DIFFUSE: TextureUnit;
export var TU_ALBEDOBUFFER: TextureUnit;
export var TU_NORMAL: TextureUnit;
export var TU_NORMALBUFFER: TextureUnit;
export var TU_SPECULAR: TextureUnit;
export var TU_EMISSIVE: TextureUnit;
export var TU_ENVIRONMENT: TextureUnit;
export var TU_VOLUMEMAP: TextureUnit;
export var TU_CUSTOM1: TextureUnit;
export var TU_CUSTOM2: TextureUnit;
export var TU_LIGHTRAMP: TextureUnit;
export var TU_LIGHTSHAPE: TextureUnit;
export var TU_SHADOWMAP: TextureUnit;
export var TU_FACESELECT: TextureUnit;
export var TU_INDIRECTION: TextureUnit;
export var TU_DEPTHBUFFER: TextureUnit;
export var TU_LIGHTBUFFER: TextureUnit;
export var TU_ZONE: TextureUnit;
export var MAX_MATERIAL_TEXTURE_UNITS: TextureUnit;
export var MAX_TEXTURE_UNITS: TextureUnit;
// enum FaceCameraMode
export type FaceCameraMode = number;
export var FC_NONE: FaceCameraMode;
export var FC_ROTATE_XYZ: FaceCameraMode;
export var FC_ROTATE_Y: FaceCameraMode;
export var FC_LOOKAT_XYZ: FaceCameraMode;
export var FC_LOOKAT_Y: FaceCameraMode;
// enum LightType
export type LightType = number;
export var LIGHT_DIRECTIONAL: LightType;
export var LIGHT_SPOT: LightType;
export var LIGHT_POINT: LightType;
// enum RayQueryLevel
export type RayQueryLevel = number;
export var RAY_AABB: RayQueryLevel;
export var RAY_OBB: RayQueryLevel;
export var RAY_TRIANGLE: RayQueryLevel;
export var RAY_TRIANGLE_UV: RayQueryLevel;
// enum LightVSVariation
export type LightVSVariation = number;
export var LVS_DIR: LightVSVariation;
export var LVS_SPOT: LightVSVariation;
export var LVS_POINT: LightVSVariation;
export var LVS_SHADOW: LightVSVariation;
export var LVS_SPOTSHADOW: LightVSVariation;
export var LVS_POINTSHADOW: LightVSVariation;
export var MAX_LIGHT_VS_VARIATIONS: LightVSVariation;
// enum VertexLightVSVariation
export type VertexLightVSVariation = number;
export var VLVS_NOLIGHTS: VertexLightVSVariation;
export var VLVS_1LIGHT: VertexLightVSVariation;
export var VLVS_2LIGHTS: VertexLightVSVariation;
export var VLVS_3LIGHTS: VertexLightVSVariation;
export var VLVS_4LIGHTS: VertexLightVSVariation;
export var MAX_VERTEXLIGHT_VS_VARIATIONS: VertexLightVSVariation;
// enum LightPSVariation
export type LightPSVariation = number;
export var LPS_NONE: LightPSVariation;
export var LPS_SPOT: LightPSVariation;
export var LPS_POINT: LightPSVariation;
export var LPS_POINTMASK: LightPSVariation;
export var LPS_SPEC: LightPSVariation;
export var LPS_SPOTSPEC: LightPSVariation;
export var LPS_POINTSPEC: LightPSVariation;
export var LPS_POINTMASKSPEC: LightPSVariation;
export var LPS_SHADOW: LightPSVariation;
export var LPS_SPOTSHADOW: LightPSVariation;
export var LPS_POINTSHADOW: LightPSVariation;
export var LPS_POINTMASKSHADOW: LightPSVariation;
export var LPS_SHADOWSPEC: LightPSVariation;
export var LPS_SPOTSHADOWSPEC: LightPSVariation;
export var LPS_POINTSHADOWSPEC: LightPSVariation;
export var LPS_POINTMASKSHADOWSPEC: LightPSVariation;
export var MAX_LIGHT_PS_VARIATIONS: LightPSVariation;
// enum DeferredLightVSVariation
export type DeferredLightVSVariation = number;
export var DLVS_NONE: DeferredLightVSVariation;
export var DLVS_DIR: DeferredLightVSVariation;
export var DLVS_ORTHO: DeferredLightVSVariation;
export var DLVS_ORTHODIR: DeferredLightVSVariation;
export var MAX_DEFERRED_LIGHT_VS_VARIATIONS: DeferredLightVSVariation;
// enum DeferredLightPSVariation
export type DeferredLightPSVariation = number;
export var DLPS_NONE: DeferredLightPSVariation;
export var DLPS_SPOT: DeferredLightPSVariation;
export var DLPS_POINT: DeferredLightPSVariation;
export var DLPS_POINTMASK: DeferredLightPSVariation;
export var DLPS_SPEC: DeferredLightPSVariation;
export var DLPS_SPOTSPEC: DeferredLightPSVariation;
export var DLPS_POINTSPEC: DeferredLightPSVariation;
export var DLPS_POINTMASKSPEC: DeferredLightPSVariation;
export var DLPS_SHADOW: DeferredLightPSVariation;
export var DLPS_SPOTSHADOW: DeferredLightPSVariation;
export var DLPS_POINTSHADOW: DeferredLightPSVariation;
export var DLPS_POINTMASKSHADOW: DeferredLightPSVariation;
export var DLPS_SHADOWSPEC: DeferredLightPSVariation;
export var DLPS_SPOTSHADOWSPEC: DeferredLightPSVariation;
export var DLPS_POINTSHADOWSPEC: DeferredLightPSVariation;
export var DLPS_POINTMASKSHADOWSPEC: DeferredLightPSVariation;
export var DLPS_ORTHO: DeferredLightPSVariation;
export var DLPS_ORTHOSPOT: DeferredLightPSVariation;
export var DLPS_ORTHOPOINT: DeferredLightPSVariation;
export var DLPS_ORTHOPOINTMASK: DeferredLightPSVariation;
export var DLPS_ORTHOSPEC: DeferredLightPSVariation;
export var DLPS_ORTHOSPOTSPEC: DeferredLightPSVariation;
export var DLPS_ORTHOPOINTSPEC: DeferredLightPSVariation;
export var DLPS_ORTHOPOINTMASKSPEC: DeferredLightPSVariation;
export var DLPS_ORTHOSHADOW: DeferredLightPSVariation;
export var DLPS_ORTHOSPOTSHADOW: DeferredLightPSVariation;
export var DLPS_ORTHOPOINTSHADOW: DeferredLightPSVariation;
export var DLPS_ORTHOPOINTMASKSHADOW: DeferredLightPSVariation;
export var DLPS_ORTHOSHADOWSPEC: DeferredLightPSVariation;
export var DLPS_ORTHOSPOTSHADOWSPEC: DeferredLightPSVariation;
export var DLPS_ORTHOPOINTSHADOWSPEC: DeferredLightPSVariation;
export var DLPS_ORTHOPOINTMASKSHADOWSPEC: DeferredLightPSVariation;
export var MAX_DEFERRED_LIGHT_PS_VARIATIONS: DeferredLightPSVariation;
// enum RenderCommandType
export type RenderCommandType = number;
export var CMD_NONE: RenderCommandType;
export var CMD_CLEAR: RenderCommandType;
export var CMD_SCENEPASS: RenderCommandType;
export var CMD_QUAD: RenderCommandType;
export var CMD_FORWARDLIGHTS: RenderCommandType;
export var CMD_LIGHTVOLUMES: RenderCommandType;
export var CMD_RENDERUI: RenderCommandType;
// enum RenderCommandSortMode
export type RenderCommandSortMode = number;
export var SORT_FRONTTOBACK: RenderCommandSortMode;
export var SORT_BACKTOFRONT: RenderCommandSortMode;
// enum RenderTargetSizeMode
export type RenderTargetSizeMode = number;
export var SIZE_ABSOLUTE: RenderTargetSizeMode;
export var SIZE_VIEWPORTDIVISOR: RenderTargetSizeMode;
export var SIZE_VIEWPORTMULTIPLIER: RenderTargetSizeMode;
// enum PassLightingMode
export type PassLightingMode = number;
export var LIGHTING_UNLIT: PassLightingMode;
export var LIGHTING_PERVERTEX: PassLightingMode;
export var LIGHTING_PERPIXEL: PassLightingMode;
// enum EmitterType
export type EmitterType = number;
export var EMITTER_SPHERE: EmitterType;
export var EMITTER_BOX: EmitterType;
// enum LoopMode2D
export type LoopMode2D = number;
export var LM_DEFAULT: LoopMode2D;
export var LM_FORCE_LOOPED: LoopMode2D;
export var LM_FORCE_CLAMPED: LoopMode2D;
// enum LightType2D
export type LightType2D = number;
export var LIGHT2D_DIRECTIONAL: LightType2D;
export var LIGHT2D_POINT: LightType2D;
// enum EmitterType2D
export type EmitterType2D = number;
export var EMITTER_TYPE_GRAVITY: EmitterType2D;
export var EMITTER_TYPE_RADIAL: EmitterType2D;
// enum BodyType2D
export type BodyType2D = number;
export var BT_STATIC: BodyType2D;
export var BT_DYNAMIC: BodyType2D;
export var BT_KINEMATIC: BodyType2D;
// enum Orientation2D
export type Orientation2D = number;
export var O_ORTHOGONAL: Orientation2D;
export var O_ISOMETRIC: Orientation2D;
export var O_STAGGERED: Orientation2D;
// enum TileMapLayerType2D
export type TileMapLayerType2D = number;
export var LT_TILE_LAYER: TileMapLayerType2D;
export var LT_OBJECT_GROUP: TileMapLayerType2D;
export var LT_IMAGE_LAYER: TileMapLayerType2D;
export var LT_INVALID: TileMapLayerType2D;
// enum TileMapObjectType2D
export type TileMapObjectType2D = number;
export var OT_RECTANGLE: TileMapObjectType2D;
export var OT_ELLIPSE: TileMapObjectType2D;
export var OT_POLYGON: TileMapObjectType2D;
export var OT_POLYLINE: TileMapObjectType2D;
export var OT_TILE: TileMapObjectType2D;
export var OT_INVALID: TileMapObjectType2D;
// enum ShapeType
export type ShapeType = number;
export var SHAPE_BOX: ShapeType;
export var SHAPE_SPHERE: ShapeType;
export var SHAPE_STATICPLANE: ShapeType;
export var SHAPE_CYLINDER: ShapeType;
export var SHAPE_CAPSULE: ShapeType;
export var SHAPE_CONE: ShapeType;
export var SHAPE_TRIANGLEMESH: ShapeType;
export var SHAPE_CONVEXHULL: ShapeType;
export var SHAPE_TERRAIN: ShapeType;
// enum ConstraintType
export type ConstraintType = number;
export var CONSTRAINT_POINT: ConstraintType;
export var CONSTRAINT_HINGE: ConstraintType;
export var CONSTRAINT_SLIDER: ConstraintType;
export var CONSTRAINT_CONETWIST: ConstraintType;
// enum CollisionEventMode
export type CollisionEventMode = number;
export var COLLISION_NEVER: CollisionEventMode;
export var COLLISION_ACTIVE: CollisionEventMode;
export var COLLISION_ALWAYS: CollisionEventMode;
// enum CrowdTargetState
export type CrowdTargetState = number;
export var CROWD_AGENT_TARGET_NONE: CrowdTargetState;
export var CROWD_AGENT_TARGET_FAILED: CrowdTargetState;
export var CROWD_AGENT_TARGET_VALID: CrowdTargetState;
export var CROWD_AGENT_TARGET_REQUESTING: CrowdTargetState;
export var CROWD_AGENT_TARGET_WAITINGFORQUEUE: CrowdTargetState;
export var CROWD_AGENT_TARGET_WAITINGFORPATH: CrowdTargetState;
export var CROWD_AGENT_TARGET_VELOCITY: CrowdTargetState;
// enum CrowdAgentState
export type CrowdAgentState = number;
export var CROWD_AGENT_INVALID: CrowdAgentState;
export var CROWD_AGENT_READY: CrowdAgentState;
export var CROWD_AGENT_TRAVERSINGLINK: CrowdAgentState;
// enum NavigationQuality
export type NavigationQuality = number;
export var NAVIGATIONQUALITY_LOW: NavigationQuality;
export var NAVIGATIONQUALITY_MEDIUM: NavigationQuality;
export var NAVIGATIONQUALITY_HIGH: NavigationQuality;
// enum NavigationPushiness
export type NavigationPushiness = number;
export var PUSHINESS_LOW: NavigationPushiness;
export var PUSHINESS_MEDIUM: NavigationPushiness;
export var PUSHINESS_HIGH: NavigationPushiness;
// enum NavmeshPartitionType
export type NavmeshPartitionType = number;
export var NAVMESH_PARTITION_WATERSHED: NavmeshPartitionType;
export var NAVMESH_PARTITION_MONOTONE: NavmeshPartitionType;
// enum MouseMode
export type MouseMode = number;
export var MM_ABSOLUTE: MouseMode;
export var MM_RELATIVE: MouseMode;
export var MM_WRAP: MouseMode;
// enum TEXT_ALIGN
export type TEXT_ALIGN = number;
export var TEXT_ALIGN_LEFT: TEXT_ALIGN;
export var TEXT_ALIGN_RIGHT: TEXT_ALIGN;
export var TEXT_ALIGN_CENTER: TEXT_ALIGN;
// enum UI_EDIT_TYPE
export type UI_EDIT_TYPE = number;
export var UI_EDIT_TYPE_TEXT: UI_EDIT_TYPE;
export var UI_EDIT_TYPE_SEARCH: UI_EDIT_TYPE;
export var UI_EDIT_TYPE_PASSWORD: UI_EDIT_TYPE;
export var UI_EDIT_TYPE_EMAIL: UI_EDIT_TYPE;
export var UI_EDIT_TYPE_PHONE: UI_EDIT_TYPE;
export var UI_EDIT_TYPE_URL: UI_EDIT_TYPE;
export var UI_EDIT_TYPE_NUMBER: UI_EDIT_TYPE;
// enum UI_AXIS
export type UI_AXIS = number;
export var UI_AXIS_X: UI_AXIS;
export var UI_AXIS_Y: UI_AXIS;
// enum UI_LAYOUT_SIZE
export type UI_LAYOUT_SIZE = number;
export var UI_LAYOUT_SIZE_GRAVITY: UI_LAYOUT_SIZE;
export var UI_LAYOUT_SIZE_PREFERRED: UI_LAYOUT_SIZE;
export var UI_LAYOUT_SIZE_AVAILABLE: UI_LAYOUT_SIZE;
// enum UI_LAYOUT_DISTRIBUTION
export type UI_LAYOUT_DISTRIBUTION = number;
export var UI_LAYOUT_DISTRIBUTION_PREFERRED: UI_LAYOUT_DISTRIBUTION;
export var UI_LAYOUT_DISTRIBUTION_AVAILABLE: UI_LAYOUT_DISTRIBUTION;
export var UI_LAYOUT_DISTRIBUTION_GRAVITY: UI_LAYOUT_DISTRIBUTION;
// enum UI_LAYOUT_POSITION
export type UI_LAYOUT_POSITION = number;
export var UI_LAYOUT_POSITION_CENTER: UI_LAYOUT_POSITION;
export var UI_LAYOUT_POSITION_LEFT_TOP: UI_LAYOUT_POSITION;
export var UI_LAYOUT_POSITION_RIGHT_BOTTOM: UI_LAYOUT_POSITION;
export var UI_LAYOUT_POSITION_GRAVITY: UI_LAYOUT_POSITION;
// enum UI_LAYOUT_DISTRIBUTION_POSITION
export type UI_LAYOUT_DISTRIBUTION_POSITION = number;
export var UI_LAYOUT_DISTRIBUTION_POSITION_CENTER: UI_LAYOUT_DISTRIBUTION_POSITION;
export var UI_LAYOUT_DISTRIBUTION_POSITION_LEFT_TOP: UI_LAYOUT_DISTRIBUTION_POSITION;
export var UI_LAYOUT_DISTRIBUTION_POSITION_RIGHT_BOTTOM: UI_LAYOUT_DISTRIBUTION_POSITION;
// enum UI_MESSAGEWINDOW_SETTINGS
export type UI_MESSAGEWINDOW_SETTINGS = number;
export var UI_MESSAGEWINDOW_SETTINGS_OK: UI_MESSAGEWINDOW_SETTINGS;
export var UI_MESSAGEWINDOW_SETTINGS_OK_CANCEL: UI_MESSAGEWINDOW_SETTINGS;
export var UI_MESSAGEWINDOW_SETTINGS_YES_NO: UI_MESSAGEWINDOW_SETTINGS;
// enum UI_SIZE_DEP
export type UI_SIZE_DEP = number;
export var UI_SIZE_DEP_NONE: UI_SIZE_DEP;
export var UI_SIZE_DEP_WIDTH_DEPEND_ON_HEIGHT: UI_SIZE_DEP;
export var UI_SIZE_DEP_HEIGHT_DEPEND_ON_WIDTH: UI_SIZE_DEP;
export var UI_SIZE_DEP_BOTH: UI_SIZE_DEP;
// enum UI_SCROLL_MODE
export type UI_SCROLL_MODE = number;
export var UI_SCROLL_MODE_X_Y: UI_SCROLL_MODE;
export var UI_SCROLL_MODE_Y: UI_SCROLL_MODE;
export var UI_SCROLL_MODE_Y_AUTO: UI_SCROLL_MODE;
export var UI_SCROLL_MODE_X_AUTO_Y_AUTO: UI_SCROLL_MODE;
export var UI_SCROLL_MODE_OFF: UI_SCROLL_MODE;
// enum UI_TEXT_ALIGN
export type UI_TEXT_ALIGN = number;
export var UI_TEXT_ALIGN_LEFT: UI_TEXT_ALIGN;
export var UI_TEXT_ALIGN_RIGHT: UI_TEXT_ALIGN;
export var UI_TEXT_ALIGN_CENTER: UI_TEXT_ALIGN;
// enum UI_WIDGET_VISIBILITY
export type UI_WIDGET_VISIBILITY = number;
export var UI_WIDGET_VISIBILITY_VISIBLE: UI_WIDGET_VISIBILITY;
export var UI_WIDGET_VISIBILITY_INVISIBLE: UI_WIDGET_VISIBILITY;
export var UI_WIDGET_VISIBILITY_GONE: UI_WIDGET_VISIBILITY;
// enum UI_GRAVITY
export type UI_GRAVITY = number;
export var UI_GRAVITY_NONE: UI_GRAVITY;
export var UI_GRAVITY_LEFT: UI_GRAVITY;
export var UI_GRAVITY_RIGHT: UI_GRAVITY;
export var UI_GRAVITY_TOP: UI_GRAVITY;
export var UI_GRAVITY_BOTTOM: UI_GRAVITY;
export var UI_GRAVITY_LEFT_RIGHT: UI_GRAVITY;
export var UI_GRAVITY_TOP_BOTTOM: UI_GRAVITY;
export var UI_GRAVITY_ALL: UI_GRAVITY;
export var UI_GRAVITY_DEFAULT: UI_GRAVITY;
// enum UI_EVENT_TYPE
export type UI_EVENT_TYPE = number;
export var UI_EVENT_TYPE_CLICK: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_LONG_CLICK: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_POINTER_DOWN: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_POINTER_UP: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_POINTER_MOVE: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_RIGHT_POINTER_DOWN: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_RIGHT_POINTER_UP: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_WHEEL: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_CHANGED: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_KEY_DOWN: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_KEY_UP: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_SHORTCUT: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_CONTEXT_MENU: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_FILE_DROP: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_TAB_CHANGED: UI_EVENT_TYPE;
export var UI_EVENT_TYPE_CUSTOM: UI_EVENT_TYPE;
// enum UI_WIDGET_Z_REL
export type UI_WIDGET_Z_REL = number;
export var UI_WIDGET_Z_REL_BEFORE: UI_WIDGET_Z_REL;
export var UI_WIDGET_Z_REL_AFTER: UI_WIDGET_Z_REL;
// enum UI_WINDOW_SETTINGS
export type UI_WINDOW_SETTINGS = number;
export var UI_WINDOW_SETTINGS_NONE: UI_WINDOW_SETTINGS;
export var UI_WINDOW_SETTINGS_TITLEBAR: UI_WINDOW_SETTINGS;
export var UI_WINDOW_SETTINGS_RESIZABLE: UI_WINDOW_SETTINGS;
export var UI_WINDOW_SETTINGS_CLOSE_BUTTON: UI_WINDOW_SETTINGS;
export var UI_WINDOW_SETTINGS_CAN_ACTIVATE: UI_WINDOW_SETTINGS;
export var UI_WINDOW_SETTINGS_DEFAULT: UI_WINDOW_SETTINGS;
// enum CompressedFormat
export type CompressedFormat = number;
export var CF_NONE: CompressedFormat;
export var CF_RGBA: CompressedFormat;
export var CF_DXT1: CompressedFormat;
export var CF_DXT3: CompressedFormat;
export var CF_DXT5: CompressedFormat;
export var CF_ETC1: CompressedFormat;
export var CF_PVRTC_RGB_2BPP: CompressedFormat;
export var CF_PVRTC_RGBA_2BPP: CompressedFormat;
export var CF_PVRTC_RGB_4BPP: CompressedFormat;
export var CF_PVRTC_RGBA_4BPP: CompressedFormat;
// enum JSONValueType
export type JSONValueType = number;
export var JSON_ANY: JSONValueType;
export var JSON_OBJECT: JSONValueType;
export var JSON_ARRAY: JSONValueType;
// enum PListValueType
export type PListValueType = number;
export var PLVT_NONE: PListValueType;
export var PLVT_INT: PListValueType;
export var PLVT_BOOL: PListValueType;
export var PLVT_FLOAT: PListValueType;
export var PLVT_STRING: PListValueType;
export var PLVT_VALUEMAP: PListValueType;
export var PLVT_VALUEVECTOR: PListValueType;
// enum AsyncLoadState
export type AsyncLoadState = number;
export var ASYNC_DONE: AsyncLoadState;
export var ASYNC_QUEUED: AsyncLoadState;
export var ASYNC_LOADING: AsyncLoadState;
export var ASYNC_SUCCESS: AsyncLoadState;
export var ASYNC_FAIL: AsyncLoadState;
// enum ResourceRequest
export type ResourceRequest = number;
export var RESOURCE_CHECKEXISTS: ResourceRequest;
export var RESOURCE_GETFILE: ResourceRequest;
// enum ObserverPositionSendMode
export type ObserverPositionSendMode = number;
export var OPSM_NONE: ObserverPositionSendMode;
export var OPSM_POSITION: ObserverPositionSendMode;
export var OPSM_POSITION_ROTATION: ObserverPositionSendMode;
// enum HttpRequestState
export type HttpRequestState = number;
export var HTTP_INITIALIZING: HttpRequestState;
export var HTTP_ERROR: HttpRequestState;
export var HTTP_OPEN: HttpRequestState;
export var HTTP_CLOSED: HttpRequestState;
// enum FileMode
export type FileMode = number;
export var FILE_READ: FileMode;
export var FILE_WRITE: FileMode;
export var FILE_READWRITE: FileMode;
export var QUICKSORT_THRESHOLD: number;
export var CONVERSION_BUFFER_LENGTH: number;
export var MATRIX_CONVERSION_BUFFER_LENGTH: number;
export var NUM_FRUSTUM_PLANES: number;
export var NUM_FRUSTUM_VERTICES: number;
export var M_PI: number;
export var M_HALF_PI: number;
export var M_MIN_INT: number;
export var M_MAX_INT: number;
export var M_MIN_UNSIGNED: number;
export var M_MAX_UNSIGNED: number;
export var M_EPSILON: number;
export var M_LARGE_EPSILON: number;
export var M_MIN_NEARCLIP: number;
export var M_MAX_FOV: number;
export var M_LARGE_VALUE: number;
export var M_INFINITY: number;
export var M_DEGTORAD: number;
export var M_DEGTORAD_2: number;
export var M_RADTODEG: number;
export var AM_EDIT: number;
export var AM_FILE: number;
export var AM_NET: number;
export var AM_DEFAULT: number;
export var AM_LATESTDATA: number;
export var AM_NOEDIT: number;
export var AM_NODEID: number;
export var AM_COMPONENTID: number;
export var AM_NODEIDVECTOR: number;
export var USE_UPDATE: number;
export var USE_POSTUPDATE: number;
export var USE_FIXEDUPDATE: number;
export var USE_FIXEDPOSTUPDATE: number;
export var MAX_NETWORK_ATTRIBUTES: number;
export var FIRST_REPLICATED_ID: number;
export var LAST_REPLICATED_ID: number;
export var FIRST_LOCAL_ID: number;
export var LAST_LOCAL_ID: number;
export var SMOOTH_NONE: number;
export var SMOOTH_POSITION: number;
export var SMOOTH_ROTATION: number;
export var DEFAULT_NEARCLIP: number;
export var DEFAULT_FARCLIP: number;
export var DEFAULT_CAMERA_FOV: number;
export var DEFAULT_ORTHOSIZE: number;
export var VO_NONE: number;
export var VO_LOW_MATERIAL_QUALITY: number;
export var VO_DISABLE_SHADOWS: number;
export var VO_DISABLE_OCCLUSION: number;
export var DRAWABLE_GEOMETRY: number;
export var DRAWABLE_LIGHT: number;
export var DRAWABLE_ZONE: number;
export var DRAWABLE_GEOMETRY2D: number;
export var DRAWABLE_ANY: number;
export var DEFAULT_VIEWMASK: number;
export var DEFAULT_LIGHTMASK: number;
export var DEFAULT_SHADOWMASK: number;
export var DEFAULT_ZONEMASK: number;
export var MAX_VERTEX_LIGHTS: number;
export var ANIMATION_LOD_BASESCALE: number;
export var QUALITY_LOW: number;
export var QUALITY_MEDIUM: number;
export var QUALITY_HIGH: number;
export var QUALITY_MAX: number;
export var SHADOWQUALITY_LOW_16BIT: number;
export var SHADOWQUALITY_LOW_24BIT: number;
export var SHADOWQUALITY_HIGH_16BIT: number;
export var SHADOWQUALITY_HIGH_24BIT: number;
export var CLEAR_COLOR: number;
export var CLEAR_DEPTH: number;
export var CLEAR_STENCIL: number;
export var MASK_NONE: number;
export var MASK_POSITION: number;
export var MASK_NORMAL: number;
export var MASK_COLOR: number;
export var MASK_TEXCOORD1: number;
export var MASK_TEXCOORD2: number;
export var MASK_CUBETEXCOORD1: number;
export var MASK_CUBETEXCOORD2: number;
export var MASK_TANGENT: number;
export var MASK_BLENDWEIGHTS: number;
export var MASK_BLENDINDICES: number;
export var MASK_INSTANCEMATRIX1: number;
export var MASK_INSTANCEMATRIX2: number;
export var MASK_INSTANCEMATRIX3: number;
export var MASK_DEFAULT: number;
export var NO_ELEMENT: number;
export var MAX_RENDERTARGETS: number;
export var MAX_VERTEX_STREAMS: number;
export var MAX_CONSTANT_REGISTERS: number;
export var BITS_PER_COMPONENT: number;
export var SHADOW_MIN_QUANTIZE: number;
export var SHADOW_MIN_VIEW: number;
export var MAX_LIGHT_SPLITS: number;
export var MAX_CASCADE_SPLITS: number;
export var OCCLUSION_MIN_SIZE: number;
export var OCCLUSION_DEFAULT_MAX_TRIANGLES: number;
export var OCCLUSION_RELATIVE_BIAS: number;
export var OCCLUSION_FIXED_BIAS: number;
export var OCCLUSION_X_SCALE: number;
export var OCCLUSION_Z_SCALE: number;
export var NUM_OCTANTS: number;
export var ROOT_INDEX: number;
export var SHADOW_MIN_PIXELS: number;
export var INSTANCING_BUFFER_DEFAULT_SIZE: number;
export var MAX_VIEWPORT_TEXTURES: number;
export var NUM_SCREEN_BUFFERS: number;
export var MAX_TEXTURE_QUALITY_LEVELS: number;
export var CHANNEL_POSITION: number;
export var CHANNEL_ROTATION: number;
export var CHANNEL_SCALE: number;
export var MAX_BILLBOARDS: number;
export var DEFAULT_NUM_PARTICLES: number;
export var BONECOLLISION_NONE: number;
export var BONECOLLISION_SPHERE: number;
export var BONECOLLISION_BOX: number;
export var PIXEL_SIZE: number;
export var STREAM_BUFFER_LENGTH: number;
export var DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY: number;
export var MOUSEB_LEFT: number;
export var MOUSEB_MIDDLE: number;
export var MOUSEB_RIGHT: number;
export var MOUSEB_X1: number;
export var MOUSEB_X2: number;
export var QUAL_SHIFT: number;
export var QUAL_CTRL: number;
export var QUAL_ALT: number;
export var QUAL_ANY: number;
export var KEY_A: number;
export var KEY_B: number;
export var KEY_C: number;
export var KEY_D: number;
export var KEY_E: number;
export var KEY_F: number;
export var KEY_G: number;
export var KEY_H: number;
export var KEY_I: number;
export var KEY_J: number;
export var KEY_K: number;
export var KEY_L: number;
export var KEY_M: number;
export var KEY_N: number;
export var KEY_O: number;
export var KEY_P: number;
export var KEY_Q: number;
export var KEY_R: number;
export var KEY_S: number;
export var KEY_T: number;
export var KEY_U: number;
export var KEY_V: number;
export var KEY_W: number;
export var KEY_X: number;
export var KEY_Y: number;
export var KEY_Z: number;
export var KEY_0: number;
export var KEY_1: number;
export var KEY_2: number;
export var KEY_3: number;
export var KEY_4: number;
export var KEY_5: number;
export var KEY_6: number;
export var KEY_7: number;
export var KEY_8: number;
export var KEY_9: number;
export var KEY_BACKSPACE: number;
export var KEY_TAB: number;
export var KEY_RETURN: number;
export var KEY_RETURN2: number;
export var KEY_KP_ENTER: number;
export var KEY_SHIFT: number;
export var KEY_CTRL: number;
export var KEY_ALT: number;
export var KEY_GUI: number;
export var KEY_PAUSE: number;
export var KEY_CAPSLOCK: number;
export var KEY_ESC: number;
export var KEY_SPACE: number;
export var KEY_PAGEUP: number;
export var KEY_PAGEDOWN: number;
export var KEY_END: number;
export var KEY_HOME: number;
export var KEY_LEFT: number;
export var KEY_UP: number;
export var KEY_RIGHT: number;
export var KEY_DOWN: number;
export var KEY_SELECT: number;
export var KEY_PRINTSCREEN: number;
export var KEY_INSERT: number;
export var KEY_DELETE: number;
export var KEY_LGUI: number;
export var KEY_RGUI: number;
export var KEY_APPLICATION: number;
export var KEY_KP_0: number;
export var KEY_KP_1: number;
export var KEY_KP_2: number;
export var KEY_KP_3: number;
export var KEY_KP_4: number;
export var KEY_KP_5: number;
export var KEY_KP_6: number;
export var KEY_KP_7: number;
export var KEY_KP_8: number;
export var KEY_KP_9: number;
export var KEY_KP_MULTIPLY: number;
export var KEY_KP_PLUS: number;
export var KEY_KP_MINUS: number;
export var KEY_KP_PERIOD: number;
export var KEY_KP_DIVIDE: number;
export var KEY_F1: number;
export var KEY_F2: number;
export var KEY_F3: number;
export var KEY_F4: number;
export var KEY_F5: number;
export var KEY_F6: number;
export var KEY_F7: number;
export var KEY_F8: number;
export var KEY_F9: number;
export var KEY_F10: number;
export var KEY_F11: number;
export var KEY_F12: number;
export var KEY_F13: number;
export var KEY_F14: number;
export var KEY_F15: number;
export var KEY_F16: number;
export var KEY_F17: number;
export var KEY_F18: number;
export var KEY_F19: number;
export var KEY_F20: number;
export var KEY_F21: number;
export var KEY_F22: number;
export var KEY_F23: number;
export var KEY_F24: number;
export var KEY_NUMLOCKCLEAR: number;
export var KEY_SCROLLLOCK: number;
export var KEY_LSHIFT: number;
export var KEY_RSHIFT: number;
export var KEY_LCTRL: number;
export var KEY_RCTRL: number;
export var KEY_LALT: number;
export var KEY_RALT: number;
export var SCANCODE_UNKNOWN: number;
export var SCANCODE_CTRL: number;
export var SCANCODE_SHIFT: number;
export var SCANCODE_ALT: number;
export var SCANCODE_GUI: number;
export var SCANCODE_A: number;
export var SCANCODE_B: number;
export var SCANCODE_C: number;
export var SCANCODE_D: number;
export var SCANCODE_E: number;
export var SCANCODE_F: number;
export var SCANCODE_G: number;
export var SCANCODE_H: number;
export var SCANCODE_I: number;
export var SCANCODE_J: number;
export var SCANCODE_K: number;
export var SCANCODE_L: number;
export var SCANCODE_M: number;
export var SCANCODE_N: number;
export var SCANCODE_O: number;
export var SCANCODE_P: number;
export var SCANCODE_Q: number;
export var SCANCODE_R: number;
export var SCANCODE_S: number;
export var SCANCODE_T: number;
export var SCANCODE_U: number;
export var SCANCODE_V: number;
export var SCANCODE_W: number;
export var SCANCODE_X: number;
export var SCANCODE_Y: number;
export var SCANCODE_Z: number;
export var SCANCODE_1: number;
export var SCANCODE_2: number;
export var SCANCODE_3: number;
export var SCANCODE_4: number;
export var SCANCODE_5: number;
export var SCANCODE_6: number;
export var SCANCODE_7: number;
export var SCANCODE_8: number;
export var SCANCODE_9: number;
export var SCANCODE_0: number;
export var SCANCODE_RETURN: number;
export var SCANCODE_ESCAPE: number;
export var SCANCODE_BACKSPACE: number;
export var SCANCODE_TAB: number;
export var SCANCODE_SPACE: number;
export var SCANCODE_MINUS: number;
export var SCANCODE_EQUALS: number;
export var SCANCODE_LEFTBRACKET: number;
export var SCANCODE_RIGHTBRACKET: number;
export var SCANCODE_BACKSLASH: number;
export var SCANCODE_NONUSHASH: number;
export var SCANCODE_SEMICOLON: number;
export var SCANCODE_APOSTROPHE: number;
export var SCANCODE_GRAVE: number;
export var SCANCODE_COMMA: number;
export var SCANCODE_PERIOD: number;
export var SCANCODE_SLASH: number;
export var SCANCODE_CAPSLOCK: number;
export var SCANCODE_F1: number;
export var SCANCODE_F2: number;
export var SCANCODE_F3: number;
export var SCANCODE_F4: number;
export var SCANCODE_F5: number;
export var SCANCODE_F6: number;
export var SCANCODE_F7: number;
export var SCANCODE_F8: number;
export var SCANCODE_F9: number;
export var SCANCODE_F10: number;
export var SCANCODE_F11: number;
export var SCANCODE_F12: number;
export var SCANCODE_PRINTSCREEN: number;
export var SCANCODE_SCROLLLOCK: number;
export var SCANCODE_PAUSE: number;
export var SCANCODE_INSERT: number;
export var SCANCODE_HOME: number;
export var SCANCODE_PAGEUP: number;
export var SCANCODE_DELETE: number;
export var SCANCODE_END: number;
export var SCANCODE_PAGEDOWN: number;
export var SCANCODE_RIGHT: number;
export var SCANCODE_LEFT: number;
export var SCANCODE_DOWN: number;
export var SCANCODE_UP: number;
export var SCANCODE_NUMLOCKCLEAR: number;
export var SCANCODE_KP_DIVIDE: number;
export var SCANCODE_KP_MULTIPLY: number;
export var SCANCODE_KP_MINUS: number;
export var SCANCODE_KP_PLUS: number;
export var SCANCODE_KP_ENTER: number;
export var SCANCODE_KP_1: number;
export var SCANCODE_KP_2: number;
export var SCANCODE_KP_3: number;
export var SCANCODE_KP_4: number;
export var SCANCODE_KP_5: number;
export var SCANCODE_KP_6: number;
export var SCANCODE_KP_7: number;
export var SCANCODE_KP_8: number;
export var SCANCODE_KP_9: number;
export var SCANCODE_KP_0: number;
export var SCANCODE_KP_PERIOD: number;
export var SCANCODE_NONUSBACKSLASH: number;
export var SCANCODE_APPLICATION: number;
export var SCANCODE_POWER: number;
export var SCANCODE_KP_EQUALS: number;
export var SCANCODE_F13: number;
export var SCANCODE_F14: number;
export var SCANCODE_F15: number;
export var SCANCODE_F16: number;
export var SCANCODE_F17: number;
export var SCANCODE_F18: number;
export var SCANCODE_F19: number;
export var SCANCODE_F20: number;
export var SCANCODE_F21: number;
export var SCANCODE_F22: number;
export var SCANCODE_F23: number;
export var SCANCODE_F24: number;
export var SCANCODE_EXECUTE: number;
export var SCANCODE_HELP: number;
export var SCANCODE_MENU: number;
export var SCANCODE_SELECT: number;
export var SCANCODE_STOP: number;
export var SCANCODE_AGAIN: number;
export var SCANCODE_UNDO: number;
export var SCANCODE_CUT: number;
export var SCANCODE_COPY: number;
export var SCANCODE_PASTE: number;
export var SCANCODE_FIND: number;
export var SCANCODE_MUTE: number;
export var SCANCODE_VOLUMEUP: number;
export var SCANCODE_VOLUMEDOWN: number;
export var SCANCODE_KP_COMMA: number;
export var SCANCODE_KP_EQUALSAS400: number;
export var SCANCODE_INTERNATIONAL1: number;
export var SCANCODE_INTERNATIONAL2: number;
export var SCANCODE_INTERNATIONAL3: number;
export var SCANCODE_INTERNATIONAL4: number;
export var SCANCODE_INTERNATIONAL5: number;
export var SCANCODE_INTERNATIONAL6: number;
export var SCANCODE_INTERNATIONAL7: number;
export var SCANCODE_INTERNATIONAL8: number;
export var SCANCODE_INTERNATIONAL9: number;
export var SCANCODE_LANG1: number;
export var SCANCODE_LANG2: number;
export var SCANCODE_LANG3: number;
export var SCANCODE_LANG4: number;
export var SCANCODE_LANG5: number;
export var SCANCODE_LANG6: number;
export var SCANCODE_LANG7: number;
export var SCANCODE_LANG8: number;
export var SCANCODE_LANG9: number;
export var SCANCODE_ALTERASE: number;
export var SCANCODE_SYSREQ: number;
export var SCANCODE_CANCEL: number;
export var SCANCODE_CLEAR: number;
export var SCANCODE_PRIOR: number;
export var SCANCODE_RETURN2: number;
export var SCANCODE_SEPARATOR: number;
export var SCANCODE_OUT: number;
export var SCANCODE_OPER: number;
export var SCANCODE_CLEARAGAIN: number;
export var SCANCODE_CRSEL: number;
export var SCANCODE_EXSEL: number;
export var SCANCODE_KP_00: number;
export var SCANCODE_KP_000: number;
export var SCANCODE_THOUSANDSSEPARATOR: number;
export var SCANCODE_DECIMALSEPARATOR: number;
export var SCANCODE_CURRENCYUNIT: number;
export var SCANCODE_CURRENCYSUBUNIT: number;
export var SCANCODE_KP_LEFTPAREN: number;
export var SCANCODE_KP_RIGHTPAREN: number;
export var SCANCODE_KP_LEFTBRACE: number;
export var SCANCODE_KP_RIGHTBRACE: number;
export var SCANCODE_KP_TAB: number;
export var SCANCODE_KP_BACKSPACE: number;
export var SCANCODE_KP_A: number;
export var SCANCODE_KP_B: number;
export var SCANCODE_KP_C: number;
export var SCANCODE_KP_D: number;
export var SCANCODE_KP_E: number;
export var SCANCODE_KP_F: number;
export var SCANCODE_KP_XOR: number;
export var SCANCODE_KP_POWER: number;
export var SCANCODE_KP_PERCENT: number;
export var SCANCODE_KP_LESS: number;
export var SCANCODE_KP_GREATER: number;
export var SCANCODE_KP_AMPERSAND: number;
export var SCANCODE_KP_DBLAMPERSAND: number;
export var SCANCODE_KP_VERTICALBAR: number;
export var SCANCODE_KP_DBLVERTICALBAR: number;
export var SCANCODE_KP_COLON: number;
export var SCANCODE_KP_HASH: number;
export var SCANCODE_KP_SPACE: number;
export var SCANCODE_KP_AT: number;
export var SCANCODE_KP_EXCLAM: number;
export var SCANCODE_KP_MEMSTORE: number;
export var SCANCODE_KP_MEMRECALL: number;
export var SCANCODE_KP_MEMCLEAR: number;
export var SCANCODE_KP_MEMADD: number;
export var SCANCODE_KP_MEMSUBTRACT: number;
export var SCANCODE_KP_MEMMULTIPLY: number;
export var SCANCODE_KP_MEMDIVIDE: number;
export var SCANCODE_KP_PLUSMINUS: number;
export var SCANCODE_KP_CLEAR: number;
export var SCANCODE_KP_CLEARENTRY: number;
export var SCANCODE_KP_BINARY: number;
export var SCANCODE_KP_OCTAL: number;
export var SCANCODE_KP_DECIMAL: number;
export var SCANCODE_KP_HEXADECIMAL: number;
export var SCANCODE_LCTRL: number;
export var SCANCODE_LSHIFT: number;
export var SCANCODE_LALT: number;
export var SCANCODE_LGUI: number;
export var SCANCODE_RCTRL: number;
export var SCANCODE_RSHIFT: number;
export var SCANCODE_RALT: number;
export var SCANCODE_RGUI: number;
export var SCANCODE_MODE: number;
export var SCANCODE_AUDIONEXT: number;
export var SCANCODE_AUDIOPREV: number;
export var SCANCODE_AUDIOSTOP: number;
export var SCANCODE_AUDIOPLAY: number;
export var SCANCODE_AUDIOMUTE: number;
export var SCANCODE_MEDIASELECT: number;
export var SCANCODE_WWW: number;
export var SCANCODE_MAIL: number;
export var SCANCODE_CALCULATOR: number;
export var SCANCODE_COMPUTER: number;
export var SCANCODE_AC_SEARCH: number;
export var SCANCODE_AC_HOME: number;
export var SCANCODE_AC_BACK: number;
export var SCANCODE_AC_FORWARD: number;
export var SCANCODE_AC_STOP: number;
export var SCANCODE_AC_REFRESH: number;
export var SCANCODE_AC_BOOKMARKS: number;
export var SCANCODE_BRIGHTNESSDOWN: number;
export var SCANCODE_BRIGHTNESSUP: number;
export var SCANCODE_DISPLAYSWITCH: number;
export var SCANCODE_KBDILLUMTOGGLE: number;
export var SCANCODE_KBDILLUMDOWN: number;
export var SCANCODE_KBDILLUMUP: number;
export var SCANCODE_EJECT: number;
export var SCANCODE_SLEEP: number;
export var SCANCODE_APP1: number;
export var SCANCODE_APP2: number;
export var HAT_CENTER: number;
export var HAT_UP: number;
export var HAT_RIGHT: number;
export var HAT_DOWN: number;
export var HAT_LEFT: number;
export var CONTROLLER_BUTTON_A: number;
export var CONTROLLER_BUTTON_B: number;
export var CONTROLLER_BUTTON_X: number;
export var CONTROLLER_BUTTON_Y: number;
export var CONTROLLER_BUTTON_BACK: number;
export var CONTROLLER_BUTTON_GUIDE: number;
export var CONTROLLER_BUTTON_START: number;
export var CONTROLLER_BUTTON_LEFTSTICK: number;
export var CONTROLLER_BUTTON_RIGHTSTICK: number;
export var CONTROLLER_BUTTON_LEFTSHOULDER: number;
export var CONTROLLER_BUTTON_RIGHTSHOULDER: number;
export var CONTROLLER_BUTTON_DPAD_UP: number;
export var CONTROLLER_BUTTON_DPAD_DOWN: number;
export var CONTROLLER_BUTTON_DPAD_LEFT: number;
export var CONTROLLER_BUTTON_DPAD_RIGHT: number;
export var CONTROLLER_AXIS_LEFTX: number;
export var CONTROLLER_AXIS_LEFTY: number;
export var CONTROLLER_AXIS_RIGHTX: number;
export var CONTROLLER_AXIS_RIGHTY: number;
export var CONTROLLER_AXIS_TRIGGERLEFT: number;
export var CONTROLLER_AXIS_TRIGGERRIGHT: number;
export var UI_VERTEX_SIZE: number;
export var COLOR_LUT_SIZE: number;
export var PRIORITY_LAST: number;
export var MSG_IDENTITY: number;
export var MSG_CONTROLS: number;
export var MSG_SCENELOADED: number;
export var MSG_REQUESTPACKAGE: number;
export var MSG_PACKAGEDATA: number;
export var MSG_LOADSCENE: number;
export var MSG_SCENECHECKSUMERROR: number;
export var MSG_CREATENODE: number;
export var MSG_NODEDELTAUPDATE: number;
export var MSG_NODELATESTDATA: number;
export var MSG_REMOVENODE: number;
export var MSG_CREATECOMPONENT: number;
export var MSG_COMPONENTDELTAUPDATE: number;
export var MSG_COMPONENTLATESTDATA: number;
export var MSG_REMOVECOMPONENT: number;
export var MSG_REMOTEEVENT: number;
export var MSG_REMOTENODEEVENT: number;
export var MSG_PACKAGEINFO: number;
export var CONTROLS_CONTENT_ID: number;
export var PACKAGE_FRAGMENT_SIZE: number;
export var SCAN_FILES: number;
export var SCAN_DIRS: number;
export var SCAN_HIDDEN: number;
export var LOG_RAW: number;
export var LOG_DEBUG: number;
export var LOG_INFO: number;
export var LOG_WARNING: number;
export var LOG_ERROR: number;
export var LOG_NONE: number;
//----------------------------------------------------
// MODULE: Container
//----------------------------------------------------
export class RefCounted {
// Construct. Allocate the reference count structure and set an initial self weak reference.
constructor();
// Increment reference count. Can also be called outside of a SharedPtr for traditional reference counting.
addRef(): void;
// Decrement reference count and delete self if no more references. Can also be called outside of a SharedPtr for traditional reference counting.
releaseRef(): void;
// Return reference count.
refs(): number;
// Return weak reference count.
weakRefs(): number;
isObject(): boolean;
}
//----------------------------------------------------
// MODULE: Math
//----------------------------------------------------
export class BoundingBox {
}
export class Color {
}
export class Quaternion {
}
export class Rect {
}
export class IntRect {
}
export class Vector2 {
}
export class IntVector2 {
}
export class Vector3 {
}
export class Vector4 {
}
//----------------------------------------------------
// MODULE: Core
//----------------------------------------------------
export class Context extends RefCounted {
eventSender: AObject;
editorContext: boolean;
// Construct.
constructor();
// Register a subsystem.
registerSubsystem(subsystem: AObject): void;
// Remove a subsystem.
removeSubsystem(objectType: string): void;
// Copy base class attributes to derived class.
copyBaseAttributes(baseType: string, derivedType: string): void;
// Return subsystem by type.
getSubsystem(type: string): AObject;
// Return active event sender. Null outside event handling.
getEventSender(): AObject;
// Return object type name from hash, or empty if unknown.
getTypeName(objectType: string): string;
// Get whether an Editor Context
getEditorContext(): boolean;
// Get whether an Editor Context
setEditorContext(editor: boolean): void;
}
export class AObject extends RefCounted {
type: string;
baseType: string;
typeName: string;
context: Context;
eventSender: AObject;
category: string;
typeNameStatic: string;
// Construct.
constructor();
// Return type hash.
getType(): string;
// Return base class type hash.
getBaseType(): string;
// Return type name.
getTypeName(): string;
// Unsubscribe from a specific sender's events.
unsubscribeFromEvents(sender: AObject): void;
// Unsubscribe from all events.
unsubscribeFromAllEvents(): void;
// Return execution context.
getContext(): Context;
// Return subsystem by type.
getSubsystem(type: string): AObject;
// Return active event sender. Null outside event handling.
getEventSender(): AObject;
// Return whether has subscribed to any event.
hasEventHandlers(): boolean;
// Return object category. Categories are (optionally) registered along with the object factory. Return an empty string if the object category is not registered.
getCategory(): string;
isObject(): boolean;
getTypeNameStatic(): string;
sendEvent(eventType:string, data?:Object);
subscribeToEvent(eventType:string, callback:(data:any)=>void);
subscribeToEvent(sender:AObject, eventType:string, callback:(data:any)=>void);
}
//----------------------------------------------------
// MODULE: Scene
//----------------------------------------------------
export class Animatable extends Serializable {
animationEnabled: boolean;
objectAnimation: ObjectAnimation;
// Construct.
constructor();
// Set animation enabled.
setAnimationEnabled(enable: boolean): void;
// Set object animation.
setObjectAnimation(objectAnimation: ObjectAnimation): void;
// Set attribute animation.
setAttributeAnimation(name: string, attributeAnimation: ValueAnimation, wrapMode?: WrapMode, speed?: number): void;
// Set attribute animation wrap mode.
setAttributeAnimationWrapMode(name: string, wrapMode: WrapMode): void;
// Set attribute animation speed.
setAttributeAnimationSpeed(name: string, speed: number): void;
// Return animation enabled.
getAnimationEnabled(): boolean;
// Return object animation.
getObjectAnimation(): ObjectAnimation;
// Return attribute animation.
getAttributeAnimation(name: string): ValueAnimation;
// Return attribute animation wrap mode.
getAttributeAnimationWrapMode(name: string): WrapMode;
// Return attribute animation speed.
getAttributeAnimationSpeed(name: string): number;
}
export class Component extends Animatable {
enabled: boolean;
id: number;
node: Node;
scene: Scene;
// Construct.
constructor();
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Mark for attribute check on the next network update.
markNetworkUpdate(): void;
// Visualize the component as debug geometry.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Set enabled/disabled state.
setEnabled(enable: boolean): void;
// Remove from the scene node. If no other shared pointer references exist, causes immediate deletion.
remove(): void;
// Return ID.
getID(): number;
// Return scene node.
getNode(): Node;
// Return the scene the node belongs to.
getScene(): Scene;
// Return whether is enabled.
isEnabled(): boolean;
// Return whether is effectively enabled (node is also enabled.)
isEnabledEffective(): boolean;
// Return component in the same scene node by type. If there are several, returns the first.
getComponent(type: string): Component;
// Prepare network update by comparing attributes and marking replication states dirty as necessary.
prepareNetworkUpdate(): void;
}
export class Node extends Animatable {
name: string;
position: Vector3;
position2D: Vector2;
rotation: Quaternion;
rotation2D: number;
direction: Vector3;
scale: Vector3;
scale2D: Vector2;
worldPosition: Vector3;
worldRotation: Quaternion;
worldRotation2D: number;
worldDirection: Vector3;
enabled: boolean;
deepEnabled: boolean;
enabledRecursive: boolean;
parent: Node;
id: number;
nameHash: string;
scene: Scene;
up: Vector3;
right: Vector3;
worldPosition2D: Vector2;
worldUp: Vector3;
worldRight: Vector3;
worldScale: Vector3;
worldScale2D: Vector2;
numComponents: number;
numNetworkComponents: number;
netPositionAttr: Vector3;
numPersistentChildren: number;
numPersistentComponents: number;
positionSilent: Vector3;
rotationSilent: Quaternion;
scaleSilent: Vector3;
// Construct.
constructor();
// Apply attribute changes that can not be applied immediately recursively to child nodes and components.
applyAttributes(): void;
// Return whether should save default-valued attributes into XML. Always save node transforms for readability, even if identity.
saveDefaultAttributes(): boolean;
// Mark for attribute check on the next network update.
markNetworkUpdate(): void;
// Set name of the scene node. Names are not required to be unique.
setName(name: string): void;
// Set position in parent space. If the scene node is on the root level (is child of the scene itself), this is same as world space.
setPosition(position: Vector3): void;
// Set position in parent space (for Atomic2D).
setPosition2D(position: Vector2): void;
// Set rotation in parent space.
setRotation(rotation: Quaternion): void;
// Set rotation in parent space (for Atomic2D).
setRotation2D(rotation: number): void;
// Set forward direction in parent space. Positive Z axis equals identity rotation.
setDirection(direction: Vector3): void;
// Set scale in parent space.
setScale(scale: Vector3): void;
// Set scale in parent space (for Atomic2D).
setScale2D(scale: Vector2): void;
// Set position in world space.
setWorldPosition(position: Vector3): void;
// Set rotation in world space.
setWorldRotation(rotation: Quaternion): void;
// Set rotation in world space (for Atomic2D).
setWorldRotation2D(rotation: number): void;
// Set forward direction in world space.
setWorldDirection(direction: Vector3): void;
// Move the scene node in the chosen transform space.
translate(delta: Vector3, space?: TransformSpace): void;
// Move the scene node in the chosen transform space (for Atomic2D).
translate2D(delta: Vector2, space?: TransformSpace): void;
// Rotate the scene node in the chosen transform space.
rotate(delta: Quaternion, space?: TransformSpace): void;
// Rotate the scene node in the chosen transform space (for Atomic2D).
rotate2D(delta: number, space?: TransformSpace): void;
// Rotate around a point in the chosen transform space.
rotateAround(point: Vector3, delta: Quaternion, space?: TransformSpace): void;
// Rotate around a point in the chosen transform space (for Atomic2D).
rotateAround2D(point: Vector2, delta: number, space?: TransformSpace): void;
// Rotate around the X axis.
pitch(angle: number, space?: TransformSpace): void;
// Rotate around the Y axis.
yaw(angle: number, space?: TransformSpace): void;
// Rotate around the Z axis.
roll(angle: number, space?: TransformSpace): void;
// Look at a target position in the chosen transform space. Note that the up vector is always specified in world space. Return true if successful, or false if resulted in an illegal rotation, in which case the current rotation remains.
lookAt(target: Vector3, up?: Vector3, space?: TransformSpace): boolean;
// Set enabled/disabled state without recursion. Components in a disabled node become effectively disabled regardless of their own enable/disable state.
setEnabled(enable: boolean): void;
// Set enabled state on self and child nodes. Nodes' own enabled state is remembered (IsEnabledSelf) and can be restored.
setDeepEnabled(enable: boolean): void;
// Reset enabled state to the node's remembered state prior to calling SetDeepEnabled.
resetDeepEnabled(): void;
// Set enabled state on self and child nodes. Unlike SetDeepEnabled this does not remember the nodes' own enabled state, but overwrites it.
setEnabledRecursive(enable: boolean): void;
// Mark node and child nodes to need world transform recalculation. Notify listener components.
markDirty(): void;
// Create a child scene node (with specified ID if provided).
createChild(name?: string, mode?: CreateMode, id?: number): Node;
// Add a child scene node at a specific index. If index is not explicitly specified or is greater than current children size, append the new child at the end.
addChild(node: Node, index?: number): void;
// Remove a child scene node.
removeChild(node: Node): void;
// Remove all child scene nodes.
removeAllChildren(): void;
// Remove child scene nodes that match criteria.
removeChildren(removeReplicated: boolean, removeLocal: boolean, recursive: boolean): void;
// Create a component to this node (with specified ID if provided).
createComponent(type: string, mode?: CreateMode, id?: number): Component;
// Create a component to this node if it does not exist already.
getOrCreateComponent(type: string, mode?: CreateMode, id?: number): Component;
// Remove all components from this node.
removeAllComponents(): void;
// Remove components that match criteria.
removeComponents(removeReplicated: boolean, removeLocal: boolean): void;
// Clone scene node, components and child nodes. Return the clone.
clone(mode?: CreateMode): Node;
// Remove from the parent node. If no other shared pointer references exist, causes immediate deletion.
remove(): void;
// Set parent scene node. Retains the world transform.
setParent(parent: Node): void;
// Add listener component that is notified of node being dirtied. Can either be in the same node or another.
addListener(component: Component): void;
// Remove listener component.
removeListener(component: Component): void;
// Return ID.
getID(): number;
// Return name.
getName(): string;
// Return name hash.
getNameHash(): string;
// Return parent scene node.
getParent(): Node;
// Return scene.
getScene(): Scene;
// Return whether is enabled. Disables nodes effectively disable all their components.
isEnabled(): boolean;
// Returns the node's last own enabled state. May be different than the value returned by IsEnabled when SetDeepEnabled has been used.
isEnabledSelf(): boolean;
// Return position in parent space.
getPosition(): Vector3;
// Return position in parent space (for Atomic2D).
getPosition2D(): Vector2;
// Return rotation in parent space.
getRotation(): Quaternion;
// Return rotation in parent space (for Atomic2D).
getRotation2D(): number;
// Return forward direction in parent space. Positive Z axis equals identity rotation.
getDirection(): Vector3;
// Return up direction in parent space. Positive Y axis equals identity rotation.
getUp(): Vector3;
// Return right direction in parent space. Positive X axis equals identity rotation.
getRight(): Vector3;
// Return scale in parent space.
getScale(): Vector3;
// Return scale in parent space (for Atomic2D).
getScale2D(): Vector2;
// Return position in world space.
getWorldPosition(): Vector3;
// Return position in world space (for Atomic2D).
getWorldPosition2D(): Vector2;
// Return rotation in world space.
getWorldRotation(): Quaternion;
// Return rotation in world space (for Atomic2D).
getWorldRotation2D(): number;
// Return direction in world space.
getWorldDirection(): Vector3;
// Return node's up vector in world space.
getWorldUp(): Vector3;
// Return node's right vector in world space.
getWorldRight(): Vector3;
// Return scale in world space.
getWorldScale(): Vector3;
// Return scale in world space (for Atomic2D).
getWorldScale2D(): Vector2;
// Convert a local space position or rotation to world space (for Atomic2D).
localToWorld2D(vector: Vector2): Vector2;
// Convert a world space position or rotation to local space (for Atomic2D).
worldToLocal2D(vector: Vector2): Vector2;
// Return whether transform has changed and world transform needs recalculation.
isDirty(): boolean;
// Return number of child scene nodes.
getNumChildren(recursive?: boolean): number;
// Return child scene node by name.
getChild(name: string, recursive?: boolean): Node;
// Return number of components.
getNumComponents(): number;
// Return number of non-local components.
getNumNetworkComponents(): number;
// Return component by type. If there are several, returns the first.
getComponent(type: string): Component;
// Return whether has a specific component.
hasComponent(type: string): boolean;
// Set ID. Called by Scene.
setID(id: number): void;
// Set scene. Called by Scene.
setScene(scene: Scene): void;
// Reset scene, ID and owner. Called by Scene.
resetScene(): void;
// Set network position attribute.
setNetPositionAttr(value: Vector3): void;
// Return network position attribute.
getNetPositionAttr(): Vector3;
// Prepare network update by comparing attributes and marking replication states dirty as necessary.
prepareNetworkUpdate(): void;
// Mark node dirty in scene replication states.
markReplicationDirty(): void;
// Add a pre-created component.
addComponent(component: Component, id: number, mode: CreateMode): void;
// Calculate number of non-temporary child nodes.
getNumPersistentChildren(): number;
// Calculate number of non-temporary components.
getNumPersistentComponents(): number;
// Set position in parent space silently without marking the node & child nodes dirty. Used by animation code.
setPositionSilent(position: Vector3): void;
// Set position in parent space silently without marking the node & child nodes dirty. Used by animation code.
setRotationSilent(rotation: Quaternion): void;
// Set scale in parent space silently without marking the node & child nodes dirty. Used by animation code.
setScaleSilent(scale: Vector3): void;
// Set local transform silently without marking the node & child nodes dirty. Used by animation code.
setTransformSilent(position: Vector3, rotation: Quaternion, scale: Vector3): void;
saveXML(file:File):boolean;
loadXML(file:File):boolean;
getChildrenWithName(name:string, recursive?:boolean):Node[];
getChildrenWithComponent(componentType:string, recursive?:boolean):Node[];
getComponents(componentType?:string, recursive?:boolean):Component[];
getChildAtIndex(index:number):Node;
createJSComponent(name:string, args?:{});
getJSComponent(name:string):JSComponent;
createChildPrefab(childName:string, prefabPath:string):Node;
loadPrefab(prefabPath:string):boolean;
}
export class ObjectAnimation extends Resource {
// Construct.
constructor();
// Add attribute animation, attribute name can in following format: "attribute" or "#0/#1/attribute" or ""#0/#1/@component#1/attribute.
addAttributeAnimation(name: string, attributeAnimation: ValueAnimation, wrapMode?: WrapMode, speed?: number): void;
// Return attribute animation by name.
getAttributeAnimation(name: string): ValueAnimation;
// Return attribute animation wrap mode by name.
getAttributeAnimationWrapMode(name: string): WrapMode;
// Return attribute animation speed by name.
getAttributeAnimationSpeed(name: string): number;
// Return attribute animation info by name.
getAttributeAnimationInfo(name: string): ValueAnimationInfo;
}
export class PrefabComponent extends Component {
prefabGUID: string;
// Construct.
constructor();
setPrefabGUID(guid: string): void;
getPrefabGUID(): string;
savePrefab(): boolean;
undoPrefab(): void;
breakPrefab(): void;
}
export class Scene extends Node {
updateEnabled: boolean;
timeScale: number;
elapsedTime: number;
smoothingConstant: number;
snapThreshold: number;
asyncLoadingMs: number;
asyncProgress: number;
asyncLoadMode: LoadMode;
fileName: string;
checksum: number;
varNamesAttr: string;
// Construct.
constructor();
// Load from a binary file asynchronously. Return true if started successfully. The LOAD_RESOURCES_ONLY mode can also be used to preload resources from object prefab files.
loadAsync(file: File, mode?: LoadMode): boolean;
// Load from an XML file asynchronously. Return true if started successfully. The LOAD_RESOURCES_ONLY mode can also be used to preload resources from object prefab files.
loadAsyncXML(file: File, mode?: LoadMode): boolean;
// Stop asynchronous loading.
stopAsyncLoading(): void;
// Clear scene completely of either replicated, local or all nodes and components.
clear(clearReplicated?: boolean, clearLocal?: boolean): void;
// Enable or disable scene update.
setUpdateEnabled(enable: boolean): void;
// Set update time scale. 1.0 = real time (default.)
setTimeScale(scale: number): void;
// Set elapsed time in seconds. This can be used to prevent inaccuracy in the timer if the scene runs for a long time.
setElapsedTime(time: number): void;
// Set network client motion smoothing constant.
setSmoothingConstant(constant: number): void;
// Set network client motion smoothing snap threshold.
setSnapThreshold(threshold: number): void;
// Set maximum milliseconds per frame to spend on async scene loading.
setAsyncLoadingMs(ms: number): void;
// Clear required package files.
clearRequiredPackageFiles(): void;
// Register a node user variable hash reverse mapping (for editing.)
registerVar(name: string): void;
// Unregister a node user variable hash reverse mapping.
unregisterVar(name: string): void;
// Clear all registered node user variable hash reverse mappings.
unregisterAllVars(): void;
// Return node from the whole scene by ID, or null if not found.
getNode(id: number): Node;
// Return whether updates are enabled.
isUpdateEnabled(): boolean;
// Return whether an asynchronous loading operation is in progress.
isAsyncLoading(): boolean;
// Return asynchronous loading progress between 0.0 and 1.0, or 1.0 if not in progress.
getAsyncProgress(): number;
// Return the load mode of the current asynchronous loading operation.
getAsyncLoadMode(): LoadMode;
// Return source file name.
getFileName(): string;
// Return source file checksum.
getChecksum(): number;
// Return update time scale.
getTimeScale(): number;
// Return elapsed time in seconds.
getElapsedTime(): number;
// Return motion smoothing constant.
getSmoothingConstant(): number;
// Return motion smoothing snap threshold.
getSnapThreshold(): number;
// Return maximum milliseconds per frame to spend on async loading.
getAsyncLoadingMs(): number;
// Return a node user variable name, or empty if not registered.
getVarName(hash: string): string;
// Update scene. Called by HandleUpdate.
update(timeStep: number): void;
// Begin a threaded update. During threaded update components can choose to delay dirty processing.
beginThreadedUpdate(): void;
// End a threaded update. Notify components that marked themselves for delayed dirty processing.
endThreadedUpdate(): void;
// Add a component to the delayed dirty notify queue. Is thread-safe.
delayedMarkedDirty(component: Component): void;
// Return threaded update flag.
isThreadedUpdate(): boolean;
// Get free node ID, either non-local or local.
getFreeNodeID(mode: CreateMode): number;
// Get free component ID, either non-local or local.
getFreeComponentID(mode: CreateMode): number;
// Node added. Assign scene pointer and add to ID map.
nodeAdded(node: Node): void;
// Node removed. Remove from ID map.
nodeRemoved(node: Node): void;
// Component added. Add to ID map.
componentAdded(component: Component): void;
// Component removed. Remove from ID map.
componentRemoved(component: Component): void;
// Set node user variable reverse mappings.
setVarNamesAttr(value: string): void;
// Return node user variable reverse mappings.
getVarNamesAttr(): string;
// Prepare network update by comparing attributes and marking replication states dirty as necessary.
prepareNetworkUpdate(): void;
getMainCamera():Camera;
}
export class Serializable extends AObject {
temporary: boolean;
numAttributes: number;
numNetworkAttributes: number;
// Construct.
constructor();
// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
applyAttributes(): void;
// Return whether should save default-valued attributes into XML. Default false.
saveDefaultAttributes(): boolean;
// Mark for attribute check on the next network update.
markNetworkUpdate(): void;
// Reset all editable attributes to their default values.
resetToDefault(): void;
// Remove instance's default values if they are set previously.
removeInstanceDefault(): void;
// Set temporary flag. Temporary objects will not be saved.
setTemporary(enable: boolean): void;
// Enable interception of an attribute from network updates. Intercepted attributes are sent as events instead of applying directly. This can be used to implement client side prediction.
setInterceptNetworkUpdate(attributeName: string, enable: boolean): void;
// Allocate network attribute state.
allocateNetworkState(): void;
// Return number of attributes.
getNumAttributes(): number;
// Return number of network replication attributes.
getNumNetworkAttributes(): number;
// Return whether is temporary.
isTemporary(): boolean;
// Return whether an attribute's network updates are being intercepted.
getInterceptNetworkUpdate(attributeName: string): boolean;
getAttributes():AttributeInfo[];
getAttribute(name:string):any;
setAttribute(name:string, value:any):void;
}
export class SmoothedTransform extends Component {
targetPosition: Vector3;
targetRotation: Quaternion;
targetWorldPosition: Vector3;
targetWorldRotation: Quaternion;
// Construct.
constructor();
// Update smoothing.
update(constant: number, squaredSnapThreshold: number): void;
// Set target position in parent space.
setTargetPosition(position: Vector3): void;
// Set target rotation in parent space.
setTargetRotation(rotation: Quaternion): void;
// Set target position in world space.
setTargetWorldPosition(position: Vector3): void;
// Set target rotation in world space.
setTargetWorldRotation(rotation: Quaternion): void;
// Return target position in parent space.
getTargetPosition(): Vector3;
// Return target rotation in parent space.
getTargetRotation(): Quaternion;
// Return target position in world space.
getTargetWorldPosition(): Vector3;
// Return target rotation in world space.
getTargetWorldRotation(): Quaternion;
// Return whether smoothing is in progress.
isInProgress(): boolean;
}
export class SplinePath extends Component {
interpolationMode: InterpolationMode;
speed: number;
position: Vector3;
controlledNode: Node;
controlledIdAttr: number;
// Construct an Empty SplinePath.
constructor();
// Apply Attributes to the SplinePath.
applyAttributes(): void;
// Draw the Debug Geometry.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Add a Node to the SplinePath as a Control Point.
addControlPoint(point: Node, index?: number): void;
// Remove a Node Control Point from the SplinePath.
removeControlPoint(point: Node): void;
// Clear the Control Points from the SplinePath.
clearControlPoints(): void;
// Set the Interpolation Mode.
setInterpolationMode(interpolationMode: InterpolationMode): void;
// Set the movement Speed.
setSpeed(speed: number): void;
// Set the controlled Node's position on the SplinePath.
setPosition(factor: number): void;
// Set the Node to be moved along the SplinePath.
setControlledNode(controlled: Node): void;
// Get the Interpolation Mode.
getInterpolationMode(): InterpolationMode;
// Get the movement Speed.
getSpeed(): number;
// Get the parent Node's last position on the spline.
getPosition(): Vector3;
// Get the controlled Node.
getControlledNode(): Node;
// Get a point on the SplinePath from 0.f to 1.f where 0 is the start and 1 is the end.
getPoint(factor: number): Vector3;
// Move the controlled Node to the next position along the SplinePath based off the Speed value.
move(timeStep: number): void;
// Reset movement along the path.
reset(): void;
// Returns whether the movement along the SplinePath is complete.
isFinished(): boolean;
// Set Controlled Node ID attribute.
setControlledIdAttr(value: number): void;
// Get Controlled Node ID attribute.
getControlledIdAttr(): number;
}
export class ValueAnimation extends Resource {
interpolationMethod: InterpMethod;
splineTension: number;
valueType: VariantType;
beginTime: number;
endTime: number;
// Construct.
constructor();
// Set interpolation method.
setInterpolationMethod(method: InterpMethod): void;
// Set spline tension, should be between 0.0f and 1.0f, but this is not a must.
setSplineTension(tension: number): void;
// Set value type.
setValueType(valueType: VariantType): void;
// Return animation is valid.
isValid(): boolean;
// Return interpolation method.
getInterpolationMethod(): InterpMethod;
// Return spline tension.
getSplineTension(): number;
// Return value type.
getValueType(): VariantType;
// Return begin time.
getBeginTime(): number;
// Return end time.
getEndTime(): number;
// Has event frames.
hasEventFrames(): boolean;
}
export class ValueAnimationInfo extends RefCounted {
wrapMode: WrapMode;
speed: number;
target: AObject;
animation: ValueAnimation;
// Construct without target object.
constructor(animation: ValueAnimation, wrapMode: WrapMode, speed: number);
// Update. Return true when the animation is finished. No-op when the target object is not defined.
update(timeStep: number): boolean;
// Set wrap mode.
setWrapMode(wrapMode: WrapMode): void;
// Set speed.
setSpeed(speed: number): void;
// Return target object.
getTarget(): AObject;
// Return animation.
getAnimation(): ValueAnimation;
// Return wrap mode.
getWrapMode(): WrapMode;
// Return speed.
getSpeed(): number;
}
//----------------------------------------------------
// MODULE: Graphics
//----------------------------------------------------
export class Camera extends Component {
nearClip: number;
farClip: number;
fov: number;
orthoSize: number;
aspectRatio: number;
fillMode: FillMode;
zoom: number;
lodBias: number;
viewMask: number;
viewOverrideFlags: number;
orthographic: boolean;
autoAspectRatio: boolean;
projectionOffset: Vector2;
useReflection: boolean;
useClipping: boolean;
flipVertical: boolean;
halfViewSize: number;
reverseCulling: boolean;
aspectRatioInternal: number;
orthoSizeAttr: number;
reflectionPlaneAttr: Vector4;
clipPlaneAttr: Vector4;
// Construct.
constructor();
// Visualize the component as debug geometry.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Set near clip distance.
setNearClip(nearClip: number): void;
// Set far clip distance.
setFarClip(farClip: number): void;
// Set vertical field of view in degrees.
setFov(fov: number): void;
// Set orthographic mode view uniform size.
setOrthoSize(orthoSize: number): void;
// Set aspect ratio manually. Disables the auto aspect ratio -mode.
setAspectRatio(aspectRatio: number): void;
// Set polygon fill mode to use when rendering a scene.
setFillMode(mode: FillMode): void;
// Set zoom.
setZoom(zoom: number): void;
// Set LOD bias.
setLodBias(bias: number): void;
// Set view mask. Will be and'ed with object's view mask to see if the object should be rendered.
setViewMask(mask: number): void;
// Set view override flags.
setViewOverrideFlags(flags: number): void;
// Set orthographic mode enabled/disabled.
setOrthographic(enable: boolean): void;
// Set automatic aspect ratio based on viewport dimensions. Enabled by default.
setAutoAspectRatio(enable: boolean): void;
// Set projection offset. It needs to be calculated as (offset in pixels) / (viewport dimensions.)
setProjectionOffset(offset: Vector2): void;
// Set reflection mode.
setUseReflection(enable: boolean): void;
// Set whether to use a custom clip plane.
setUseClipping(enable: boolean): void;
// Set vertical flipping mode. Called internally by View to resolve OpenGL / Direct3D9 rendertarget sampling differences.
setFlipVertical(enable: boolean): void;
// Return far clip distance.
getFarClip(): number;
// Return near clip distance.
getNearClip(): number;
// Return vertical field of view in degrees.
getFov(): number;
// Return orthographic mode size.
getOrthoSize(): number;
// Return aspect ratio.
getAspectRatio(): number;
// Return zoom.
getZoom(): number;
// Return LOD bias.
getLodBias(): number;
// Return view mask.
getViewMask(): number;
// Return view override flags.
getViewOverrideFlags(): number;
// Return fill mode.
getFillMode(): FillMode;
// Return orthographic flag.
isOrthographic(): boolean;
// Return auto aspect ratio flag.
getAutoAspectRatio(): boolean;
// Return frustum near and far sizes.
getFrustumSize(near: Vector3, far: Vector3): void;
// Return half view size.
getHalfViewSize(): number;
worldToScreenPoint(worldPos: Vector3): Vector2;
screenToWorldPoint(screenPos: Vector3): Vector3;
// Return projection offset.
getProjectionOffset(): Vector2;
// Return whether is using reflection.
getUseReflection(): boolean;
// Return whether is using a custom clipping plane.
getUseClipping(): boolean;
// Return vertical flipping mode.
getFlipVertical(): boolean;
// Return whether to reverse culling; affected by vertical flipping and reflection.
getReverseCulling(): boolean;
// Return distance to position. In orthographic mode uses only Z coordinate.
getDistance(worldPos: Vector3): number;
// Return squared distance to position. In orthographic mode uses only Z coordinate.
getDistanceSquared(worldPos: Vector3): number;
// Return a scene node's LOD scaled distance.
getLodDistance(distance: number, scale: number, bias: number): number;
// Return a world rotation for facing a camera on certain axes based on the existing world rotation.
getFaceCameraRotation(position: Vector3, rotation: Quaternion, mode: FaceCameraMode): Quaternion;
// Return if projection parameters are valid for rendering and raycasting.
isProjectionValid(): boolean;
// Set aspect ratio without disabling the "auto aspect ratio" mode. Called internally by View.
setAspectRatioInternal(aspectRatio: number): void;
// Set orthographic size attribute without forcing the aspect ratio.
setOrthoSizeAttr(orthoSize: number): void;
// Set reflection plane attribute.
setReflectionPlaneAttr(value: Vector4): void;
// Return reflection plane attribute.
getReflectionPlaneAttr(): Vector4;
// Set clipping plane attribute.
setClipPlaneAttr(value: Vector4): void;
// Return clipping plane attribute.
getClipPlaneAttr(): Vector4;
}
export class DebugRenderer extends Component {
view: Camera;
// Construct.
constructor();
// Set the camera viewpoint. Call before rendering, or before adding geometry if you want to use culling.
setView(camera: Camera): void;
// Add a scene node represented as its coordinate axes.
addNode(node: Node, scale?: number, depthTest?: boolean): void;
// Add a bounding box.
addBoundingBox(box: BoundingBox, color: Color, depthTest?: boolean): void;
// Add a cylinder
addCylinder(position: Vector3, radius: number, height: number, color: Color, depthTest?: boolean): void;
// Update vertex buffer and render all debug lines. The viewport and rendertarget should be set before.
render(): void;
// Check whether a bounding box is inside the view frustum.
isInside(box: BoundingBox): boolean;
// Return whether has something to render.
hasContent(): boolean;
}
export class Drawable extends Component {
updateGeometryType: UpdateGeometryType;
numOccluderTriangles: number;
drawDistance: number;
shadowDistance: number;
lodBias: number;
viewMask: number;
lightMask: number;
shadowMask: number;
zoneMask: number;
maxLights: number;
castShadows: boolean;
occluder: boolean;
occludee: boolean;
boundingBox: BoundingBox;
worldBoundingBox: BoundingBox;
drawableFlags: number;
sortValue: number;
basePass: number;
zone: Zone;
distance: number;
lodDistance: number;
firstLight: Light;
minZ: number;
maxZ: number;
// Construct.
constructor(drawableFlags: number);
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Return whether a geometry update is necessary, and if it can happen in a worker thread.
getUpdateGeometryType(): UpdateGeometryType;
// Return number of occlusion geometry triangles.
getNumOccluderTriangles(): number;
// Visualize the component as debug geometry.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Set draw distance.
setDrawDistance(distance: number): void;
// Set shadow draw distance.
setShadowDistance(distance: number): void;
// Set LOD bias.
setLodBias(bias: number): void;
// Set view mask. Is and'ed with camera's view mask to see if the object should be rendered.
setViewMask(mask: number): void;
// Set light mask. Is and'ed with light's and zone's light mask to see if the object should be lit.
setLightMask(mask: number): void;
// Set shadow mask. Is and'ed with light's light mask and zone's shadow mask to see if the object should be rendered to a shadow map.
setShadowMask(mask: number): void;
// Set zone mask. Is and'ed with zone's zone mask to see if the object should belong to the zone.
setZoneMask(mask: number): void;
// Set maximum number of per-pixel lights. Default 0 is unlimited.
setMaxLights(num: number): void;
// Set shadowcaster flag.
setCastShadows(enable: boolean): void;
// Set occlusion flag.
setOccluder(enable: boolean): void;
// Set occludee flag.
setOccludee(enable: boolean): void;
// Mark for update and octree reinsertion. Update is automatically queued when the drawable's scene node moves or changes scale.
markForUpdate(): void;
// Return local space bounding box. May not be applicable or properly updated on all drawables.
getBoundingBox(): BoundingBox;
// Return world-space bounding box.
getWorldBoundingBox(): BoundingBox;
// Return drawable flags.
getDrawableFlags(): number;
// Return draw distance.
getDrawDistance(): number;
// Return shadow draw distance.
getShadowDistance(): number;
// Return LOD bias.
getLodBias(): number;
// Return view mask.
getViewMask(): number;
// Return light mask.
getLightMask(): number;
// Return shadow mask.
getShadowMask(): number;
// Return zone mask.
getZoneMask(): number;
// Return maximum number of per-pixel lights.
getMaxLights(): number;
// Return shadowcaster flag.
getCastShadows(): boolean;
// Return occluder flag.
isOccluder(): boolean;
// Return occludee flag.
isOccludee(): boolean;
// Set new zone. Zone assignment may optionally be temporary, meaning it needs to be re-evaluated on the next frame.
setZone(zone: Zone, temporary?: boolean): void;
// Set sorting value.
setSortValue(value: number): void;
// Set view-space depth bounds.
setMinMaxZ(minZ: number, maxZ: number): void;
// Mark in view without specifying a camera. Used for shadow casters.
markInView(frameNumber: number): void;
// Sort and limit per-pixel lights to maximum allowed. Convert extra lights into vertex lights.
limitLights(): void;
// Sort and limit per-vertex lights to maximum allowed.
limitVertexLights(removeConvertedLights: boolean): void;
// Set base pass flag for a batch.
setBasePass(batchIndex: number): void;
// Return current zone.
getZone(): Zone;
// Return whether current zone is inconclusive or dirty due to the drawable moving.
isZoneDirty(): boolean;
// Return distance from camera.
getDistance(): number;
// Return LOD scaled distance from camera.
getLodDistance(): number;
// Return sorting value.
getSortValue(): number;
// Return whether has a base pass.
hasBasePass(batchIndex: number): boolean;
// Return the first added per-pixel light.
getFirstLight(): Light;
// Return the minimum view-space depth.
getMinZ(): number;
// Return the maximum view-space depth.
getMaxZ(): number;
addLight(light: Light): void;
addVertexLight(light: Light): void;
}
export class Light extends Drawable {
lightType: LightType;
perVertex: boolean;
color: Color;
specularIntensity: number;
brightness: number;
range: number;
fov: number;
aspectRatio: number;
fadeDistance: number;
shadowFadeDistance: number;
shadowIntensity: number;
shadowResolution: number;
shadowNearFarRatio: number;
rampTexture: Texture;
shapeTexture: Texture;
effectiveColor: Color;
effectiveSpecularIntensity: number;
numShadowSplits: number;
// Construct.
constructor();
// Visualize the component as debug geometry.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Set light type.
setLightType(type: LightType): void;
// Set vertex lighting mode.
setPerVertex(enable: boolean): void;
// Set color.
setColor(color: Color): void;
// Set specular intensity. Zero disables specular calculations.
setSpecularIntensity(intensity: number): void;
// Set light brightness multiplier. Both the color and specular intensity are multiplied with this to get final values for rendering.
setBrightness(brightness: number): void;
// Set range.
setRange(range: number): void;
// Set spotlight field of view.
setFov(fov: number): void;
// Set spotlight aspect ratio.
setAspectRatio(aspectRatio: number): void;
// Set fade out start distance.
setFadeDistance(distance: number): void;
// Set shadow fade out start distance. Only has effect if shadow distance is also non-zero.
setShadowFadeDistance(distance: number): void;
// Set shadow intensity between 0.0 - 1.0. 0.0 (the default) gives fully dark shadows.
setShadowIntensity(intensity: number): void;
// Set shadow resolution between 0.25 - 1.0. Determines the shadow map to use.
setShadowResolution(resolution: number): void;
// Set shadow camera near/far clip distance ratio.
setShadowNearFarRatio(nearFarRatio: number): void;
// Set range attenuation texture.
setRampTexture(texture: Texture): void;
// Set spotlight attenuation texture.
setShapeTexture(texture: Texture): void;
// Return light type.
getLightType(): LightType;
// Return vertex lighting mode.
getPerVertex(): boolean;
// Return color.
getColor(): Color;
// Return specular intensity.
getSpecularIntensity(): number;
// Return brightness multiplier.
getBrightness(): number;
// Return effective color, multiplied by brightness. Do not multiply the alpha so that can compare against the default black color to detect a light with no effect.
getEffectiveColor(): Color;
// Return effective specular intensity, multiplied by absolute value of brightness.
getEffectiveSpecularIntensity(): number;
// Return range.
getRange(): number;
// Return spotlight field of view.
getFov(): number;
// Return spotlight aspect ratio.
getAspectRatio(): number;
// Return fade start distance.
getFadeDistance(): number;
// Return shadow fade start distance.
getShadowFadeDistance(): number;
// Return shadow intensity.
getShadowIntensity(): number;
// Return shadow resolution.
getShadowResolution(): number;
// Return shadow camera near/far clip distance ratio.
getShadowNearFarRatio(): number;
// Return range attenuation texture.
getRampTexture(): Texture;
// Return spotlight attenuation texture.
getShapeTexture(): Texture;
// Return number of shadow map cascade splits for a directional light, considering also graphics API limitations.
getNumShadowSplits(): number;
// Return whether light has negative (darkening) color.
isNegative(): boolean;
// Return a divisor value based on intensity for calculating the sort value.
getIntensityDivisor(attenuation?: number): number;
getShadowCascade():Number[];
setShadowCascade(args:Number[]);
setShadowCascadeParameter(index:number, value:number);
}
export class Material extends Resource {
numTechniques: number;
cullMode: CullMode;
shadowCullMode: CullMode;
fillMode: FillMode;
scene: Scene;
auxViewFrameNumber: number;
occlusion: boolean;
specular: boolean;
shaderParameterHash: number;
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Set number of techniques.
setNumTechniques(num: number): void;
// Set technique.
setTechnique(index: number, tech: Technique, qualityLevel?: number, lodDistance?: number): void;
setShaderParameterAnimation(name: string, animation: ValueAnimation, wrapMode?: WrapMode, speed?: number): void;
// Set shader parameter animation wrap mode.
setShaderParameterAnimationWrapMode(name: string, wrapMode: WrapMode): void;
// Set shader parameter animation speed.
setShaderParameterAnimationSpeed(name: string, speed: number): void;
// Set texture.
setTexture(unit: TextureUnit, texture: Texture): void;
// Set culling mode.
setCullMode(mode: CullMode): void;
// Set culling mode for shadows.
setShadowCullMode(mode: CullMode): void;
// Set polygon fill mode. Interacts with the camera's fill mode setting so that the "least filled" mode will be used.
setFillMode(mode: FillMode): void;
// Associate the material with a scene to ensure that shader parameter animation happens in sync with scene update, respecting the scene time scale. If no scene is set, the global update events will be used.
setScene(scene: Scene): void;
// Remove shader parameter.
removeShaderParameter(name: string): void;
// Reset all shader pointers.
releaseShaders(): void;
// Clone the material.
clone(cloneName?: string): Material;
// Ensure that material techniques are listed in correct order.
sortTechniques(): void;
// Mark material for auxiliary view rendering.
markForAuxView(frameNumber: number): void;
// Return number of techniques.
getNumTechniques(): number;
// Return technique by index.
getTechnique(index: number): Technique;
// Return pass by technique index and pass name.
getPass(index: number, passName: string): Pass;
// Return texture by unit.
getTexture(unit: TextureUnit): Texture;
// Return shader parameter animation.
getShaderParameterAnimation(name: string): ValueAnimation;
// Return shader parameter animation wrap mode.
getShaderParameterAnimationWrapMode(name: string): WrapMode;
// Return shader parameter animation speed.
getShaderParameterAnimationSpeed(name: string): number;
// Return normal culling mode.
getCullMode(): CullMode;
// Return culling mode for shadows.
getShadowCullMode(): CullMode;
// Return polygon fill mode.
getFillMode(): FillMode;
// Return last auxiliary view rendered frame number.
getAuxViewFrameNumber(): number;
// Return whether should render occlusion.
getOcclusion(): boolean;
// Return whether should render specular.
getSpecular(): boolean;
// Return the scene associated with the material for shader parameter animation updates.
getScene(): Scene;
// Return shader parameter hash value. Used as an optimization to avoid setting shader parameters unnecessarily.
getShaderParameterHash(): number;
// Return name for texture unit.
getTextureUnitName(unit: TextureUnit): string;
static getTextureUnitName(unit:TextureUnit):string;
getShaderParameters():ShaderParameter[];
}
export class Octree extends Component {
numLevels: number;
// Construct.
constructor();
// Set size and maximum subdivision levels. If octree is not empty, drawable objects will be temporarily moved to the root.
setSize(box: BoundingBox, numLevels: number): void;
// Add a drawable manually.
addManualDrawable(drawable: Drawable): void;
// Remove a manually added drawable.
removeManualDrawable(drawable: Drawable): void;
// Return subdivision levels.
getNumLevels(): number;
// Mark drawable object as requiring an update and a reinsertion.
queueUpdate(drawable: Drawable): void;
// Cancel drawable object's update.
cancelUpdate(drawable: Drawable): void;
}
export class Renderer extends AObject {
numViewports: number;
hDRRendering: boolean;
specularLighting: boolean;
textureAnisotropy: number;
textureFilterMode: TextureFilterMode;
textureQuality: number;
materialQuality: number;
drawShadows: boolean;
shadowMapSize: number;
shadowQuality: number;
reuseShadowMaps: boolean;
maxShadowMaps: number;
dynamicInstancing: boolean;
minInstances: number;
maxSortedInstances: number;
maxOccluderTriangles: number;
occlusionBufferSize: number;
occluderSizeThreshold: number;
mobileShadowBiasMul: number;
mobileShadowBiasAdd: number;
defaultRenderPath: RenderPath;
numViews: number;
numPrimitives: number;
numBatches: number;
defaultZone: Zone;
defaultMaterial: Material;
defaultLightRamp: Texture2D;
defaultLightSpot: Texture2D;
faceSelectCubeMap: TextureCube;
indirectionCubeMap: TextureCube;
shadowCamera: Camera;
// Construct.
constructor();
// Set number of backbuffer viewports to render.
setNumViewports(num: number): void;
// Set a backbuffer viewport.
setViewport(index: number, viewport: Viewport): void;
// Set HDR rendering on/off.
setHDRRendering(enable: boolean): void;
// Set specular lighting on/off.
setSpecularLighting(enable: boolean): void;
// Set texture anisotropy.
setTextureAnisotropy(level: number): void;
// Set texture filtering.
setTextureFilterMode(mode: TextureFilterMode): void;
// Set texture quality level. See the QUALITY constants in GraphicsDefs.h.
setTextureQuality(quality: number): void;
// Set material quality level. See the QUALITY constants in GraphicsDefs.h.
setMaterialQuality(quality: number): void;
// Set shadows on/off.
setDrawShadows(enable: boolean): void;
// Set shadow map resolution.
setShadowMapSize(size: number): void;
// Set shadow quality mode. See the SHADOWQUALITY constants in GraphicsDefs.h.
setShadowQuality(quality: number): void;
// Set reuse of shadow maps. Default is true. If disabled, also transparent geometry can be shadowed.
setReuseShadowMaps(enable: boolean): void;
// Set maximum number of shadow maps created for one resolution. Only has effect if reuse of shadow maps is disabled.
setMaxShadowMaps(shadowMaps: number): void;
// Set dynamic instancing on/off.
setDynamicInstancing(enable: boolean): void;
// Set minimum number of instances required in a batch group to render as instanced.
setMinInstances(instances: number): void;
// Set maximum number of sorted instances per batch group. If exceeded, instances are rendered unsorted.
setMaxSortedInstances(instances: number): void;
// Set maximum number of occluder trianges.
setMaxOccluderTriangles(triangles: number): void;
// Set occluder buffer width.
setOcclusionBufferSize(size: number): void;
// Set required screen size (1.0 = full screen) for occluders.
setOccluderSizeThreshold(screenSize: number): void;
// Set shadow depth bias multiplier for mobile platforms (OpenGL ES.) No effect on desktops. Default 2.
setMobileShadowBiasMul(mul: number): void;
// Set shadow depth bias addition for mobile platforms (OpenGL ES.) No effect on desktops. Default 0.0001.
setMobileShadowBiasAdd(add: number): void;
// Force reload of shaders.
reloadShaders(): void;
// Return number of backbuffer viewports.
getNumViewports(): number;
// Return backbuffer viewport by index.
getViewport(index: number): Viewport;
// Return default renderpath.
getDefaultRenderPath(): RenderPath;
// Return whether HDR rendering is enabled.
getHDRRendering(): boolean;
// Return whether specular lighting is enabled.
getSpecularLighting(): boolean;
// Return whether drawing shadows is enabled.
getDrawShadows(): boolean;
// Return texture anisotropy.
getTextureAnisotropy(): number;
// Return texture filtering.
getTextureFilterMode(): TextureFilterMode;
// Return texture quality level.
getTextureQuality(): number;
// Return material quality level.
getMaterialQuality(): number;
// Return shadow map resolution.
getShadowMapSize(): number;
// Return shadow quality.
getShadowQuality(): number;
// Return whether shadow maps are reused.
getReuseShadowMaps(): boolean;
// Return maximum number of shadow maps per resolution.
getMaxShadowMaps(): number;
// Return whether dynamic instancing is in use.
getDynamicInstancing(): boolean;
// Return minimum number of instances required in a batch group to render as instanced.
getMinInstances(): number;
// Return maximum number of sorted instances per batch group.
getMaxSortedInstances(): number;
// Return maximum number of occluder triangles.
getMaxOccluderTriangles(): number;
// Return occlusion buffer width.
getOcclusionBufferSize(): number;
// Return occluder screen size threshold.
getOccluderSizeThreshold(): number;
// Return shadow depth bias multiplier for mobile platforms.
getMobileShadowBiasMul(): number;
// Return shadow depth bias addition for mobile platforms.
getMobileShadowBiasAdd(): number;
// Return number of views rendered.
getNumViews(): number;
// Return number of primitives rendered.
getNumPrimitives(): number;
// Return number of batches rendered.
getNumBatches(): number;
// Return number of geometries rendered.
getNumGeometries(allViews?: boolean): number;
// Return number of lights rendered.
getNumLights(allViews?: boolean): number;
// Return number of shadow maps rendered.
getNumShadowMaps(allViews?: boolean): number;
// Return number of occluders rendered.
getNumOccluders(allViews?: boolean): number;
// Return the default zone.
getDefaultZone(): Zone;
// Return the default material.
getDefaultMaterial(): Material;
// Return the default range attenuation texture.
getDefaultLightRamp(): Texture2D;
// Return the default spotlight attenuation texture.
getDefaultLightSpot(): Texture2D;
// Return the shadowed pointlight face selection cube map.
getFaceSelectCubeMap(): TextureCube;
// Return the shadowed pointlight indirection cube map.
getIndirectionCubeMap(): TextureCube;
// Update for rendering. Called by HandleRenderUpdate().
update(timeStep: number): void;
// Render. Called by Engine.
render(): void;
// Add debug geometry to the debug renderer.
drawDebugGeometry(depthTest: boolean): void;
// Queue a render surface's viewports for rendering. Called by the surface, or by View.
queueRenderSurface(renderTarget: RenderSurface): void;
// Queue a viewport for rendering. Null surface means backbuffer.
queueViewport(renderTarget: RenderSurface, viewport: Viewport): void;
// Allocate a shadow map. If shadow map reuse is disabled, a different map is returned each time.
getShadowMap(light: Light, camera: Camera, viewWidth: number, viewHeight: number): Texture2D;
// Allocate a rendertarget or depth-stencil texture for deferred rendering or postprocessing. Should only be called during actual rendering, not before.
getScreenBuffer(width: number, height: number, format: number, cubemap: boolean, filtered: boolean, srgb: boolean, persistentKey?: number): Texture;
// Allocate a depth-stencil surface that does not need to be readable. Should only be called during actual rendering, not before.
getDepthStencil(width: number, height: number): RenderSurface;
// Allocate a temporary shadow camera and a scene node for it. Is thread-safe.
getShadowCamera(): Camera;
// Set cull mode while taking possible projection flipping into account.
setCullMode(mode: CullMode, camera: Camera): void;
// Ensure sufficient size of the instancing vertex buffer. Return true if successful.
resizeInstancingBuffer(numInstances: number): boolean;
// Save the screen buffer allocation status. Called by View.
saveScreenBufferAllocations(): void;
// Restore the screen buffer allocation status. Called by View.
restoreScreenBufferAllocations(): void;
// Optimize a light by scissor rectangle.
optimizeLightByScissor(light: Light, camera: Camera): void;
// Optimize a light by marking it to the stencil buffer and setting a stencil test.
optimizeLightByStencil(light: Light, camera: Camera): void;
// Return a scissor rectangle for a light.
getLightScissor(light: Light, camera: Camera): Rect;
}
export class RenderPath extends RefCounted {
numRenderTargets: number;
numCommands: number;
// Construct.
constructor();
// Clone the rendering path.
clone(): RenderPath;
// Clear existing data and load from an XML file. Return true if successful.
load(file: XMLFile): boolean;
// Append data from an XML file. Return true if successful.
append(file: XMLFile): boolean;
// Enable/disable commands and rendertargets by tag.
setEnabled(tag: string, active: boolean): void;
// Toggle enabled state of commands and rendertargets by tag.
toggleEnabled(tag: string): void;
// Remove rendertargets by tag name.
removeRenderTargets(tag: string): void;
// Remove a command by index.
removeCommand(index: number): void;
// Remove commands by tag name.
removeCommands(tag: string): void;
// Return number of rendertargets.
getNumRenderTargets(): number;
// Return number of commands.
getNumCommands(): number;
}
export class Shader extends Resource {
timeStamp: number;
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Return a variation with defines.
getVariation(type: ShaderType, defines: string): ShaderVariation;
// Return either vertex or pixel shader source code.
getSourceCode(type: ShaderType): string;
// Return the latest timestamp of the shader code and its includes.
getTimeStamp(): number;
}
export class ShaderPrecache extends AObject {
// Construct and begin collecting shader combinations. Load existing combinations from XML if the file exists.
constructor(fileName: string);
// Collect a shader combination. Called by Graphics when shaders have been set.
storeShaders(vs: ShaderVariation, ps: ShaderVariation): void;
}
export class Pass extends RefCounted {
blendMode: BlendMode;
depthTestMode: CompareMode;
lightingMode: PassLightingMode;
depthWrite: boolean;
alphaMask: boolean;
isDesktop: boolean;
vertexShader: string;
pixelShader: string;
vertexShaderDefines: string;
pixelShaderDefines: string;
name: string;
index: number;
shadersLoadedFrameNumber: number;
// Construct.
constructor(passName: string);
// Set blend mode.
setBlendMode(mode: BlendMode): void;
// Set depth compare mode.
setDepthTestMode(mode: CompareMode): void;
// Set pass lighting mode, affects what shader variations will be attempted to be loaded.
setLightingMode(mode: PassLightingMode): void;
// Set depth write on/off.
setDepthWrite(enable: boolean): void;
// Set alpha masking hint. Completely opaque draw calls will be performed before alpha masked.
setAlphaMask(enable: boolean): void;
// Set whether requires desktop level hardware.
setIsDesktop(enable: boolean): void;
// Set vertex shader name.
setVertexShader(name: string): void;
// Set pixel shader name.
setPixelShader(name: string): void;
// Set vertex shader defines.
setVertexShaderDefines(defines: string): void;
// Set pixel shader defines.
setPixelShaderDefines(defines: string): void;
// Reset shader pointers.
releaseShaders(): void;
// Mark shaders loaded this frame.
markShadersLoaded(frameNumber: number): void;
// Return pass name.
getName(): string;
// Return pass index. This is used for optimal render-time pass queries that avoid map lookups.
getIndex(): number;
// Return blend mode.
getBlendMode(): BlendMode;
// Return depth compare mode.
getDepthTestMode(): CompareMode;
// Return pass lighting mode.
getLightingMode(): PassLightingMode;
// Return last shaders loaded frame number.
getShadersLoadedFrameNumber(): number;
// Return depth write mode.
getDepthWrite(): boolean;
// Return alpha masking hint.
getAlphaMask(): boolean;
// Return vertex shader name.
getVertexShader(): string;
// Return pixel shader name.
getPixelShader(): string;
// Return vertex shader defines.
getVertexShaderDefines(): string;
// Return pixel shader defines.
getPixelShaderDefines(): string;
}
export class Technique extends Resource {
isDesktop: boolean;
numPasses: number;
// Construct.
constructor();
// Set whether requires desktop level hardware.
setIsDesktop(enable: boolean): void;
// Create a new pass.
createPass(passName: string): Pass;
// Remove a pass.
removePass(passName: string): void;
// Reset shader pointers in all passes.
releaseShaders(): void;
// Return whether technique is supported by the current hardware.
isSupported(): boolean;
// Return number of passes.
getNumPasses(): number;
// Return a pass type index by name. Allocate new if not used yet.
getPassIndex(passName: string): number;
}
export class View extends AObject {
graphics: Graphics;
renderer: Renderer;
scene: Scene;
octree: Octree;
camera: Camera;
renderTarget: RenderSurface;
drawDebug: boolean;
// Construct.
constructor();
// Define with rendertarget and viewport. Return true if successful.
define(renderTarget: RenderSurface, viewport: Viewport): boolean;
// Render batches.
render(): void;
// Return graphics subsystem.
getGraphics(): Graphics;
// Return renderer subsystem.
getRenderer(): Renderer;
// Return scene.
getScene(): Scene;
// Return octree.
getOctree(): Octree;
// Return camera.
getCamera(): Camera;
// Return the rendertarget. 0 if using the backbuffer.
getRenderTarget(): RenderSurface;
// Return whether should draw debug geometry.
getDrawDebug(): boolean;
// Set global (per-frame) shader parameters. Called by Batch and internally by View.
setGlobalShaderParameters(): void;
// Set camera-specific shader parameters. Called by Batch and internally by View.
setCameraShaderParameters(camera: Camera, setProjectionMatrix: boolean): void;
// Set G-buffer offset and inverse size shader parameters. Called by Batch and internally by View.
setGBufferShaderParameters(texSize: IntVector2, viewRect: IntRect): void;
}
export class Viewport extends AObject {
scene: Scene;
camera: Camera;
rect: IntRect;
renderPath: RenderPath;
drawDebug: boolean;
view: View;
width: number;
height: number;
// Construct with a full rectangle.
constructor(scene: Scene, camera: Camera, renderPath?: RenderPath);
// Set scene.
setScene(scene: Scene): void;
// Set camera.
setCamera(camera: Camera): void;
// Set rectangle.
setRect(rect: IntRect): void;
// Set rendering path from an XML file.
setRenderPath(file: XMLFile): void;
// Set whether to render debug geometry. Default true.
setDrawDebug(enable: boolean): void;
// Return scene.
getScene(): Scene;
// Return camera.
getCamera(): Camera;
// Return the internal rendering structure. May be null if the viewport has not been rendered yet.
getView(): View;
// Return rectangle.
getRect(): IntRect;
// Return the viewport width
getWidth(): number;
// Return the viewport height
getHeight(): number;
// Return rendering path.
getRenderPath(): RenderPath;
// Return whether to draw debug geometry.
getDrawDebug(): boolean;
worldToScreenPoint(worldPos: Vector3): IntVector2;
screenToWorldPoint(x: number, y: number, depth: number): Vector3;
// Allocate the view structure. Called by Renderer.
allocateView(): void;
}
export class Zone extends Drawable {
boundingBox: BoundingBox;
ambientColor: Color;
fogColor: Color;
fogStart: number;
fogEnd: number;
fogHeight: number;
fogHeightScale: number;
priority: number;
heightFog: boolean;
override: boolean;
ambientGradient: boolean;
zoneTexture: Texture;
ambientStartColor: Color;
ambientEndColor: Color;
// Construct.
constructor();
// Visualize the component as debug geometry.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Set local-space bounding box. Will be used as an oriented bounding box to test whether objects or the camera are inside.
setBoundingBox(box: BoundingBox): void;
// Set ambient color
setAmbientColor(color: Color): void;
// Set fog color.
setFogColor(color: Color): void;
// Set fog start distance.
setFogStart(start: number): void;
// Set fog end distance.
setFogEnd(end: number): void;
// Set fog height distance relative to the scene node's world position. Effective only in height fog mode.
setFogHeight(height: number): void;
// Set fog height scale. Effective only in height fog mode.
setFogHeightScale(scale: number): void;
// Set zone priority. If an object or camera is inside several zones, the one with highest priority is used.
setPriority(priority: number): void;
// Set height fog mode.
setHeightFog(enable: boolean): void;
// Set override mode. If camera is inside an override zone, that zone will be used for all rendered objects instead of their own zone.
setOverride(enable: boolean): void;
// Set ambient gradient mode. In gradient mode ambient color is interpolated from neighbor zones.
setAmbientGradient(enable: boolean): void;
// Set zone texture. This will be bound to the zone texture unit when rendering objects inside the zone. Note that the default shaders do not use it.
setZoneTexture(texture: Texture): void;
// Return zone's own ambient color, disregarding gradient mode.
getAmbientColor(): Color;
// Return ambient start color. Not safe to call from worker threads due to possible octree query.
getAmbientStartColor(): Color;
// Return ambient end color. Not safe to call from worker threads due to possible octree query.
getAmbientEndColor(): Color;
// Return fog color.
getFogColor(): Color;
// Return fog start distance.
getFogStart(): number;
// Return fog end distance.
getFogEnd(): number;
// Return fog height distance relative to the scene node's world position.
getFogHeight(): number;
// Return fog height scale.
getFogHeightScale(): number;
// Return zone priority.
getPriority(): number;
// Return whether height fog mode is enabled.
getHeightFog(): boolean;
// Return whether override mode is enabled.
getOverride(): boolean;
// Return whether ambient gradient mode is enabled.
getAmbientGradient(): boolean;
// Return zone texture.
getZoneTexture(): Texture;
// Check whether a point is inside.
isInside(point: Vector3): boolean;
}
export class Graphics extends AObject {
windowIcon: Image;
windowTitle: string;
srgb: boolean;
flushGPU: boolean;
forceGL2: boolean;
orientations: string;
textureForUpdate: Texture;
defaultTextureFilterMode: TextureFilterMode;
textureAnisotropy: number;
viewport: IntRect;
blendMode: BlendMode;
colorWrite: boolean;
cullMode: CullMode;
depthTest: CompareMode;
depthWrite: boolean;
fillMode: FillMode;
apiName: string;
windowPosition: IntVector2;
width: number;
height: number;
multiSample: number;
fullscreen: boolean;
borderless: boolean;
resizable: boolean;
vSync: boolean;
tripleBuffer: boolean;
numPrimitives: number;
numBatches: number;
dummyColorFormat: number;
shadowMapFormat: number;
hiresShadowMapFormat: number;
instancingSupport: boolean;
lightPrepassSupport: boolean;
deferredSupport: boolean;
anisotropySupport: boolean;
hardwareShadowSupport: boolean;
readableDepthSupport: boolean;
sRGBSupport: boolean;
sRGBWriteSupport: boolean;
desktopResolution: IntVector2;
vertexShader: ShaderVariation;
pixelShader: ShaderVariation;
depthStencil: RenderSurface;
depthTexture: Texture2D;
depthConstantBias: number;
depthSlopeScaledBias: number;
stencilTest: boolean;
scissorTest: boolean;
scissorRect: IntRect;
stencilTestMode: CompareMode;
stencilPass: StencilOp;
stencilFail: StencilOp;
stencilZFail: StencilOp;
stencilRef: number;
stencilCompareMask: number;
stencilWriteMask: number;
useClipPlane: boolean;
renderTargetDimensions: IntVector2;
vbo: number;
ubo: number;
alphaFormat: number;
luminanceFormat: number;
luminanceAlphaFormat: number;
rGBFormat: number;
rGBAFormat: number;
rGBA16Format: number;
rGBAFloat16Format: number;
rGBAFloat32Format: number;
rG16Format: number;
rGFloat16Format: number;
rGFloat32Format: number;
float16Format: number;
float32Format: number;
linearDepthFormat: number;
depthStencilFormat: number;
readableDepthFormat: number;
pixelUVOffset: Vector2;
maxBones: number;
gL3Support: boolean;
// Construct.
constructor();
// Set window icon.
setWindowIcon(windowIcon: Image): void;
// Set window title.
setWindowTitle(windowTitle: string): void;
// Set window size.
setWindowSize(width: number, height: number): void;
// Center window.
centerWindow(): void;
// Bring the window to front with focus
raiseWindow(): void;
// Set whether the main window uses sRGB conversion on write.
setSRGB(enable: boolean): void;
// Set whether to flush the GPU command buffer to prevent multiple frames being queued and uneven frame timesteps. Not yet implemented on OpenGL.
setFlushGPU(enable: boolean): void;
// Set forced use of OpenGL 2 even if OpenGL 3 is available. Must be called before setting the screen mode for the first time. Default false.
setForceGL2(enable: boolean): void;
// Set allowed screen orientations as a space-separated list of "LandscapeLeft", "LandscapeRight", "Portrait" and "PortraitUpsideDown". Affects currently only iOS platform.
setOrientations(orientations: string): void;
// Toggle between full screen and windowed mode. Return true if successful.
toggleFullscreen(): boolean;
// Close the window.
close(): void;
// Take a screenshot. Return true if successful.
takeScreenShot(destImage: Image): boolean;
// Begin frame rendering. Return true if device available and can render.
beginFrame(): boolean;
// End frame rendering and swap buffers.
endFrame(): void;
// Clear any or all of rendertarget, depth buffer and stencil buffer.
clear(flags: number, color?: Color, depth?: number, stencil?: number): void;
// Resolve multisampled backbuffer to a texture rendertarget. The texture's size should match the viewport size.
resolveToTexture(destination: Texture2D, viewport: IntRect): boolean;
// Draw indexed, instanced geometry.
drawInstanced(type: PrimitiveType, indexStart: number, indexCount: number, minVertex: number, vertexCount: number, instanceCount: number): void;
// Set shaders.
setShaders(vs: ShaderVariation, ps: ShaderVariation): void;
// Check whether a shader parameter exists on the currently set shaders.
hasShaderParameter(param: string): boolean;
// Check whether the current pixel shader uses a texture unit.
hasTextureUnit(unit: TextureUnit): boolean;
// Clear remembered shader parameter source group.
clearParameterSource(group: ShaderParameterGroup): void;
// Clear remembered shader parameter sources.
clearParameterSources(): void;
// Clear remembered transform shader parameter sources.
clearTransformSources(): void;
// Set texture.
setTexture(index: number, texture: Texture): void;
// Bind texture unit 0 for update. Called by Texture.
setTextureForUpdate(texture: Texture): void;
// Set default texture filtering mode.
setDefaultTextureFilterMode(mode: TextureFilterMode): void;
// Set texture anisotropy.
setTextureAnisotropy(level: number): void;
// Dirty texture parameters of all textures (when global settings change.)
setTextureParametersDirty(): void;
// Reset all rendertargets, depth-stencil surface and viewport.
resetRenderTargets(): void;
// Reset specific rendertarget.
resetRenderTarget(index: number): void;
// Reset depth-stencil surface.
resetDepthStencil(): void;
// Set viewport.
setViewport(rect: IntRect): void;
// Set blending mode.
setBlendMode(mode: BlendMode): void;
// Set color write on/off.
setColorWrite(enable: boolean): void;
// Set hardware culling mode.
setCullMode(mode: CullMode): void;
// Set depth bias.
setDepthBias(constantBias: number, slopeScaledBias: number): void;
// Set depth compare.
setDepthTest(mode: CompareMode): void;
// Set depth write on/off.
setDepthWrite(enable: boolean): void;
// Set polygon fill mode.
setFillMode(mode: FillMode): void;
// Set stencil test.
setStencilTest(enable: boolean, mode?: CompareMode, pass?: StencilOp, fail?: StencilOp, zFail?: StencilOp, stencilRef?: number, compareMask?: number, writeMask?: number): void;
// Begin dumping shader variation names to an XML file for precaching.
beginDumpShaders(fileName: string): void;
// End dumping shader variations names.
endDumpShaders(): void;
// Return whether rendering initialized.
isInitialized(): boolean;
// Return window title.
getWindowTitle(): string;
// Return graphics API name.
getApiName(): string;
// Return window position.
getWindowPosition(): IntVector2;
// Return window width.
getWidth(): number;
// Return window height.
getHeight(): number;
// Return multisample mode (1 = no multisampling.)
getMultiSample(): number;
// Return whether window is fullscreen.
getFullscreen(): boolean;
// Return whether window is borderless.
getBorderless(): boolean;
// Return whether window is resizable.
getResizable(): boolean;
// Return whether vertical sync is on.
getVSync(): boolean;
// Return whether triple buffering is enabled.
getTripleBuffer(): boolean;
// Return whether the main window is using sRGB conversion on write.
getSRGB(): boolean;
// Return whether the GPU command buffer is flushed each frame. Not yet implemented on OpenGL.
getFlushGPU(): boolean;
// Return whether OpenGL 2 use is forced.
getForceGL2(): boolean;
// Return allowed screen orientations.
getOrientations(): string;
// Return whether device is lost, and can not yet render.
isDeviceLost(): boolean;
// Return number of primitives drawn this frame.
getNumPrimitives(): number;
// Return number of batches drawn this frame.
getNumBatches(): number;
// Return dummy color texture format for shadow maps. 0 if not needed, may be nonzero on OS X to work around an Intel driver issue.
getDummyColorFormat(): number;
// Return shadow map depth texture format, or 0 if not supported.
getShadowMapFormat(): number;
// Return 24-bit shadow map depth texture format, or 0 if not supported.
getHiresShadowMapFormat(): number;
// Return whether hardware instancing is supported.
getInstancingSupport(): boolean;
// Return whether light pre-pass rendering is supported.
getLightPrepassSupport(): boolean;
// Return whether deferred rendering is supported.
getDeferredSupport(): boolean;
// Return whether anisotropic texture filtering is supported.
getAnisotropySupport(): boolean;
// Return whether shadow map depth compare is done in hardware. Always true on OpenGL.
getHardwareShadowSupport(): boolean;
// Return whether a readable hardware depth format is available.
getReadableDepthSupport(): boolean;
// Return whether sRGB conversion on texture sampling is supported.
getSRGBSupport(): boolean;
// Return whether sRGB conversion on rendertarget writing is supported.
getSRGBWriteSupport(): boolean;
// Return the desktop resolution.
getDesktopResolution(): IntVector2;
// Return a shader variation by name and defines.
getShader(type: ShaderType, name: string, defines?: string): ShaderVariation;
// Return vertex shader.
getVertexShader(): ShaderVariation;
// Return pixel shader.
getPixelShader(): ShaderVariation;
// Return texture unit index by name.
getTextureUnit(name: string): TextureUnit;
// Return texture unit name by index.
getTextureUnitName(unit: TextureUnit): string;
// Return texture by texture unit index.
getTexture(index: number): Texture;
// Return default texture filtering mode.
getDefaultTextureFilterMode(): TextureFilterMode;
// Return rendertarget by index.
getRenderTarget(index: number): RenderSurface;
// Return depth-stencil surface.
getDepthStencil(): RenderSurface;
// Return readable depth-stencil texture. Not created automatically on OpenGL.
getDepthTexture(): Texture2D;
// Return the viewport coordinates.
getViewport(): IntRect;
// Return texture anisotropy.
getTextureAnisotropy(): number;
// Return blending mode.
getBlendMode(): BlendMode;
// Return whether color write is enabled.
getColorWrite(): boolean;
// Return hardware culling mode.
getCullMode(): CullMode;
// Return depth constant bias.
getDepthConstantBias(): number;
// Return depth slope scaled bias.
getDepthSlopeScaledBias(): number;
// Return depth compare mode.
getDepthTest(): CompareMode;
// Return whether depth write is enabled.
getDepthWrite(): boolean;
// Return polygon fill mode.
getFillMode(): FillMode;
// Return whether stencil test is enabled.
getStencilTest(): boolean;
// Return whether scissor test is enabled.
getScissorTest(): boolean;
// Return scissor rectangle coordinates.
getScissorRect(): IntRect;
// Return stencil compare mode.
getStencilTestMode(): CompareMode;
// Return stencil operation to do if stencil test passes.
getStencilPass(): StencilOp;
// Return stencil operation to do if stencil test fails.
getStencilFail(): StencilOp;
// Return stencil operation to do if depth compare fails.
getStencilZFail(): StencilOp;
// Return stencil reference value.
getStencilRef(): number;
// Return stencil compare bitmask.
getStencilCompareMask(): number;
// Return stencil write bitmask.
getStencilWriteMask(): number;
// Return whether a custom clipping plane is in use.
getUseClipPlane(): boolean;
// Return rendertarget width and height.
getRenderTargetDimensions(): IntVector2;
// Window was resized through user interaction. Called by Input subsystem.
windowResized(): void;
// Window was moved through user interaction. Called by Input subsystem.
windowMoved(): void;
// Clean up too large scratch buffers.
cleanupScratchBuffers(): void;
// Clean up a render surface from all FBOs.
cleanupRenderSurface(surface: RenderSurface): void;
// Clean up shader programs when a shader variation is released or destroyed.
cleanupShaderPrograms(variation: ShaderVariation): void;
// Release/clear GPU objects and optionally close the window.
release(clearGPUObjects: boolean, closeWindow: boolean): void;
// Restore GPU objects and reinitialize state. Requires an open window.
restore(): void;
// Maximize the Window.
maximize(): void;
// Minimize the Window.
minimize(): void;
// Mark the FBO needing an update.
markFBODirty(): void;
// Bind a VBO, avoiding redundant operation.
setVBO(object: number): void;
// Bind a UBO, avoiding redundant operation.
setUBO(object: number): void;
// Return the API-specific alpha texture format.
getAlphaFormat(): number;
// Return the API-specific luminance texture format.
getLuminanceFormat(): number;
// Return the API-specific luminance alpha texture format.
getLuminanceAlphaFormat(): number;
// Return the API-specific RGB texture format.
getRGBFormat(): number;
// Return the API-specific RGBA texture format.
getRGBAFormat(): number;
// Return the API-specific RGBA 16-bit texture format.
getRGBA16Format(): number;
// Return the API-specific RGBA 16-bit float texture format.
getRGBAFloat16Format(): number;
// Return the API-specific RGBA 32-bit float texture format.
getRGBAFloat32Format(): number;
// Return the API-specific RG 16-bit texture format.
getRG16Format(): number;
// Return the API-specific RG 16-bit float texture format.
getRGFloat16Format(): number;
// Return the API-specific RG 32-bit float texture format.
getRGFloat32Format(): number;
// Return the API-specific single channel 16-bit float texture format.
getFloat16Format(): number;
// Return the API-specific single channel 32-bit float texture format.
getFloat32Format(): number;
// Return the API-specific linear depth texture format.
getLinearDepthFormat(): number;
// Return the API-specific hardware depth-stencil texture format.
getDepthStencilFormat(): number;
// Return the API-specific readable hardware depth format, or 0 if not supported.
getReadableDepthFormat(): number;
// Return UV offset required for pixel perfect rendering.
getPixelUVOffset(): Vector2;
// Return maximum number of supported bones for skinning.
getMaxBones(): number;
// Return whether is using an OpenGL 3 context.
getGL3Support(): boolean;
}
export class RenderSurface extends RefCounted {
numViewports: number;
updateMode: RenderSurfaceUpdateMode;
linkedRenderTarget: RenderSurface;
linkedDepthStencil: RenderSurface;
parentTexture: Texture;
renderBuffer: number;
width: number;
height: number;
usage: TextureUsage;
target: number;
// Construct with parent texture.
constructor(parentTexture: Texture);
// Set number of viewports.
setNumViewports(num: number): void;
// Set viewport.
setViewport(index: number, viewport: Viewport): void;
// Set viewport update mode. Default is to update when visible.
setUpdateMode(mode: RenderSurfaceUpdateMode): void;
// Set linked color rendertarget.
setLinkedRenderTarget(renderTarget: RenderSurface): void;
// Set linked depth-stencil surface.
setLinkedDepthStencil(depthStencil: RenderSurface): void;
// Queue manual update of the viewport(s).
queueUpdate(): void;
// Create a renderbuffer. Return true if successful.
createRenderBuffer(width: number, height: number, format: number): boolean;
// Handle device loss.
onDeviceLost(): void;
// Release renderbuffer if any.
release(): void;
// Return parent texture.
getParentTexture(): Texture;
// Return renderbuffer if created.
getRenderBuffer(): number;
// Return width.
getWidth(): number;
// Return height.
getHeight(): number;
// Return usage.
getUsage(): TextureUsage;
// Return number of viewports.
getNumViewports(): number;
// Return viewport by index.
getViewport(index: number): Viewport;
// Return viewport update mode.
getUpdateMode(): RenderSurfaceUpdateMode;
// Return linked color buffer.
getLinkedRenderTarget(): RenderSurface;
// Return linked depth buffer.
getLinkedDepthStencil(): RenderSurface;
// Set surface's OpenGL target.
setTarget(target: number): void;
// Return surface's OpenGL target.
getTarget(): number;
// Clear update flag. Called by Renderer.
wasUpdated(): void;
}
export class ShaderVariation extends RefCounted {
name: string;
defines: string;
owner: Shader;
shaderType: ShaderType;
fullName: string;
compilerOutput: string;
// Construct.
constructor(owner: Shader, type: ShaderType);
// Mark the GPU resource destroyed on context destruction.
onDeviceLost(): void;
// Release the shader.
release(): void;
// Compile the shader. Return true if successful.
create(): boolean;
// Set name.
setName(name: string): void;
// Set defines.
setDefines(defines: string): void;
// Return the owner resource.
getOwner(): Shader;
// Return shader type.
getShaderType(): ShaderType;
// Return name.
getName(): string;
// Return defines.
getDefines(): string;
// Return full shader name.
getFullName(): string;
// Return compile error/warning string.
getCompilerOutput(): string;
}
export class Texture extends Resource {
numLevels: number;
filterMode: TextureFilterMode;
shadowCompare: boolean;
borderColor: Color;
srgb: boolean;
backupTexture: Texture;
target: number;
format: number;
levels: number;
width: number;
height: number;
depth: number;
parametersDirty: boolean;
usage: TextureUsage;
components: number;
parameters: XMLFile;
// Construct.
constructor();
// Set number of requested mip levels. Needs to be called before setting size.
setNumLevels(levels: number): void;
// Set filtering mode.
setFilterMode(filter: TextureFilterMode): void;
// Set addressing mode by texture coordinate.
setAddressMode(coord: TextureCoordinate, address: TextureAddressMode): void;
// Set shadow compare mode.
setShadowCompare(enable: boolean): void;
// Set border color for border addressing mode.
setBorderColor(color: Color): void;
// Set sRGB sampling and writing mode.
setSRGB(enable: boolean): void;
// Set backup texture to use when rendering to this texture.
setBackupTexture(texture: Texture): void;
// Set mip levels to skip on a quality setting when loading. Ensures higher quality levels do not skip more.
setMipsToSkip(quality: number, mips: number): void;
// Dirty the parameters.
setParametersDirty(): void;
// Update changed parameters to OpenGL. Called by Graphics when binding the texture.
updateParameters(): void;
// Return texture's OpenGL target.
getTarget(): number;
// Return texture format.
getFormat(): number;
// Return whether the texture format is compressed.
isCompressed(): boolean;
// Return number of mip levels.
getLevels(): number;
// Return width.
getWidth(): number;
// Return height.
getHeight(): number;
// Return height.
getDepth(): number;
// Return whether parameters are dirty.
getParametersDirty(): boolean;
// Return filtering mode.
getFilterMode(): TextureFilterMode;
// Return addressing mode by texture coordinate.
getAddressMode(coord: TextureCoordinate): TextureAddressMode;
// Return whether shadow compare is enabled.
getShadowCompare(): boolean;
// Return border color.
getBorderColor(): Color;
// Return whether is using sRGB sampling and writing.
getSRGB(): boolean;
// Return backup texture.
getBackupTexture(): Texture;
// Return mip levels to skip on a quality setting when loading.
getMipsToSkip(quality: number): number;
// Return mip level width, or 0 if level does not exist.
getLevelWidth(level: number): number;
// Return mip level width, or 0 if level does not exist.
getLevelHeight(level: number): number;
// Return mip level depth, or 0 if level does not exist.
getLevelDepth(level: number): number;
// Return texture usage type.
getUsage(): TextureUsage;
// Return data size in bytes for a pixel or block row.
getRowDataSize(width: number): number;
// Return number of image components required to receive pixel data from GetData(), or 0 for compressed images.
getComponents(): number;
// Return the non-internal texture format corresponding to an OpenGL internal format.
getExternalFormat(format: number): number;
// Return the data type corresponding to an OpenGL internal format.
getDataType(format: number): number;
// Set additional parameters from an XML file.
setParameters(xml: XMLFile): void;
// Return the corresponding SRGB texture format if supported. If not supported, return format unchanged.
getSRGBFormat(format: number): number;
}
export class Texture2D extends Texture {
renderSurface: RenderSurface;
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Mark the GPU resource destroyed on context destruction.
onDeviceLost(): void;
// Recreate the GPU resource and restore data if applicable.
onDeviceReset(): void;
// Release the texture.
release(): void;
// Set size, format and usage. Zero size will follow application window size. Return true if successful.
setSize(width: number, height: number, format: number, usage?: TextureUsage): boolean;
// Return render surface.
getRenderSurface(): RenderSurface;
}
export class Texture3D extends Texture {
renderSurface: RenderSurface;
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Mark the GPU resource destroyed on context destruction.
onDeviceLost(): void;
// Recreate the GPU resource and restore data if applicable.
onDeviceReset(): void;
// Release the texture.
release(): void;
// Set size, format and usage. Zero size will follow application window size. Return true if successful.
setSize(width: number, height: number, depth: number, format: number, usage?: TextureUsage): boolean;
// Return render surface.
getRenderSurface(): RenderSurface;
}
export class TextureCube extends Texture {
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Mark the GPU resource destroyed on context destruction.
onDeviceLost(): void;
// Recreate the GPU resource and restore data if applicable.
onDeviceReset(): void;
// Release the texture.
release(): void;
// Set size, format and usage. Return true if successful.
setSize(size: number, format: number, usage?: TextureUsage): boolean;
// Return render surface for one face.
getRenderSurface(face: CubeMapFace): RenderSurface;
}
//----------------------------------------------------
// MODULE: Atomic3D
//----------------------------------------------------
export class AnimatedModel extends StaticModel {
updateGeometryType: UpdateGeometryType;
animationLodBias: number;
updateInvisible: boolean;
numAnimationStates: number;
numMorphs: number;
boneCreationEnabled: boolean;
// Construct.
constructor();
// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
applyAttributes(): void;
// Return whether a geometry update is necessary, and if it can happen in a worker thread.
getUpdateGeometryType(): UpdateGeometryType;
// Visualize the component as debug geometry.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Set model.
setModel(model: Model, createBones?: boolean): void;
// Add an animation.
addAnimationState(animation: Animation): AnimationState;
// Remove all animations.
removeAllAnimationStates(): void;
// Set animation LOD bias.
setAnimationLodBias(bias: number): void;
// Set whether to update animation and the bounding box when not visible. Recommended to enable for physically controlled models like ragdolls.
setUpdateInvisible(enable: boolean): void;
// Reset all vertex morphs to zero.
resetMorphWeights(): void;
// Return number of animation states.
getNumAnimationStates(): number;
// Return animation LOD bias.
getAnimationLodBias(): number;
// Return whether to update animation when not visible.
getUpdateInvisible(): boolean;
// Return number of vertex morphs.
getNumMorphs(): number;
// Return whether is the master (first) animated model.
isMaster(): boolean;
// Globally enable/disable bone creation, useful for when in the editor
setBoneCreationEnabled(enabled: boolean): void;
}
export class Animation extends Resource {
animationName: string;
length: number;
numTriggers: number;
animationNameHash: string;
numTracks: number;
// Construct.
constructor();
// Set animation name.
setAnimationName(name: string): void;
// Set animation length.
setLength(length: number): void;
// Remove a trigger point by index.
removeTrigger(index: number): void;
// Remove all trigger points.
removeAllTriggers(): void;
// Resize trigger point vector.
setNumTriggers(num: number): void;
// Return animation name.
getAnimationName(): string;
// Return animation name hash.
getAnimationNameHash(): string;
// Return animation length.
getLength(): number;
// Return number of animation tracks.
getNumTracks(): number;
// Return number of animation trigger points.
getNumTriggers(): number;
}
export class AnimationController extends Component {
// Construct.
constructor();
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Update the animations. Is called from HandleScenePostUpdate().
update(timeStep: number): void;
// Play an animation and set full target weight. Name must be the full resource name. Return true on success.
play(name: string, layer: number, looped: boolean, fadeInTime?: number): boolean;
// Play an animation, set full target weight and fade out all other animations on the same layer. Name must be the full resource name. Return true on success.
playExclusive(name: string, layer: number, looped: boolean, fadeTime?: number): boolean;
// Stop an animation. Zero fadetime is instant. Return true on success.
stop(name: string, fadeOutTime?: number): boolean;
// Stop all animations on a specific layer. Zero fadetime is instant.
stopLayer(layer: number, fadeOutTime?: number): void;
// Stop all animations. Zero fadetime is instant.
stopAll(fadeTime?: number): void;
// Fade animation to target weight. Return true on success.
fade(name: string, targetWeight: number, fadeTime: number): boolean;
// Fade other animations on the same layer to target weight. Return true on success.
fadeOthers(name: string, targetWeight: number, fadeTime: number): boolean;
// Set animation blending layer priority. Return true on success.
setLayer(name: string, layer: number): boolean;
// Set animation start bone. Return true on success.
setStartBone(name: string, startBoneName: string): boolean;
// Set animation time position. Return true on success.
setTime(name: string, time: number): boolean;
// Set animation weight. Return true on success.
setWeight(name: string, weight: number): boolean;
// Set animation looping. Return true on success.
setLooped(name: string, enable: boolean): boolean;
// Set animation speed. Return true on success.
setSpeed(name: string, speed: number): boolean;
// Set animation autofade at end (non-looped animations only.) Zero time disables. Return true on success.
setAutoFade(name: string, fadeOutTime: number): boolean;
// Return whether an animation is active. Note that non-looping animations that are being clamped at the end also return true.
isPlaying(name: string): boolean;
// Return whether an animation is fading in.
isFadingIn(name: string): boolean;
// Return whether an animation is fading out.
isFadingOut(name: string): boolean;
// Return whether an animation is at its end. Will return false if the animation is not active at all.
isAtEnd(name: string): boolean;
// Return animation blending layer.
getLayer(name: string): number;
// Return animation start bone name, or empty string if no such animation.
getStartBoneName(name: string): string;
// Return animation time position.
getTime(name: string): number;
// Return animation weight.
getWeight(name: string): number;
// Return animation looping.
isLooped(name: string): boolean;
// Return animation length.
getLength(name: string): number;
// Return animation speed.
getSpeed(name: string): number;
// Return animation fade target weight.
getFadeTarget(name: string): number;
// Return animation fade time.
getFadeTime(name: string): number;
// Return animation autofade time.
getAutoFade(name: string): number;
addAnimationResource(animation: Animation): void;
removeAnimationResource(animation: Animation): void;
clearAnimationResources(): void;
}
export class AnimationState extends RefCounted {
looped: boolean;
weight: number;
time: number;
layer: number;
animation: Animation;
model: AnimatedModel;
node: Node;
length: number;
// Construct with animated model and animation pointers.
constructor(model: AnimatedModel, animation: Animation);
// Set looping enabled/disabled.
setLooped(looped: boolean): void;
// Set blending weight.
setWeight(weight: number): void;
// Set time position. Does not fire animation triggers.
setTime(time: number): void;
// Modify blending weight.
addWeight(delta: number): void;
// Modify time position. %Animation triggers will be fired.
addTime(delta: number): void;
// Set blending layer.
setLayer(layer: number): void;
// Return animation.
getAnimation(): Animation;
// Return animated model this state belongs to (model mode.)
getModel(): AnimatedModel;
// Return root scene node this state controls (node hierarchy mode.)
getNode(): Node;
// Return whether weight is nonzero.
isEnabled(): boolean;
// Return whether looped.
isLooped(): boolean;
// Return blending weight.
getWeight(): number;
// Return time position.
getTime(): number;
// Return animation length.
getLength(): number;
// Return blending layer.
getLayer(): number;
// Apply the animation at the current time position.
apply(): void;
}
export class BillboardSet extends Drawable {
updateGeometryType: UpdateGeometryType;
material: Material;
numBillboards: number;
relative: boolean;
scaled: boolean;
sorted: boolean;
faceCameraMode: FaceCameraMode;
animationLodBias: number;
// Construct.
constructor();
// Return whether a geometry update is necessary, and if it can happen in a worker thread.
getUpdateGeometryType(): UpdateGeometryType;
// Set material.
setMaterial(material: Material): void;
// Set number of billboards.
setNumBillboards(num: number): void;
// Set whether billboards are relative to the scene node. Default true.
setRelative(enable: boolean): void;
// Set whether scene node scale affects billboards' size. Default true.
setScaled(enable: boolean): void;
// Set whether billboards are sorted by distance. Default false.
setSorted(enable: boolean): void;
// Set how the billboards should rotate in relation to the camera. Default is to follow camera rotation on all axes (FC_ROTATE_XYZ.)
setFaceCameraMode(mode: FaceCameraMode): void;
// Set animation LOD bias.
setAnimationLodBias(bias: number): void;
// Mark for bounding box and vertex buffer update. Call after modifying the billboards.
commit(): void;
// Return material.
getMaterial(): Material;
// Return number of billboards.
getNumBillboards(): number;
// Return whether billboards are relative to the scene node.
isRelative(): boolean;
// Return whether scene node scale affects billboards' size.
isScaled(): boolean;
// Return whether billboards are sorted.
isSorted(): boolean;
// Return how the billboards rotate in relation to the camera.
getFaceCameraMode(): FaceCameraMode;
// Return animation LOD bias.
getAnimationLodBias(): number;
}
export class CustomGeometry extends Drawable {
numOccluderTriangles: number;
numGeometries: number;
dynamic: boolean;
// Construct.
constructor();
// Return number of occlusion geometry triangles.
getNumOccluderTriangles(): number;
// Clear all geometries.
clear(): void;
// Set number of geometries.
setNumGeometries(num: number): void;
// Set vertex buffer dynamic mode. A dynamic buffer should be faster to update frequently. Effective at the next Commit() call.
setDynamic(enable: boolean): void;
// Begin defining a geometry. Clears existing vertices in that index.
beginGeometry(index: number, type: PrimitiveType): void;
// Define a vertex position. This begins a new vertex.
defineVertex(position: Vector3): void;
// Define a vertex normal.
defineNormal(normal: Vector3): void;
// Define a vertex color.
defineColor(color: Color): void;
// Define a vertex UV coordinate.
defineTexCoord(texCoord: Vector2): void;
// Define a vertex tangent.
defineTangent(tangent: Vector4): void;
// Set the primitive type, number of vertices and elements in a geometry, after which the vertices can be edited with GetVertex(). An alternative to BeginGeometry() / DefineVertex().
defineGeometry(index: number, type: PrimitiveType, numVertices: number, hasNormals: boolean, hasColors: boolean, hasTexCoords: boolean, hasTangents: boolean): void;
// Update vertex buffer and calculate the bounding box. Call after finishing defining geometry.
commit(): void;
// Return number of geometries.
getNumGeometries(): number;
// Return number of vertices in a geometry.
getNumVertices(index: number): number;
// Return whether vertex buffer dynamic mode is enabled.
isDynamic(): boolean;
// Return material by geometry index.
getMaterial(index?: number): Material;
}
export class DecalSet extends Drawable {
updateGeometryType: UpdateGeometryType;
material: Material;
maxVertices: number;
maxIndices: number;
numDecals: number;
numVertices: number;
numIndices: number;
// Construct.
constructor();
// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
applyAttributes(): void;
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Return whether a geometry update is necessary, and if it can happen in a worker thread.
getUpdateGeometryType(): UpdateGeometryType;
// Set material. The material should use a small negative depth bias to avoid Z-fighting.
setMaterial(material: Material): void;
// Set maximum number of decal vertices.
setMaxVertices(num: number): void;
// Set maximum number of decal vertex indices.
setMaxIndices(num: number): void;
// Add a decal at world coordinates, using a target drawable's geometry for reference. If the decal needs to move with the target, the decal component should be created to the target's node. Return true if successful.
addDecal(target: Drawable, worldPosition: Vector3, worldRotation: Quaternion, size: number, aspectRatio: number, depth: number, topLeftUV: Vector2, bottomRightUV: Vector2, timeToLive?: number, normalCutoff?: number, subGeometry?: number): boolean;
// Remove n oldest decals.
removeDecals(num: number): void;
// Remove all decals.
removeAllDecals(): void;
// Return material.
getMaterial(): Material;
// Return number of decals.
getNumDecals(): number;
// Retur number of vertices in the decals.
getNumVertices(): number;
// Retur number of vertex indices in the decals.
getNumIndices(): number;
// Return maximum number of decal vertices.
getMaxVertices(): number;
// Return maximum number of decal vertex indices.
getMaxIndices(): number;
}
export class Model extends Resource {
boundingBox: BoundingBox;
numGeometries: number;
numMorphs: number;
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Set local-space bounding box.
setBoundingBox(box: BoundingBox): void;
// Set number of geometries.
setNumGeometries(num: number): void;
// Set number of LOD levels in a geometry.
setNumGeometryLodLevels(index: number, num: number): boolean;
// Set geometry center.
setGeometryCenter(index: number, center: Vector3): boolean;
// Clone the model. The geometry data is deep-copied and can be modified in the clone without affecting the original.
clone(cloneName?: string): Model;
// Return bounding box.
getBoundingBox(): BoundingBox;
// Return number of geometries.
getNumGeometries(): number;
// Return number of LOD levels in geometry.
getNumGeometryLodLevels(index: number): number;
// Return geometry center by index.
getGeometryCenter(index: number): Vector3;
// Return number of vertex morphs.
getNumMorphs(): number;
// Return vertex buffer morph range start.
getMorphRangeStart(bufferIndex: number): number;
// Return vertex buffer morph range vertex count.
getMorphRangeCount(bufferIndex: number): number;
}
export class ParticleEffect extends Resource {
material: Material;
numParticles: number;
updateInvisible: boolean;
relative: boolean;
scaled: boolean;
sorted: boolean;
animationLodBias: number;
emitterType: EmitterType;
emitterSize: Vector3;
minDirection: Vector3;
maxDirection: Vector3;
constantForce: Vector3;
dampingForce: number;
activeTime: number;
inactiveTime: number;
minEmissionRate: number;
maxEmissionRate: number;
minParticleSize: Vector2;
maxParticleSize: Vector2;
minTimeToLive: number;
maxTimeToLive: number;
minVelocity: number;
maxVelocity: number;
minRotation: number;
maxRotation: number;
minRotationSpeed: number;
maxRotationSpeed: number;
sizeAdd: number;
sizeMul: number;
numColorFrames: number;
numTextureFrames: number;
randomDirection: Vector3;
randomSize: Vector2;
randomVelocity: number;
randomTimeToLive: number;
randomRotationSpeed: number;
randomRotation: number;
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Set material.
setMaterial(material: Material): void;
// Set maximum number of particles.
setNumParticles(num: number): void;
// Set whether to update when particles are not visible.
setUpdateInvisible(enable: boolean): void;
// Set whether billboards are relative to the scene node. Default true.
setRelative(enable: boolean): void;
// Set scaled.
setScaled(enable: boolean): void;
// Set sorted.
setSorted(enable: boolean): void;
// Set animation LOD bias.
setAnimationLodBias(lodBias: number): void;
// Set emitter type.
setEmitterType(type: EmitterType): void;
// Set emitter size.
setEmitterSize(size: Vector3): void;
// Set negative direction limit.
setMinDirection(direction: Vector3): void;
// Set positive direction limit.
setMaxDirection(direction: Vector3): void;
// Set constant force acting on particles.
setConstantForce(force: Vector3): void;
// Set particle velocity damping force.
setDampingForce(force: number): void;
// Set emission active period length (0 = infinite.)
setActiveTime(time: number): void;
// Set emission inactive period length (0 = infinite.)
setInactiveTime(time: number): void;
// Set minimum emission rate.
setMinEmissionRate(rate: number): void;
// Set maximum emission rate.
setMaxEmissionRate(rate: number): void;
// Set particle minimum size.
setMinParticleSize(size: Vector2): void;
// Set particle maximum size.
setMaxParticleSize(size: Vector2): void;
// Set particle minimum time to live.
setMinTimeToLive(time: number): void;
// Set particle maximum time to live.
setMaxTimeToLive(time: number): void;
// Set particle minimum velocity.
setMinVelocity(velocity: number): void;
// Set particle maximum velocity.
setMaxVelocity(velocity: number): void;
// Set particle minimum rotation.
setMinRotation(rotation: number): void;
// Set particle maximum rotation.
setMaxRotation(rotation: number): void;
// Set particle minimum rotation speed.
setMinRotationSpeed(speed: number): void;
// Set particle maximum rotation speed.
setMaxRotationSpeed(speed: number): void;
// Set particle size additive modifier.
setSizeAdd(sizeAdd: number): void;
// Set particle size multiplicative modifier.
setSizeMul(sizeMul: number): void;
// Add a color frame sorted in the correct position based on time.
addColorTime(color: Color, time: number): void;
// Remove color frame at index
removeColorFrame(index: number): void;
// Set number of color frames.
setNumColorFrames(number: number): void;
// Sort the list of color frames based on time.
sortColorFrames(): void;
// Add a texture frame sorted in the correct position based on time.
addTextureTime(uv: Rect, time: number): void;
// Remove texture frame at index
removeTextureFrame(index: number): void;
// Set number of texture frames.
setNumTextureFrames(number: number): void;
// Sort the list of texture frames based on time.
sortTextureFrames(): void;
// Return material.
getMaterial(): Material;
// Return maximum number of particles.
getNumParticles(): number;
// Return whether to update when particles are not visible.
getUpdateInvisible(): boolean;
// Return whether billboards are relative to the scene node.
isRelative(): boolean;
// Return whether scene node scale affects billboards' size.
isScaled(): boolean;
// Return whether billboards are sorted.
isSorted(): boolean;
// Return animation Lod bias.
getAnimationLodBias(): number;
// Return emitter type.
getEmitterType(): EmitterType;
// Return emitter size.
getEmitterSize(): Vector3;
// Return negative direction limit.
getMinDirection(): Vector3;
// Return positive direction limit.
getMaxDirection(): Vector3;
// Return constant force acting on particles.
getConstantForce(): Vector3;
// Return particle velocity damping force.
getDampingForce(): number;
// Return emission active period length (0 = infinite.)
getActiveTime(): number;
// Return emission inactive period length (0 = infinite.)
getInactiveTime(): number;
// Return minimum emission rate.
getMinEmissionRate(): number;
// Return maximum emission rate.
getMaxEmissionRate(): number;
// Return particle minimum size.
getMinParticleSize(): Vector2;
// Return particle maximum size.
getMaxParticleSize(): Vector2;
// Return particle minimum time to live.
getMinTimeToLive(): number;
// Return particle maximum time to live.
getMaxTimeToLive(): number;
// Return particle minimum velocity.
getMinVelocity(): number;
// Return particle maximum velocity.
getMaxVelocity(): number;
// Return particle minimum rotation.
getMinRotation(): number;
// Return particle maximum rotation.
getMaxRotation(): number;
// Return particle minimum rotation speed.
getMinRotationSpeed(): number;
// Return particle maximum rotation speed.
getMaxRotationSpeed(): number;
// Return particle size additive modifier.
getSizeAdd(): number;
// Return particle size multiplicative modifier.
getSizeMul(): number;
// Return number of color animation frames.
getNumColorFrames(): number;
// Return number of texture animation frames.
getNumTextureFrames(): number;
// Return random direction.
getRandomDirection(): Vector3;
// Return random size.
getRandomSize(): Vector2;
// Return random velocity.
getRandomVelocity(): number;
// Return random timetolive.
getRandomTimeToLive(): number;
// Return random rotationspeed.
getRandomRotationSpeed(): number;
// Return random rotation.
getRandomRotation(): number;
}
export class ParticleEmitter extends BillboardSet {
effect: ParticleEffect;
numParticles: number;
emitting: boolean;
serializeParticles: boolean;
// Construct.
constructor();
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Set particle effect.
setEffect(effect: ParticleEffect): void;
// Set maximum number of particles.
setNumParticles(num: number): void;
// Set whether should be emitting. If the state was changed, also resets the emission period timer.
setEmitting(enable: boolean): void;
// Set whether particles should be serialized. Default true, set false to reduce scene file size.
setSerializeParticles(enable: boolean): void;
// Reset the emission period timer.
resetEmissionTimer(): void;
// Remove all current particles.
removeAllParticles(): void;
// Reset the particle emitter completely. Removes current particles, sets emitting state on, and resets the emission timer.
reset(): void;
// Apply not continuously updated values such as the material, the number of particles and sorting mode from the particle effect. Call this if you change the effect programmatically.
applyEffect(): void;
// Return particle effect.
getEffect(): ParticleEffect;
// Return maximum number of particles.
getNumParticles(): number;
// Return whether is currently emitting.
isEmitting(): boolean;
// Return whether particles are to be serialized.
getSerializeParticles(): boolean;
}
export class Skybox extends StaticModel {
// Construct.
constructor();
}
export class StaticModel extends Drawable {
numOccluderTriangles: number;
model: Model;
material: Material;
occlusionLodLevel: number;
numGeometries: number;
// Construct.
constructor();
// Return number of occlusion geometry triangles.
getNumOccluderTriangles(): number;
// Set model.
setModel(model: Model): void;
// Set material on all geometries.
setMaterial(material: Material): void;
// Set occlusion LOD level. By default (M_MAX_UNSIGNED) same as visible.
setOcclusionLodLevel(level: number): void;
// Apply default materials from a material list file. If filename is empty (default), the model's resource name with extension .txt will be used.
applyMaterialList(fileName?: string): void;
// Return model.
getModel(): Model;
// Return number of geometries.
getNumGeometries(): number;
// Return material by geometry index.
getMaterial(index?: number): Material;
// Return occlusion LOD level.
getOcclusionLodLevel(): number;
// Determines if the given world space point is within the model geometry.
isInside(point: Vector3): boolean;
// Determines if the given local space point is within the model geometry.
isInsideLocal(point: Vector3): boolean;
setMaterialIndex(index:number, material:Material);
}
export class StaticModelGroup extends StaticModel {
numOccluderTriangles: number;
numInstanceNodes: number;
// Construct.
constructor();
// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
applyAttributes(): void;
// Return number of occlusion geometry triangles.
getNumOccluderTriangles(): number;
// Add an instance scene node. It does not need any drawable components of its own.
addInstanceNode(node: Node): void;
// Remove an instance scene node.
removeInstanceNode(node: Node): void;
// Remove all instance scene nodes.
removeAllInstanceNodes(): void;
// Return number of instance nodes.
getNumInstanceNodes(): number;
// Return instance node by index.
getInstanceNode(index: number): Node;
}
export class Terrain extends Component {
patchSize: number;
spacing: Vector3;
smoothing: boolean;
material: Material;
drawDistance: number;
shadowDistance: number;
lodBias: number;
viewMask: number;
lightMask: number;
shadowMask: number;
zoneMask: number;
maxLights: number;
castShadows: boolean;
occluder: boolean;
occludee: boolean;
numVertices: IntVector2;
numPatches: IntVector2;
heightMap: Image;
patchSizeAttr: number;
// Construct.
constructor();
// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
applyAttributes(): void;
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Set patch quads per side. Must be a power of two.
setPatchSize(size: number): void;
// Set vertex (XZ) and height (Y) spacing.
setSpacing(spacing: Vector3): void;
// Set smoothing of heightmap.
setSmoothing(enable: boolean): void;
// Set heightmap image. Dimensions should be a power of two + 1. Uses 8-bit grayscale, or optionally red as MSB and green as LSB for 16-bit accuracy. Return true if successful.
setHeightMap(image: Image): boolean;
// Set material.
setMaterial(material: Material): void;
// Set draw distance for patches.
setDrawDistance(distance: number): void;
// Set shadow draw distance for patches.
setShadowDistance(distance: number): void;
// Set LOD bias for patches. Affects which terrain LOD to display.
setLodBias(bias: number): void;
// Set view mask for patches. Is and'ed with camera's view mask to see if the object should be rendered.
setViewMask(mask: number): void;
// Set light mask for patches. Is and'ed with light's and zone's light mask to see if the object should be lit.
setLightMask(mask: number): void;
// Set shadow mask for patches. Is and'ed with light's light mask and zone's shadow mask to see if the object should be rendered to a shadow map.
setShadowMask(mask: number): void;
// Set zone mask for patches. Is and'ed with zone's zone mask to see if the object should belong to the zone.
setZoneMask(mask: number): void;
// Set maximum number of per-pixel lights for patches. Default 0 is unlimited.
setMaxLights(num: number): void;
// Set shadowcaster flag for patches.
setCastShadows(enable: boolean): void;
// Set occlusion flag for patches. Occlusion uses the coarsest LOD and may potentially be too aggressive, so use with caution.
setOccluder(enable: boolean): void;
// Set occludee flag for patches.
setOccludee(enable: boolean): void;
// Apply changes from the heightmap image.
applyHeightMap(): void;
// Return patch quads per side.
getPatchSize(): number;
// Return vertex and height spacing.
getSpacing(): Vector3;
// Return heightmap size in vertices.
getNumVertices(): IntVector2;
// Return heightmap size in patches.
getNumPatches(): IntVector2;
// Return whether smoothing is in use.
getSmoothing(): boolean;
// Return heightmap image.
getHeightMap(): Image;
// Return material.
getMaterial(): Material;
// Return height at world coordinates.
getHeight(worldPosition: Vector3): number;
// Return normal at world coordinates.
getNormal(worldPosition: Vector3): Vector3;
// Convert world position to heightmap pixel position. Note that the internal height data representation is reversed vertically, but in the heightmap image north is at the top.
worldToHeightMap(worldPosition: Vector3): IntVector2;
// Return draw distance.
getDrawDistance(): number;
// Return shadow draw distance.
getShadowDistance(): number;
// Return LOD bias.
getLodBias(): number;
// Return view mask.
getViewMask(): number;
// Return light mask.
getLightMask(): number;
// Return shadow mask.
getShadowMask(): number;
// Return zone mask.
getZoneMask(): number;
// Return maximum number of per-pixel lights.
getMaxLights(): number;
// Return visible flag.
isVisible(): boolean;
// Return shadowcaster flag.
getCastShadows(): boolean;
// Return occluder flag.
isOccluder(): boolean;
// Return occludee flag.
isOccludee(): boolean;
// Regenerate patch geometry.
createPatchGeometry(patch: TerrainPatch): void;
// Update patch based on LOD and neighbor LOD.
updatePatchLod(patch: TerrainPatch): void;
// Set patch size attribute.
setPatchSizeAttr(value: number): void;
}
export class TerrainPatch extends Drawable {
updateGeometryType: UpdateGeometryType;
numOccluderTriangles: number;
owner: Terrain;
material: Material;
boundingBox: BoundingBox;
coordinates: IntVector2;
occlusionOffset: number;
northPatch: TerrainPatch;
southPatch: TerrainPatch;
westPatch: TerrainPatch;
eastPatch: TerrainPatch;
lodLevel: number;
// Construct.
constructor();
// Return whether a geometry update is necessary, and if it can happen in a worker thread.
getUpdateGeometryType(): UpdateGeometryType;
// Return number of occlusion geometry triangles.
getNumOccluderTriangles(): number;
// Visualize the component as debug geometry.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Set owner terrain.
setOwner(terrain: Terrain): void;
// Set neighbor patches.
setNeighbors(north: TerrainPatch, south: TerrainPatch, west: TerrainPatch, east: TerrainPatch): void;
// Set material.
setMaterial(material: Material): void;
// Set local-space bounding box.
setBoundingBox(box: BoundingBox): void;
// Set patch coordinates.
setCoordinates(coordinates: IntVector2): void;
// Set vertical offset for occlusion geometry. Should be negative.
setOcclusionOffset(offset: number): void;
// Reset to LOD level 0.
resetLod(): void;
// Return owner terrain.
getOwner(): Terrain;
// Return north neighbor patch.
getNorthPatch(): TerrainPatch;
// Return south neighbor patch.
getSouthPatch(): TerrainPatch;
// Return west neighbor patch.
getWestPatch(): TerrainPatch;
// Return east neighbor patch.
getEastPatch(): TerrainPatch;
// Return patch coordinates.
getCoordinates(): IntVector2;
// Return current LOD level.
getLodLevel(): number;
// Return vertical offset for occlusion geometry..
getOcclusionOffset(): number;
}
//----------------------------------------------------
// MODULE: Atomic2D
//----------------------------------------------------
export class AnimatedSprite2D extends StaticSprite2D {
speed: number;
animationSet: AnimationSet2D;
loopMode: LoopMode2D;
animation: string;
rootNode: Node;
animationAttr: string;
// Construct.
constructor();
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Set speed.
setSpeed(speed: number): void;
// Set animation by name and loop mode.
setAnimation(name: string, loopMode?: LoopMode2D): void;
// Set animation set.
setAnimationSet(animationSet: AnimationSet2D): void;
// Set loop mode.
setLoopMode(loopMode: LoopMode2D): void;
// Return speed.
getSpeed(): number;
// Return animation name.
getAnimation(): string;
// Return animation.
getAnimationSet(): AnimationSet2D;
// Return loop mode.
getLoopMode(): LoopMode2D;
// Return root node.
getRootNode(): Node;
// Set animation by name.
setAnimationAttr(name: string): void;
}
export class Animation2D extends RefCounted {
name: string;
length: number;
looped: boolean;
animationSet: AnimationSet2D;
numTracks: number;
// Construct.
constructor(animationSet: AnimationSet2D);
// Set name.
setName(name: string): void;
// Set length.
setLength(length: number): void;
// Set looped.
setLooped(looped: boolean): void;
// Return animation set.
getAnimationSet(): AnimationSet2D;
// Return name.
getName(): string;
// Return length.
getLength(): number;
// Return looped.
isLooped(): boolean;
// Return number of animation tracks.
getNumTracks(): number;
}
export class AnimationSet2D extends Resource {
numAnimations: number;
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Get number of animations.
getNumAnimations(): number;
}
export class CollisionBox2D extends CollisionShape2D {
size: Vector2;
angle: number;
center: Vector2;
// Construct.
constructor();
// Set size.
setSize(size: Vector2): void;
// Set angle.
setAngle(angle: number): void;
// Return size.
getSize(): Vector2;
// Return center.
getCenter(): Vector2;
// Return angle.
getAngle(): number;
}
export class CollisionChain2D extends CollisionShape2D {
loop: boolean;
vertexCount: number;
// Construct.
constructor();
// Set loop.
setLoop(loop: boolean): void;
// Set vertex count.
setVertexCount(count: number): void;
// Set vertex.
setVertex(index: number, vertex: Vector2): void;
// Return loop.
getLoop(): boolean;
// Return vertex count.
getVertexCount(): number;
// Return vertex.
getVertex(index: number): Vector2;
}
export class CollisionCircle2D extends CollisionShape2D {
radius: number;
center: Vector2;
// Construct.
constructor();
// Set radius.
setRadius(radius: number): void;
// Return radius.
getRadius(): number;
// Return center.
getCenter(): Vector2;
}
export class CollisionEdge2D extends CollisionShape2D {
vertex1: Vector2;
vertex2: Vector2;
// Construct.
constructor();
// Set vertex 1.
setVertex1(vertex: Vector2): void;
// Set vertex 2.
setVertex2(vertex: Vector2): void;
// Set vertices.
setVertices(vertex1: Vector2, vertex2: Vector2): void;
// Return vertex 1.
getVertex1(): Vector2;
// Return vertex 2.
getVertex2(): Vector2;
}
export class CollisionPolygon2D extends CollisionShape2D {
vertexCount: number;
// Construct.
constructor();
// Set vertex count.
setVertexCount(count: number): void;
// Set vertex.
setVertex(index: number, vertex: Vector2): void;
// Return vertex count.
getVertexCount(): number;
// Return vertex.
getVertex(index: number): Vector2;
}
export class CollisionShape2D extends Component {
trigger: boolean;
categoryBits: number;
maskBits: number;
groupIndex: number;
density: number;
friction: number;
restitution: number;
mass: number;
inertia: number;
massCenter: Vector2;
// Construct.
constructor();
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Set trigger.
setTrigger(trigger: boolean): void;
// Set filter category bits.
setCategoryBits(categoryBits: number): void;
// Set filter mask bits.
setMaskBits(maskBits: number): void;
// Set filter group index.
setGroupIndex(groupIndex: number): void;
// Set density.
setDensity(density: number): void;
// Set friction.
setFriction(friction: number): void;
// Set restitution .
setRestitution(restitution: number): void;
// Create fixture.
createFixture(): void;
// Release fixture.
releaseFixture(): void;
// Return trigger.
isTrigger(): boolean;
// Return filter category bits.
getCategoryBits(): number;
// Return filter mask bits.
getMaskBits(): number;
// Return filter group index.
getGroupIndex(): number;
// Return density.
getDensity(): number;
// Return friction.
getFriction(): number;
// Return restitution.
getRestitution(): number;
// Return mass.
getMass(): number;
// Return inertia.
getInertia(): number;
// Return mass center.
getMassCenter(): Vector2;
}
export class Constraint2D extends Component {
otherBody: RigidBody2D;
collideConnected: boolean;
attachedConstraint: Constraint2D;
ownerBody: RigidBody2D;
// Construct.
constructor();
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Create Joint.
createJoint(): void;
// Release Joint.
releaseJoint(): void;
// Set other rigid body.
setOtherBody(body: RigidBody2D): void;
// Set collide connected.
setCollideConnected(collideConnected: boolean): void;
// Set attached constriant (for gear).
setAttachedConstraint(constraint: Constraint2D): void;
// Return owner body.
getOwnerBody(): RigidBody2D;
// Return other body.
getOtherBody(): RigidBody2D;
// Return collide connected.
getCollideConnected(): boolean;
// Return attached constraint (for gear).
getAttachedConstraint(): Constraint2D;
}
export class ConstraintDistance2D extends Constraint2D {
ownerBodyAnchor: Vector2;
otherBodyAnchor: Vector2;
frequencyHz: number;
dampingRatio: number;
// Construct.
constructor();
// Set owner body anchor.
setOwnerBodyAnchor(anchor: Vector2): void;
// Set other body anchor.
setOtherBodyAnchor(anchor: Vector2): void;
// Set frequency Hz.
setFrequencyHz(frequencyHz: number): void;
// Set damping ratio.
setDampingRatio(dampingRatio: number): void;
// Return owner body anchor.
getOwnerBodyAnchor(): Vector2;
// Return other body anchor.
getOtherBodyAnchor(): Vector2;
// Return frequency Hz.
getFrequencyHz(): number;
// Return damping ratio.
getDampingRatio(): number;
}
export class ConstraintFriction2D extends Constraint2D {
anchor: Vector2;
maxForce: number;
maxTorque: number;
// Construct.
constructor();
// Set anchor.
setAnchor(anchor: Vector2): void;
// Set max force.
setMaxForce(maxForce: number): void;
// Set max torque.
setMaxTorque(maxTorque: number): void;
// Return anchor.
getAnchor(): Vector2;
// Set max force.
getMaxForce(): number;
// Set max torque.
getMaxTorque(): number;
}
export class ConstraintGear2D extends Constraint2D {
ownerConstraint: Constraint2D;
otherConstraint: Constraint2D;
ratio: number;
// Construct.
constructor();
// Set owner constraint.
setOwnerConstraint(constraint: Constraint2D): void;
// Set other constraint.
setOtherConstraint(constraint: Constraint2D): void;
// Set ratio.
setRatio(ratio: number): void;
// Return owner constraint.
getOwnerConstraint(): Constraint2D;
// Return other constraint.
getOtherConstraint(): Constraint2D;
// Return ratio.
getRatio(): number;
}
export class ConstraintMotor2D extends Constraint2D {
linearOffset: Vector2;
angularOffset: number;
maxForce: number;
maxTorque: number;
correctionFactor: number;
// Construct.
constructor();
// Set linear offset.
setLinearOffset(linearOffset: Vector2): void;
// Set angular offset.
setAngularOffset(angularOffset: number): void;
// Set max force.
setMaxForce(maxForce: number): void;
// Set max torque.
setMaxTorque(maxTorque: number): void;
// Set correction factor.
setCorrectionFactor(correctionFactor: number): void;
// Return linear offset.
getLinearOffset(): Vector2;
// Return angular offset.
getAngularOffset(): number;
// Return max force.
getMaxForce(): number;
// Return max torque.
getMaxTorque(): number;
// Return correction factor.
getCorrectionFactor(): number;
}
export class ConstraintMouse2D extends Constraint2D {
target: Vector2;
maxForce: number;
frequencyHz: number;
dampingRatio: number;
// Construct.
constructor();
// Set target.
setTarget(target: Vector2): void;
// Set max force.
setMaxForce(maxForce: number): void;
// Set frequency Hz.
setFrequencyHz(frequencyHz: number): void;
// Set damping ratio.
setDampingRatio(dampingRatio: number): void;
// Return target.
getTarget(): Vector2;
// Return max force.
getMaxForce(): number;
// Return frequency Hz.
getFrequencyHz(): number;
// Return damping ratio.
getDampingRatio(): number;
}
export class ConstraintPrismatic2D extends Constraint2D {
anchor: Vector2;
axis: Vector2;
enableLimit: boolean;
lowerTranslation: number;
upperTranslation: number;
enableMotor: boolean;
maxMotorForce: number;
motorSpeed: number;
// Construct.
constructor();
// Set anchor.
setAnchor(anchor: Vector2): void;
// Set axis.
setAxis(axis: Vector2): void;
// Set enable limit.
setEnableLimit(enableLimit: boolean): void;
// Set lower translation.
setLowerTranslation(lowerTranslation: number): void;
// Set upper translation.
setUpperTranslation(upperTranslation: number): void;
// Set enable motor.
setEnableMotor(enableMotor: boolean): void;
// Set maxmotor force.
setMaxMotorForce(maxMotorForce: number): void;
// Set motor speed.
setMotorSpeed(motorSpeed: number): void;
// Return anchor.
getAnchor(): Vector2;
// Return axis.
getAxis(): Vector2;
// Return enable limit.
getEnableLimit(): boolean;
// Return lower translation.
getLowerTranslation(): number;
// Return upper translation.
getUpperTranslation(): number;
// Return enable motor.
getEnableMotor(): boolean;
// Return maxmotor force.
getMaxMotorForce(): number;
// Return motor speed.
getMotorSpeed(): number;
}
export class ConstraintPulley2D extends Constraint2D {
ownerBodyGroundAnchor: Vector2;
otherBodyGroundAnchor: Vector2;
ownerBodyAnchor: Vector2;
otherBodyAnchor: Vector2;
ratio: number;
// Construct.
constructor();
// Set other body ground anchor point.
setOwnerBodyGroundAnchor(groundAnchor: Vector2): void;
// Set other body ground anchor point.
setOtherBodyGroundAnchor(groundAnchor: Vector2): void;
// Set owner body anchor point.
setOwnerBodyAnchor(anchor: Vector2): void;
// Set other body anchor point.
setOtherBodyAnchor(anchor: Vector2): void;
// Set ratio.
setRatio(ratio: number): void;
// Return owner body ground anchor.
getOwnerBodyGroundAnchor(): Vector2;
// return other body ground anchor.
getOtherBodyGroundAnchor(): Vector2;
// Return owner body anchor.
getOwnerBodyAnchor(): Vector2;
// Return other body anchor.
getOtherBodyAnchor(): Vector2;
// Return ratio.
getRatio(): number;
}
export class ConstraintRevolute2D extends Constraint2D {
anchor: Vector2;
enableLimit: boolean;
lowerAngle: number;
upperAngle: number;
enableMotor: boolean;
motorSpeed: number;
maxMotorTorque: number;
// Construct.
constructor();
// Set anchor.
setAnchor(anchor: Vector2): void;
// Set enable limit.
setEnableLimit(enableLimit: boolean): void;
// Set lower angle.
setLowerAngle(lowerAngle: number): void;
// Set upper angle.
setUpperAngle(upperAngle: number): void;
// Set enable motor.
setEnableMotor(enableMotor: boolean): void;
// Set motor speed.
setMotorSpeed(motorSpeed: number): void;
// Set max motor torque.
setMaxMotorTorque(maxMotorTorque: number): void;
// Return anchor.
getAnchor(): Vector2;
// Return enable limit.
getEnableLimit(): boolean;
// Return lower angle.
getLowerAngle(): number;
// Return upper angle.
getUpperAngle(): number;
// Return enable motor.
getEnableMotor(): boolean;
// Return motor speed.
getMotorSpeed(): number;
// Return max motor torque.
getMaxMotorTorque(): number;
}
export class ConstraintRope2D extends Constraint2D {
ownerBodyAnchor: Vector2;
otherBodyAnchor: Vector2;
maxLength: number;
// Construct.
constructor();
// Set owner body anchor.
setOwnerBodyAnchor(anchor: Vector2): void;
// Set other body anchor.
setOtherBodyAnchor(anchor: Vector2): void;
// Set max length.
setMaxLength(maxLength: number): void;
// Return owner body anchor.
getOwnerBodyAnchor(): Vector2;
// Return other body anchor.
getOtherBodyAnchor(): Vector2;
// Return max length.
getMaxLength(): number;
}
export class ConstraintWeld2D extends Constraint2D {
anchor: Vector2;
frequencyHz: number;
dampingRatio: number;
// Construct.
constructor();
// Set anchor.
setAnchor(anchor: Vector2): void;
// Set frequency Hz.
setFrequencyHz(frequencyHz: number): void;
// Set damping ratio.
setDampingRatio(dampingRatio: number): void;
// Return anchor.
getAnchor(): Vector2;
// Return frequency Hz.
getFrequencyHz(): number;
// Return damping ratio.
getDampingRatio(): number;
}
export class ConstraintWheel2D extends Constraint2D {
anchor: Vector2;
axis: Vector2;
enableMotor: boolean;
maxMotorTorque: number;
motorSpeed: number;
frequencyHz: number;
dampingRatio: number;
// Construct.
constructor();
// Set anchor.
setAnchor(anchor: Vector2): void;
// Set axis.
setAxis(axis: Vector2): void;
// Set enable motor.
setEnableMotor(enableMotor: boolean): void;
// Set max motor torque.
setMaxMotorTorque(maxMotorTorque: number): void;
// Set motor speed.
setMotorSpeed(motorSpeed: number): void;
// Set frequency Hz.
setFrequencyHz(frequencyHz: number): void;
// Set damping ratio.
setDampingRatio(dampingRatio: number): void;
// Return anchor.
getAnchor(): Vector2;
// Return axis.
getAxis(): Vector2;
// Return enable motor.
getEnableMotor(): boolean;
// Return maxMotor torque.
getMaxMotorTorque(): number;
// Return motor speed.
getMotorSpeed(): number;
// Return frequency Hz.
getFrequencyHz(): number;
// Return damping ratio.
getDampingRatio(): number;
}
export class Drawable2D extends Drawable {
layer: number;
orderInLayer: number;
// Construct.
constructor();
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Set layer.
setLayer(layer: number): void;
// Set order in layer.
setOrderInLayer(orderInLayer: number): void;
// Return layer.
getLayer(): number;
// Return order in layer.
getOrderInLayer(): number;
}
export class Light2D extends Component {
lightGroupID: number;
color: Color;
numRays: number;
lightType: LightType2D;
castShadows: boolean;
softShadows: boolean;
softShadowLength: number;
backtrace: boolean;
// Construct.
constructor();
setLightGroupID(id: number): void;
getLightGroupID(): number;
getColor(): Color;
setColor(color: Color): void;
updateVertices(): void;
setNumRays(numRays: number): void;
getNumRays(): number;
onSetEnabled(): void;
getLightType(): LightType2D;
getCastShadows(): boolean;
setCastShadows(castShadows: boolean): void;
getSoftShadows(): boolean;
setSoftShadows(softShadows: boolean): void;
getSoftShadowLength(): number;
setSoftShadowLength(softShadowLength: number): void;
getBacktrace(): boolean;
setBacktrace(backtrace: boolean): void;
}
export class DirectionalLight2D extends Light2D {
direction: number;
// Construct.
constructor();
updateVertices(): void;
getDirection(): number;
setDirection(direction: number): void;
}
export class PositionalLight2D extends Light2D {
// Construct.
constructor();
updateVertices(): void;
}
export class PointLight2D extends PositionalLight2D {
radius: number;
// Construct.
constructor();
updateVertices(): void;
setRadius(radius: number): void;
getRadius(): number;
}
export class Light2DGroup extends Drawable2D {
physicsWorld: PhysicsWorld2D;
ambientColor: Color;
lightGroupID: number;
frustumBox: BoundingBox;
// Construct.
constructor();
getPhysicsWorld(): PhysicsWorld2D;
addLight2D(light: Light2D): void;
removeLight2D(light: Light2D): void;
setDirty(): void;
setAmbientColor(color: Color): void;
getAmbientColor(): Color;
setLightGroupID(id: number): void;
getLightGroupID(): number;
getFrustumBox(): BoundingBox;
}
export class ParticleEffect2D extends Resource {
sprite: Sprite2D;
sourcePositionVariance: Vector2;
speed: number;
speedVariance: number;
particleLifeSpan: number;
particleLifespanVariance: number;
angle: number;
angleVariance: number;
gravity: Vector2;
radialAcceleration: number;
tangentialAcceleration: number;
radialAccelVariance: number;
tangentialAccelVariance: number;
startColor: Color;
startColorVariance: Color;
finishColor: Color;
finishColorVariance: Color;
maxParticles: number;
startParticleSize: number;
startParticleSizeVariance: number;
finishParticleSize: number;
finishParticleSizeVariance: number;
duration: number;
emitterType: EmitterType2D;
maxRadius: number;
maxRadiusVariance: number;
minRadius: number;
minRadiusVariance: number;
rotatePerSecond: number;
rotatePerSecondVariance: number;
blendMode: BlendMode;
rotationStart: number;
rotationStartVariance: number;
rotationEnd: number;
rotationEndVariance: number;
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Set sprite.
setSprite(sprite: Sprite2D): void;
// Set source position variance.
setSourcePositionVariance(sourcePositionVariance: Vector2): void;
// Set speed.
setSpeed(speed: number): void;
// Set speed variance.
setSpeedVariance(speedVariance: number): void;
// Set particle lifespan.
setParticleLifeSpan(particleLifeSpan: number): void;
// Set particle lifespan variance.
setParticleLifespanVariance(particleLifespanVariance: number): void;
// Set angle.
setAngle(angle: number): void;
// Set angle variance.
setAngleVariance(angleVariance: number): void;
// Set gravity.
setGravity(gravity: Vector2): void;
// Set radial acceleration.
setRadialAcceleration(radialAcceleration: number): void;
// Set tangential acceleration.
setTangentialAcceleration(tangentialAcceleration: number): void;
// Set radial acceleration variance.
setRadialAccelVariance(radialAccelVariance: number): void;
// Set tangential acceleration variance.
setTangentialAccelVariance(tangentialAccelVariance: number): void;
// Set start color.
setStartColor(startColor: Color): void;
// Set start color variance.
setStartColorVariance(startColorVariance: Color): void;
// Set finish color.
setFinishColor(finishColor: Color): void;
// Set finish color variance.
setFinishColorVariance(finishColorVariance: Color): void;
// Set max particles.
setMaxParticles(maxParticles: number): void;
// Set start particle size.
setStartParticleSize(startParticleSize: number): void;
// Set start particle size variance.
setStartParticleSizeVariance(startParticleSizeVariance: number): void;
// Set finish particle size.
setFinishParticleSize(finishParticleSize: number): void;
// Set finish particle size variance.
setFinishParticleSizeVariance(FinishParticleSizeVariance: number): void;
// Set duration.
setDuration(duration: number): void;
// Set emitter type.
setEmitterType(emitterType: EmitterType2D): void;
// Set max radius.
setMaxRadius(maxRadius: number): void;
// Set max radius variance.
setMaxRadiusVariance(maxRadiusVariance: number): void;
// Set min radius.
setMinRadius(minRadius: number): void;
// Set min radius variance.
setMinRadiusVariance(minRadiusVariance: number): void;
// Set rotate per second.
setRotatePerSecond(rotatePerSecond: number): void;
// Set rotate per second variance.
setRotatePerSecondVariance(rotatePerSecondVariance: number): void;
// Set blend mode.
setBlendMode(blendMode: BlendMode): void;
// Set rotation start.
setRotationStart(rotationStart: number): void;
// Set rotation start variance.
setRotationStartVariance(rotationStartVariance: number): void;
// Set rotation end.
setRotationEnd(rotationEnd: number): void;
// Set rotation end variance.
setRotationEndVariance(rotationEndVariance: number): void;
// Return sprite.
getSprite(): Sprite2D;
// Return source position variance.
getSourcePositionVariance(): Vector2;
// Return speed.
getSpeed(): number;
// Return speed variance.
getSpeedVariance(): number;
// Return particle lifespan.
getParticleLifeSpan(): number;
// Return particle lifespan variance.
getParticleLifespanVariance(): number;
// Return angle.
getAngle(): number;
// Return angle variance.
getAngleVariance(): number;
// Return gravity.
getGravity(): Vector2;
// Return radial acceleration.
getRadialAcceleration(): number;
// Return tangential acceleration.
getTangentialAcceleration(): number;
// Return radial acceleration variance.
getRadialAccelVariance(): number;
// Return tangential acceleration variance.
getTangentialAccelVariance(): number;
// Return start color.
getStartColor(): Color;
// Return start color variance.
getStartColorVariance(): Color;
// Return finish color.
getFinishColor(): Color;
// Return finish color variance.
getFinishColorVariance(): Color;
// Return max particles.
getMaxParticles(): number;
// Return start particle size.
getStartParticleSize(): number;
// Return start particle size variance.
getStartParticleSizeVariance(): number;
// Return finish particle size.
getFinishParticleSize(): number;
// Return finish particle size variance.
getFinishParticleSizeVariance(): number;
// Return duration.
getDuration(): number;
// Return emitter type.
getEmitterType(): EmitterType2D;
// Return max radius.
getMaxRadius(): number;
// Return max radius variance.
getMaxRadiusVariance(): number;
// Return min radius.
getMinRadius(): number;
// Return min radius variance.
getMinRadiusVariance(): number;
// Return rotate per second.
getRotatePerSecond(): number;
// Return rotate per second variance.
getRotatePerSecondVariance(): number;
// Return blend mode.
getBlendMode(): BlendMode;
// Return rotation start.
getRotationStart(): number;
// Return rotation start variance.
getRotationStartVariance(): number;
// Return rotation end.
getRotationEnd(): number;
// Return rotation end variance.
getRotationEndVariance(): number;
}
export class ParticleEmitter2D extends Drawable2D {
effect: ParticleEffect2D;
sprite: Sprite2D;
blendMode: BlendMode;
maxParticles: number;
// Construct.
constructor();
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Set particle effect.
setEffect(effect: ParticleEffect2D): void;
// Set sprite.
setSprite(sprite: Sprite2D): void;
// Set blend mode.
setBlendMode(blendMode: BlendMode): void;
// Set max particles.
setMaxParticles(maxParticles: number): void;
// Return particle effect.
getEffect(): ParticleEffect2D;
// Return sprite.
getSprite(): Sprite2D;
// Return blend mode.
getBlendMode(): BlendMode;
// Return max particles.
getMaxParticles(): number;
}
export class PhysicsWorld2D extends Component {
drawShape: boolean;
drawJoint: boolean;
drawAabb: boolean;
drawPair: boolean;
drawCenterOfMass: boolean;
allowSleeping: boolean;
warmStarting: boolean;
continuousPhysics: boolean;
subStepping: boolean;
gravity: Vector2;
autoClearForces: boolean;
velocityIterations: number;
positionIterations: number;
applyingTransforms: boolean;
// Construct.
constructor();
// Step the simulation forward.
update(timeStep: number): void;
// Add debug geometry to the debug renderer.
drawDebugGeometry(): void;
// Set draw shape.
setDrawShape(drawShape: boolean): void;
// Set draw joint.
setDrawJoint(drawJoint: boolean): void;
// Set draw aabb.
setDrawAabb(drawAabb: boolean): void;
// Set draw pair.
setDrawPair(drawPair: boolean): void;
// Set draw center of mass.
setDrawCenterOfMass(drawCenterOfMass: boolean): void;
// Set allow sleeping.
setAllowSleeping(enable: boolean): void;
// Set warm starting.
setWarmStarting(enable: boolean): void;
// Set continuous physics.
setContinuousPhysics(enable: boolean): void;
// Set sub stepping.
setSubStepping(enable: boolean): void;
// Set gravity.
setGravity(gravity: Vector2): void;
// Set auto clear forces.
setAutoClearForces(enable: boolean): void;
// Set velocity iterations.
setVelocityIterations(velocityIterations: number): void;
// Set position iterations.
setPositionIterations(positionIterations: number): void;
// Add rigid body.
addRigidBody(rigidBody: RigidBody2D): void;
// Remove rigid body.
removeRigidBody(rigidBody: RigidBody2D): void;
// Return draw shape.
getDrawShape(): boolean;
// Return draw joint.
getDrawJoint(): boolean;
// Return draw aabb.
getDrawAabb(): boolean;
// Return draw pair.
getDrawPair(): boolean;
// Return draw center of mass.
getDrawCenterOfMass(): boolean;
// Return allow sleeping.
getAllowSleeping(): boolean;
// Return warm starting.
getWarmStarting(): boolean;
// Return continuous physics.
getContinuousPhysics(): boolean;
// Return sub stepping.
getSubStepping(): boolean;
// Return auto clear forces.
getAutoClearForces(): boolean;
// Return gravity.
getGravity(): Vector2;
// Return velocity iterations.
getVelocityIterations(): number;
// Return position iterations.
getPositionIterations(): number;
// Set node dirtying to be disregarded.
setApplyingTransforms(enable: boolean): void;
// Return whether node dirtying should be disregarded.
isApplyingTransforms(): boolean;
}
export class RigidBody2D extends Component {
bodyType: BodyType2D;
mass: number;
inertia: number;
massCenter: Vector2;
useFixtureMass: boolean;
linearDamping: number;
angularDamping: number;
allowSleep: boolean;
fixedRotation: boolean;
bullet: boolean;
gravityScale: number;
awake: boolean;
linearVelocity: Vector2;
angularVelocity: number;
castShadows: boolean;
// Construct.
constructor();
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Set body type.
setBodyType(bodyType: BodyType2D): void;
// Set Mass.
setMass(mass: number): void;
// Set inertia.
setInertia(inertia: number): void;
// Set mass center.
setMassCenter(center: Vector2): void;
// Use fixture mass (default is true).
setUseFixtureMass(useFixtureMass: boolean): void;
// Set linear damping.
setLinearDamping(linearDamping: number): void;
// Set angular damping.
setAngularDamping(angularDamping: number): void;
// Set allow sleep.
setAllowSleep(allowSleep: boolean): void;
// Set fixed rotation.
setFixedRotation(fixedRotation: boolean): void;
// Set bullet.
setBullet(bullet: boolean): void;
// Set gravity scale.
setGravityScale(gravityScale: number): void;
// Set awake.
setAwake(awake: boolean): void;
// Set linear velocity.
setLinearVelocity(linearVelocity: Vector2): void;
// Set angular velocity.
setAngularVelocity(angularVelocity: number): void;
// Apply force.
applyForce(force: Vector2, point: Vector2, wake: boolean): void;
// Apply force to center.
applyForceToCenter(force: Vector2, wake: boolean): void;
// Apply Torque.
applyTorque(torque: number, wake: boolean): void;
// Apply linear impulse.
applyLinearImpulse(impulse: Vector2, point: Vector2, wake: boolean): void;
// Apply angular impulse.
applyAngularImpulse(impulse: number, wake: boolean): void;
// Create body.
createBody(): void;
// Release body.
releaseBody(): void;
// Apply world transform.
applyWorldTransform(): void;
// Add collision shape.
addCollisionShape2D(collisionShape: CollisionShape2D): void;
// Remove collision shape.
removeCollisionShape2D(collisionShape: CollisionShape2D): void;
// Add constraint.
addConstraint2D(constraint: Constraint2D): void;
// Remove constraint.
removeConstraint2D(constraint: Constraint2D): void;
// Return body type.
getBodyType(): BodyType2D;
// Return Mass.
getMass(): number;
// Return inertia.
getInertia(): number;
// Return mass center.
getMassCenter(): Vector2;
// Return use fixture mass.
getUseFixtureMass(): boolean;
// Return linear damping.
getLinearDamping(): number;
// Return angular damping.
getAngularDamping(): number;
// Return allow sleep.
isAllowSleep(): boolean;
// Return fixed rotation.
isFixedRotation(): boolean;
// Return bullet.
isBullet(): boolean;
// Return gravity scale.
getGravityScale(): number;
// Return awake.
isAwake(): boolean;
// Return linear velocity.
getLinearVelocity(): Vector2;
// Return angular velocity.
getAngularVelocity(): number;
getCastShadows(): boolean;
setCastShadows(castShadows: boolean): void;
}
export class Sprite2D extends Resource {
texture: Texture2D;
rectangle: IntRect;
hotSpot: Vector2;
offset: IntVector2;
spriteSheet: SpriteSheet2D;
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Set texture.
setTexture(texture: Texture2D): void;
// Set rectangle.
setRectangle(rectangle: IntRect): void;
// Set hot spot.
setHotSpot(hotSpot: Vector2): void;
// Set offset.
setOffset(offset: IntVector2): void;
// Set sprite sheet.
setSpriteSheet(spriteSheet: SpriteSheet2D): void;
// Return texture.
getTexture(): Texture2D;
// Return rectangle.
getRectangle(): IntRect;
// Return hot spot.
getHotSpot(): Vector2;
// Return offset.
getOffset(): IntVector2;
// Return sprite sheet.
getSpriteSheet(): SpriteSheet2D;
// Return texture rectangle.
getTextureRectangle(rect: Rect, flipX?: boolean, flipY?: boolean): boolean;
}
export class SpriteSheet2D extends Resource {
texture: Texture2D;
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Return texture.
getTexture(): Texture2D;
// Return sprite.
getSprite(name: string): Sprite2D;
// Define sprite.
defineSprite(name: string, rectangle: IntRect, hotSpot?: Vector2, offset?: IntVector2): void;
}
export class StaticSprite2D extends Drawable2D {
sprite: Sprite2D;
blendMode: BlendMode;
flipX: boolean;
flipY: boolean;
color: Color;
alpha: number;
useHotSpot: boolean;
hotSpot: Vector2;
customMaterial: Material;
// Construct.
constructor();
// Set sprite.
setSprite(sprite: Sprite2D): void;
// Set blend mode.
setBlendMode(blendMode: BlendMode): void;
// Set flip.
setFlip(flipX: boolean, flipY: boolean): void;
// Set flip X.
setFlipX(flipX: boolean): void;
// Set flip Y.
setFlipY(flipY: boolean): void;
// Set color.
setColor(color: Color): void;
// Set alpha.
setAlpha(alpha: number): void;
// Set use hot spot.
setUseHotSpot(useHotSpot: boolean): void;
// Set hot spot.
setHotSpot(hotspot: Vector2): void;
// Set custom material.
setCustomMaterial(customMaterial: Material): void;
// Return sprite.
getSprite(): Sprite2D;
// Return blend mode.
getBlendMode(): BlendMode;
// Return flip X.
getFlipX(): boolean;
// Return flip Y.
getFlipY(): boolean;
// Return color.
getColor(): Color;
// Return alpha.
getAlpha(): number;
// Return use hot spot.
getUseHotSpot(): boolean;
// Return hot spot.
getHotSpot(): Vector2;
// Return custom material.
getCustomMaterial(): Material;
}
export class TileMap2D extends Component {
tmxFile: TmxFile2D;
numLayers: number;
// Construct.
constructor();
// Set tmx file.
setTmxFile(tmxFile: TmxFile2D): void;
// Return tmx file.
getTmxFile(): TmxFile2D;
// Return number of layers.
getNumLayers(): number;
// Return tile map layer at index.
getLayer(index: number): TileMapLayer2D;
getLayerByName(name: string): TileMapLayer2D;
// Convert tile index to position.
tileIndexToPosition(x: number, y: number): Vector2;
}
export class PropertySet2D extends RefCounted {
constructor();
// Return has property.
hasProperty(name: string): boolean;
// Return property value.
getProperty(name: string): string;
}
export class Tile2D extends RefCounted {
gid: number;
sprite: Sprite2D;
objectGroup: TmxObjectGroup2D;
// Construct.
constructor();
// Return gid.
getGid(): number;
// Return sprite.
getSprite(): Sprite2D;
// Return Object Group.
getObjectGroup(): TmxObjectGroup2D;
// Return has property.
hasProperty(name: string): boolean;
// Return property.
getProperty(name: string): string;
}
export class TileMapObject2D extends RefCounted {
objectType: TileMapObjectType2D;
name: string;
type: string;
position: Vector2;
size: Vector2;
numPoints: number;
tileGid: number;
tileSprite: Sprite2D;
constructor();
// Return type.
getObjectType(): TileMapObjectType2D;
// Return name.
getName(): string;
// Return type.
getType(): string;
// Return position.
getPosition(): Vector2;
// Return size (for rectangle and ellipse).
getSize(): Vector2;
// Return number of points (use for script).
getNumPoints(): number;
// Return point at index (use for script).
getPoint(index: number): Vector2;
// Return tile Gid.
getTileGid(): number;
// Return tile sprite.
getTileSprite(): Sprite2D;
// Return has property.
hasProperty(name: string): boolean;
// Return property value.
getProperty(name: string): string;
validCollisionShape(): boolean;
createCollisionShape(node: Node): CollisionShape2D;
}
export class TileMapLayer2D extends Component {
drawOrder: number;
visible: boolean;
tileMap: TileMap2D;
tmxLayer: TmxLayer2D;
layerType: TileMapLayerType2D;
width: number;
height: number;
numObjects: number;
imageNode: Node;
name: string;
// Construct.
constructor();
// Add debug geometry to the debug renderer.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Initialize with tile map and tmx layer.
initialize(tileMap: TileMap2D, tmxLayer: TmxLayer2D): void;
// Set draw order
setDrawOrder(drawOrder: number): void;
// Set visible.
setVisible(visible: boolean): void;
// Return tile map.
getTileMap(): TileMap2D;
// Return tmx layer.
getTmxLayer(): TmxLayer2D;
// Return draw order.
getDrawOrder(): number;
// Return visible.
isVisible(): boolean;
// Return has property
hasProperty(name: string): boolean;
// Return property.
getProperty(name: string): string;
// Return layer type.
getLayerType(): TileMapLayerType2D;
// Return width (for tile layer only).
getWidth(): number;
// Return height (for tile layer only).
getHeight(): number;
// Return tile node (for tile layer only).
getTileNode(x: number, y: number): Node;
// Return tile (for tile layer only).
getTile(x: number, y: number): Tile2D;
// Return number of tile map objects (for object group only).
getNumObjects(): number;
// Return tile map object (for object group only).
getObject(index: number): TileMapObject2D;
// Return object node (for object group only).
getObjectNode(index: number): Node;
// Return image node (for image layer only).
getImageNode(): Node;
getName(): string;
}
export class TmxLayer2D extends RefCounted {
tmxFile: TmxFile2D;
type: TileMapLayerType2D;
name: string;
width: number;
height: number;
constructor(tmxFile: TmxFile2D, type: TileMapLayerType2D);
// Return tmx file.
getTmxFile(): TmxFile2D;
// Return type.
getType(): TileMapLayerType2D;
// Return name.
getName(): string;
// Return width.
getWidth(): number;
// Return height.
getHeight(): number;
// Return is visible.
isVisible(): boolean;
// Return has property (use for script).
hasProperty(name: string): boolean;
// Return property value (use for script).
getProperty(name: string): string;
}
export class TmxTileLayer2D extends TmxLayer2D {
constructor(tmxFile: TmxFile2D);
// Return tile.
getTile(x: number, y: number): Tile2D;
}
export class TmxObjectGroup2D extends TmxLayer2D {
numObjects: number;
constructor(tmxFile: TmxFile2D);
// Return number of objects.
getNumObjects(): number;
// Return tile map object at index.
getObject(index: number): TileMapObject2D;
}
export class TmxImageLayer2D extends TmxLayer2D {
position: Vector2;
source: string;
sprite: Sprite2D;
constructor(tmxFile: TmxFile2D);
// Return position.
getPosition(): Vector2;
// Return source.
getSource(): string;
// Return sprite.
getSprite(): Sprite2D;
}
export class TmxFile2D extends Resource {
numLayers: number;
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Return tile sprite by gid, if not exist return 0.
getTileSprite(gid: number): Sprite2D;
// Return tile property set by gid, if not exist return 0.
getTilePropertySet(gid: number): PropertySet2D;
// Return tile object group by gid, if not exist return 0.
getTileObjectGroup(gid: number): TmxObjectGroup2D;
// Return number of layers.
getNumLayers(): number;
// Return layer at index.
getLayer(index: number): TmxLayer2D;
}
//----------------------------------------------------
// MODULE: Audio
//----------------------------------------------------
export class Sound extends Resource {
size: number;
looped: boolean;
length: number;
dataSize: number;
sampleSize: number;
frequency: number;
intFrequency: number;
// Construct.
constructor();
// Set sound size in bytes. Also resets the sound to be uncompressed and one-shot.
setSize(dataSize: number): void;
// Set uncompressed sound data format.
setFormat(frequency: number, sixteenBit: boolean, stereo: boolean): void;
// Set loop on/off. If loop is enabled, sets the full sound as loop range.
setLooped(enable: boolean): void;
// Define loop.
setLoop(repeatOffset: number, endOffset: number): void;
// Return length in seconds.
getLength(): number;
// Return total sound data size.
getDataSize(): number;
// Return sample size.
getSampleSize(): number;
// Return default frequency as a float.
getFrequency(): number;
// Return default frequency as an integer.
getIntFrequency(): number;
// Return whether is looped.
isLooped(): boolean;
// Return whether data is sixteen bit.
isSixteenBit(): boolean;
// Return whether data is stereo.
isStereo(): boolean;
// Return whether is compressed.
isCompressed(): boolean;
// Fix interpolation by copying data from loop start to loop end (looped), or adding silence (oneshot.) Called internally, does not normally need to be called, unless the sound data is modified manually on the fly.
fixInterpolation(): void;
}
export class SoundSource extends Component {
soundType: string;
frequency: number;
gain: number;
attenuation: number;
panning: number;
autoRemove: boolean;
sound: Sound;
timePosition: number;
positionAttr: number;
playingAttr: boolean;
// Construct.
constructor();
// Play a sound.
play(sound: Sound): void;
// Stop playback.
stop(): void;
// Set sound type, determines the master gain group.
setSoundType(type: string): void;
// Set frequency.
setFrequency(frequency: number): void;
// Set gain. 0.0 is silence, 1.0 is full volume.
setGain(gain: number): void;
// Set attenuation. 1.0 is unaltered. Used for distance attenuated playback.
setAttenuation(attenuation: number): void;
// Set stereo panning. -1.0 is full left and 1.0 is full right.
setPanning(panning: number): void;
// Set whether sound source will be automatically removed from the scene node when playback stops.
setAutoRemove(enable: boolean): void;
// Return sound.
setSound(sound: Sound): void;
// Return sound.
getSound(): Sound;
// Return sound type, determines the master gain group.
getSoundType(): string;
// Return playback time position.
getTimePosition(): number;
// Return frequency.
getFrequency(): number;
// Return gain.
getGain(): number;
// Return attenuation.
getAttenuation(): number;
// Return stereo panning.
getPanning(): number;
// Return autoremove mode.
getAutoRemove(): boolean;
// Return whether is playing.
isPlaying(): boolean;
// Update the sound source. Perform subclass specific operations. Called by Audio.
update(timeStep: number): void;
// Update the effective master gain. Called internally and by Audio when the master gain changes.
updateMasterGain(): void;
// Set sound position attribute.
setPositionAttr(value: number): void;
// Set sound playing attribute
setPlayingAttr(value: boolean): void;
// Return sound position attribute.
getPositionAttr(): number;
}
//----------------------------------------------------
// MODULE: Physics
//----------------------------------------------------
export class CollisionShape extends Component {
terrain: number;
shapeType: ShapeType;
size: Vector3;
position: Vector3;
rotation: Quaternion;
margin: number;
model: Model;
lodLevel: number;
physicsWorld: PhysicsWorld;
worldBoundingBox: BoundingBox;
// Construct.
constructor();
// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
applyAttributes(): void;
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Visualize the component as debug geometry.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Set as a box.
setBox(size: Vector3, position?: Vector3, rotation?: Quaternion): void;
// Set as a sphere.
setSphere(diameter: number, position?: Vector3, rotation?: Quaternion): void;
// Set as a static plane.
setStaticPlane(position?: Vector3, rotation?: Quaternion): void;
// Set as a cylinder.
setCylinder(diameter: number, height: number, position?: Vector3, rotation?: Quaternion): void;
// Set as a capsule.
setCapsule(diameter: number, height: number, position?: Vector3, rotation?: Quaternion): void;
// Set as a cone.
setCone(diameter: number, height: number, position?: Vector3, rotation?: Quaternion): void;
// Set as a triangle mesh from Model. If you update a model's geometry and want to reapply the shape, call physicsWorld->RemoveCachedGeometry(model) first.
setTriangleMesh(model: Model, lodLevel?: number, scale?: Vector3, position?: Vector3, rotation?: Quaternion): void;
// Set as a triangle mesh from CustomGeometry.
setCustomTriangleMesh(custom: CustomGeometry, scale?: Vector3, position?: Vector3, rotation?: Quaternion): void;
// Set as a convex hull from Model.
setConvexHull(model: Model, lodLevel?: number, scale?: Vector3, position?: Vector3, rotation?: Quaternion): void;
// Set as a convex hull from CustomGeometry.
setCustomConvexHull(custom: CustomGeometry, scale?: Vector3, position?: Vector3, rotation?: Quaternion): void;
// Set as a terrain. Only works if the same scene node contains a Terrain component.
setTerrain(lodLevel?: number): void;
// Set shape type.
setShapeType(type: ShapeType): void;
// Set shape size.
setSize(size: Vector3): void;
// Set offset position.
setPosition(position: Vector3): void;
// Set offset rotation.
setRotation(rotation: Quaternion): void;
// Set offset transform.
setTransform(position: Vector3, rotation: Quaternion): void;
// Set collision margin.
setMargin(margin: number): void;
// Set triangle mesh / convex hull model.
setModel(model: Model): void;
// Set model LOD level.
setLodLevel(lodLevel: number): void;
// Return physics world.
getPhysicsWorld(): PhysicsWorld;
// Return shape type.
getShapeType(): ShapeType;
// Return shape size.
getSize(): Vector3;
// Return offset position.
getPosition(): Vector3;
// Return offset rotation.
getRotation(): Quaternion;
// Return collision margin.
getMargin(): number;
// Return triangle mesh / convex hull model.
getModel(): Model;
// Return model LOD level.
getLodLevel(): number;
// Return world-space bounding box.
getWorldBoundingBox(): BoundingBox;
// Update the new collision shape to the RigidBody.
notifyRigidBody(updateMass?: boolean): void;
// Release the collision shape.
releaseShape(): void;
}
export class Constraint extends Component {
constraintType: ConstraintType;
otherBody: RigidBody;
position: Vector3;
rotation: Quaternion;
axis: Vector3;
otherPosition: Vector3;
otherRotation: Quaternion;
otherAxis: Vector3;
worldPosition: Vector3;
highLimit: Vector2;
lowLimit: Vector2;
erp: number;
cfm: number;
disableCollision: boolean;
physicsWorld: PhysicsWorld;
ownBody: RigidBody;
// Construct.
constructor();
// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
applyAttributes(): void;
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Visualize the component as debug geometry.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Set constraint type and recreate the constraint.
setConstraintType(type: ConstraintType): void;
// Set other body to connect to. Set to null to connect to the static world.
setOtherBody(body: RigidBody): void;
// Set constraint position relative to own body.
setPosition(position: Vector3): void;
// Set constraint rotation relative to own body.
setRotation(rotation: Quaternion): void;
// Set constraint rotation relative to own body by specifying the axis.
setAxis(axis: Vector3): void;
// Set constraint position relative to the other body. If connected to the static world, is a world space position.
setOtherPosition(position: Vector3): void;
// Set constraint rotation relative to the other body. If connected to the static world, is a world space rotation.
setOtherRotation(rotation: Quaternion): void;
// Set constraint rotation relative to the other body by specifying the axis.
setOtherAxis(axis: Vector3): void;
// Set constraint world space position. Resets both own and other body relative position, ie. zeroes the constraint error.
setWorldPosition(position: Vector3): void;
// Set high limit. Interpretation is constraint type specific.
setHighLimit(limit: Vector2): void;
// Set low limit. Interpretation is constraint type specific.
setLowLimit(limit: Vector2): void;
// Set constraint error reduction parameter. Zero = leave to default.
setERP(erp: number): void;
// Set constraint force mixing parameter. Zero = leave to default.
setCFM(cfm: number): void;
// Set whether to disable collisions between connected bodies.
setDisableCollision(disable: boolean): void;
// Return physics world.
getPhysicsWorld(): PhysicsWorld;
// Return constraint type.
getConstraintType(): ConstraintType;
// Return rigid body in own scene node.
getOwnBody(): RigidBody;
// Return the other rigid body. May be null if connected to the static world.
getOtherBody(): RigidBody;
// Return constraint position relative to own body.
getPosition(): Vector3;
// Return constraint rotation relative to own body.
getRotation(): Quaternion;
// Return constraint position relative to other body.
getOtherPosition(): Vector3;
// Return constraint rotation relative to other body.
getOtherRotation(): Quaternion;
// Return constraint world position, calculated from own body.
getWorldPosition(): Vector3;
// Return high limit.
getHighLimit(): Vector2;
// Return low limit.
getLowLimit(): Vector2;
// Return constraint error reduction parameter.
getERP(): number;
// Return constraint force mixing parameter.
getCFM(): number;
// Return whether collisions between connected bodies are disabled.
getDisableCollision(): boolean;
// Release the constraint.
releaseConstraint(): void;
// Apply constraint frames.
applyFrames(): void;
}
export class PhysicsWorld extends Component {
fps: number;
gravity: Vector3;
maxSubSteps: number;
numIterations: number;
interpolation: boolean;
internalEdge: boolean;
splitImpulse: boolean;
maxNetworkAngularVelocity: number;
debugRenderer: DebugRenderer;
debugDepthTest: boolean;
applyingTransforms: boolean;
// Construct.
constructor();
// Set debug draw flags.
setDebugMode(debugMode: number): void;
// Return debug draw flags.
getDebugMode(): number;
// Step the simulation forward.
update(timeStep: number): void;
// Refresh collisions only without updating dynamics.
updateCollisions(): void;
// Set simulation substeps per second.
setFps(fps: number): void;
// Set gravity.
setGravity(gravity: Vector3): void;
// Set maximum number of physics substeps per frame. 0 (default) is unlimited. Positive values cap the amount. Use a negative value to enable an adaptive timestep. This may cause inconsistent physics behavior.
setMaxSubSteps(num: number): void;
// Set number of constraint solver iterations.
setNumIterations(num: number): void;
// Set whether to interpolate between simulation steps.
setInterpolation(enable: boolean): void;
// Set whether to use Bullet's internal edge utility for trimesh collisions. Disabled by default.
setInternalEdge(enable: boolean): void;
// Set split impulse collision mode. This is more accurate, but slower. Disabled by default.
setSplitImpulse(enable: boolean): void;
// Set maximum angular velocity for network replication.
setMaxNetworkAngularVelocity(velocity: number): void;
// Invalidate cached collision geometry for a model.
removeCachedGeometry(model: Model): void;
// Return gravity.
getGravity(): Vector3;
// Return maximum number of physics substeps per frame.
getMaxSubSteps(): number;
// Return number of constraint solver iterations.
getNumIterations(): number;
// Return whether interpolation between simulation steps is enabled.
getInterpolation(): boolean;
// Return whether Bullet's internal edge utility for trimesh collisions is enabled.
getInternalEdge(): boolean;
// Return whether split impulse collision mode is enabled.
getSplitImpulse(): boolean;
// Return simulation steps per second.
getFps(): number;
// Return maximum angular velocity for network replication.
getMaxNetworkAngularVelocity(): number;
// Add a rigid body to keep track of. Called by RigidBody.
addRigidBody(body: RigidBody): void;
// Remove a rigid body. Called by RigidBody.
removeRigidBody(body: RigidBody): void;
// Add a collision shape to keep track of. Called by CollisionShape.
addCollisionShape(shape: CollisionShape): void;
// Remove a collision shape. Called by CollisionShape.
removeCollisionShape(shape: CollisionShape): void;
// Add a constraint to keep track of. Called by Constraint.
addConstraint(joint: Constraint): void;
// Remove a constraint. Called by Constraint.
removeConstraint(joint: Constraint): void;
// Set debug renderer to use. Called both by PhysicsWorld itself and physics components.
setDebugRenderer(debug: DebugRenderer): void;
// Set debug geometry depth test mode. Called both by PhysicsWorld itself and physics components.
setDebugDepthTest(enable: boolean): void;
// Clean up the geometry cache.
cleanupGeometryCache(): void;
// Set node dirtying to be disregarded.
setApplyingTransforms(enable: boolean): void;
// Return whether node dirtying should be disregarded.
isApplyingTransforms(): boolean;
}
export class RigidBody extends Component {
mass: number;
position: Vector3;
rotation: Quaternion;
linearVelocity: Vector3;
linearFactor: Vector3;
linearRestThreshold: number;
linearDamping: number;
angularVelocity: Vector3;
angularFactor: Vector3;
angularRestThreshold: number;
angularDamping: number;
friction: number;
anisotropicFriction: Vector3;
rollingFriction: number;
restitution: number;
contactProcessingThreshold: number;
ccdRadius: number;
ccdMotionThreshold: number;
useGravity: boolean;
gravityOverride: Vector3;
kinematic: boolean;
trigger: boolean;
collisionLayer: number;
collisionMask: number;
collisionEventMode: CollisionEventMode;
physicsWorld: PhysicsWorld;
centerOfMass: Vector3;
// Construct.
constructor();
// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
applyAttributes(): void;
// Handle enabled/disabled state change.
onSetEnabled(): void;
// Visualize the component as debug geometry.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Set mass. Zero mass makes the body static.
setMass(mass: number): void;
// Set rigid body position in world space.
setPosition(position: Vector3): void;
// Set rigid body rotation in world space.
setRotation(rotation: Quaternion): void;
// Set rigid body position and rotation in world space as an atomic operation.
setTransform(position: Vector3, rotation: Quaternion): void;
// Set linear velocity.
setLinearVelocity(velocity: Vector3): void;
// Set linear degrees of freedom. Use 1 to enable an axis or 0 to disable. Default is all axes enabled (1, 1, 1).
setLinearFactor(factor: Vector3): void;
// Set linear velocity deactivation threshold.
setLinearRestThreshold(threshold: number): void;
// Set linear velocity damping factor.
setLinearDamping(damping: number): void;
// Set angular velocity.
setAngularVelocity(angularVelocity: Vector3): void;
// Set angular degrees of freedom. Use 1 to enable an axis or 0 to disable. Default is all axes enabled (1, 1, 1).
setAngularFactor(factor: Vector3): void;
// Set angular velocity deactivation threshold.
setAngularRestThreshold(threshold: number): void;
// Set angular velocity damping factor.
setAngularDamping(factor: number): void;
// Set friction coefficient.
setFriction(friction: number): void;
// Set anisotropic friction.
setAnisotropicFriction(friction: Vector3): void;
// Set rolling friction coefficient.
setRollingFriction(friction: number): void;
// Set restitution coefficient.
setRestitution(restitution: number): void;
// Set contact processing threshold.
setContactProcessingThreshold(threshold: number): void;
// Set continuous collision detection swept sphere radius.
setCcdRadius(radius: number): void;
// Set continuous collision detection motion-per-simulation-step threshold. 0 disables, which is the default.
setCcdMotionThreshold(threshold: number): void;
// Set whether gravity is applied to rigid body.
setUseGravity(enable: boolean): void;
// Set gravity override. If zero, uses physics world's gravity.
setGravityOverride(gravity: Vector3): void;
// Set rigid body kinematic mode. In kinematic mode forces are not applied to the rigid body.
setKinematic(enable: boolean): void;
// Set rigid body trigger mode. In trigger mode collisions are reported but do not apply forces.
setTrigger(enable: boolean): void;
// Set collision layer.
setCollisionLayer(layer: number): void;
// Set collision mask.
setCollisionMask(mask: number): void;
// Set collision group and mask.
setCollisionLayerAndMask(layer: number, mask: number): void;
// Set collision event signaling mode. Default is to signal when rigid bodies are active.
setCollisionEventMode(mode: CollisionEventMode): void;
// Apply torque.
applyTorque(torque: Vector3): void;
// Apply impulse to center of mass.
applyImpulse(impulse: Vector3): void;
// Apply torque impulse.
applyTorqueImpulse(torque: Vector3): void;
// Reset accumulated forces.
resetForces(): void;
// Activate rigid body if it was resting.
activate(): void;
// Readd rigid body to the physics world to clean up internal state like stale contacts.
reAddBodyToWorld(): void;
// Disable mass update. Call this to optimize performance when adding or editing multiple collision shapes in the same node.
disableMassUpdate(): void;
// Re-enable mass update and recalculate the mass/inertia by calling UpdateMass(). Call when collision shape changes are finished.
enableMassUpdate(): void;
// Return physics world.
getPhysicsWorld(): PhysicsWorld;
// Return mass.
getMass(): number;
// Return rigid body position in world space.
getPosition(): Vector3;
// Return rigid body rotation in world space.
getRotation(): Quaternion;
// Return linear velocity.
getLinearVelocity(): Vector3;
// Return linear degrees of freedom.
getLinearFactor(): Vector3;
// Return linear velocity at local point.
getVelocityAtPoint(position: Vector3): Vector3;
// Return linear velocity deactivation threshold.
getLinearRestThreshold(): number;
// Return linear velocity damping factor.
getLinearDamping(): number;
// Return angular velocity.
getAngularVelocity(): Vector3;
// Return angular degrees of freedom.
getAngularFactor(): Vector3;
// Return angular velocity deactivation threshold.
getAngularRestThreshold(): number;
// Return angular velocity damping factor.
getAngularDamping(): number;
// Return friction coefficient.
getFriction(): number;
// Return anisotropic friction.
getAnisotropicFriction(): Vector3;
// Return rolling friction coefficient.
getRollingFriction(): number;
// Return restitution coefficient.
getRestitution(): number;
// Return contact processing threshold.
getContactProcessingThreshold(): number;
// Return continuous collision detection swept sphere radius.
getCcdRadius(): number;
// Return continuous collision detection motion-per-simulation-step threshold.
getCcdMotionThreshold(): number;
// Return whether rigid body uses gravity.
getUseGravity(): boolean;
// Return gravity override. If zero (default), uses the physics world's gravity.
getGravityOverride(): Vector3;
// Return center of mass offset.
getCenterOfMass(): Vector3;
// Return kinematic mode flag.
isKinematic(): boolean;
// Return whether this RigidBody is acting as a trigger.
isTrigger(): boolean;
// Return whether rigid body is active (not sleeping.)
isActive(): boolean;
// Return collision layer.
getCollisionLayer(): number;
// Return collision mask.
getCollisionMask(): number;
// Return collision event signaling mode.
getCollisionEventMode(): CollisionEventMode;
// Apply new world transform after a simulation step. Called internally.
applyWorldTransform(newWorldPosition: Vector3, newWorldRotation: Quaternion): void;
// Update mass and inertia to the Bullet rigid body.
updateMass(): void;
// Update gravity parameters to the Bullet rigid body.
updateGravity(): void;
// Add a constraint that refers to this rigid body.
addConstraint(constraint: Constraint): void;
// Remove a constraint that refers to this rigid body.
removeConstraint(constraint: Constraint): void;
// Remove the rigid body.
releaseBody(): void;
}
//----------------------------------------------------
// MODULE: Navigation
//----------------------------------------------------
export class Navigable extends Component {
recursive: boolean;
// Construct.
constructor();
// Set whether geometry is automatically collected from child nodes. Default true.
setRecursive(enable: boolean): void;
// Return whether geometry is automatically collected from child nodes.
isRecursive(): boolean;
}
export class NavigationMesh extends Component {
tileSize: number;
cellSize: number;
cellHeight: number;
agentHeight: number;
agentRadius: number;
agentMaxClimb: number;
agentMaxSlope: number;
regionMinSize: number;
regionMergeSize: number;
edgeMaxLength: number;
edgeMaxError: number;
detailSampleDistance: number;
detailSampleMaxError: number;
padding: Vector3;
randomPoint: Vector3;
meshName: string;
boundingBox: BoundingBox;
worldBoundingBox: BoundingBox;
numTiles: IntVector2;
partitionType: NavmeshPartitionType;
drawOffMeshConnections: boolean;
drawNavAreas: boolean;
// Construct.
constructor();
// Set tile size.
setTileSize(size: number): void;
// Set cell size.
setCellSize(size: number): void;
// Set cell height.
setCellHeight(height: number): void;
// Set navigation agent height.
setAgentHeight(height: number): void;
// Set navigation agent radius.
setAgentRadius(radius: number): void;
// Set navigation agent max vertical climb.
setAgentMaxClimb(maxClimb: number): void;
// Set navigation agent max slope.
setAgentMaxSlope(maxSlope: number): void;
// Set region minimum size.
setRegionMinSize(size: number): void;
// Set region merge size.
setRegionMergeSize(size: number): void;
// Set edge max length.
setEdgeMaxLength(length: number): void;
// Set edge max error.
setEdgeMaxError(error: number): void;
// Set detail sampling distance.
setDetailSampleDistance(distance: number): void;
// Set detail sampling maximum error.
setDetailSampleMaxError(error: number): void;
// Set padding of the navigation mesh bounding box. Having enough padding allows to add geometry on the extremities of the navigation mesh when doing partial rebuilds.
setPadding(padding: Vector3): void;
// Set the cost of an area.
setAreaCost(areaID: number, cost: number): void;
// Find the nearest point on the navigation mesh to a given point. Extens specifies how far out from the specified point to check along each axis.
findNearestPoint(point: Vector3, extents?: Vector3): Vector3;
// Try to move along the surface from one point to another.
moveAlongSurface(start: Vector3, end: Vector3, extents?: Vector3, maxVisited?: number): Vector3;
// Return a random point on the navigation mesh.
getRandomPoint(): Vector3;
// Return a random point on the navigation mesh within a circle. The circle radius is only a guideline and in practice the returned point may be further away.
getRandomPointInCircle(center: Vector3, radius: number, extents?: Vector3): Vector3;
// Return distance to wall from a point. Maximum search radius must be specified.
getDistanceToWall(point: Vector3, radius: number, extents?: Vector3): number;
// Perform a walkability raycast on the navigation mesh between start and end and return the point where a wall was hit, or the end point if no walls.
raycast(start: Vector3, end: Vector3, extents?: Vector3): Vector3;
// Return the given name of this navigation mesh.
getMeshName(): string;
// Set the name of this navigation mesh.
setMeshName(newName: string): void;
// Return tile size.
getTileSize(): number;
// Return cell size.
getCellSize(): number;
// Return cell height.
getCellHeight(): number;
// Return navigation agent height.
getAgentHeight(): number;
// Return navigation agent radius.
getAgentRadius(): number;
// Return navigation agent max vertical climb.
getAgentMaxClimb(): number;
// Return navigation agent max slope.
getAgentMaxSlope(): number;
// Return region minimum size.
getRegionMinSize(): number;
// Return region merge size.
getRegionMergeSize(): number;
// Return edge max length.
getEdgeMaxLength(): number;
// Return edge max error.
getEdgeMaxError(): number;
// Return detail sampling distance.
getDetailSampleDistance(): number;
// Return detail sampling maximum error.
getDetailSampleMaxError(): number;
// Return navigation mesh bounding box padding.
getPadding(): Vector3;
// Get the current cost of an area
getAreaCost(areaID: number): number;
// Return whether has been initialized with valid navigation data.
isInitialized(): boolean;
// Return local space bounding box of the navigation mesh.
getBoundingBox(): BoundingBox;
// Return world space bounding box of the navigation mesh.
getWorldBoundingBox(): BoundingBox;
// Return number of tiles.
getNumTiles(): IntVector2;
// Set the partition type used for polygon generation.
setPartitionType(aType: NavmeshPartitionType): void;
// Return Partition Type.
getPartitionType(): NavmeshPartitionType;
// Draw debug geometry for OffMeshConnection components.
setDrawOffMeshConnections(enable: boolean): void;
// Return whether to draw OffMeshConnection components.
getDrawOffMeshConnections(): boolean;
// Draw debug geometry for NavArea components.
setDrawNavAreas(enable: boolean): void;
// Return whether to draw NavArea components.
getDrawNavAreas(): boolean;
}
export class OffMeshConnection extends Component {
endPoint: Node;
radius: number;
bidirectional: boolean;
mask: number;
areaID: number;
// Construct.
constructor();
// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
applyAttributes(): void;
// Visualize the component as debug geometry.
drawDebugGeometry(debug: DebugRenderer, depthTest: boolean): void;
// Set endpoint node.
setEndPoint(node: Node): void;
// Set radius.
setRadius(radius: number): void;
// Set bidirectional flag. Default true.
setBidirectional(enabled: boolean): void;
// Set a user assigned mask
setMask(newMask: number): void;
// Sets the assigned area Id for the connection
setAreaID(newAreaID: number): void;
// Return endpoint node.
getEndPoint(): Node;
// Return radius.
getRadius(): number;
// Return whether is bidirectional.
isBidirectional(): boolean;
// Return the user assigned mask
getMask(): number;
// Return the user assigned area ID
getAreaID(): number;
}
//----------------------------------------------------
// MODULE: Input
//----------------------------------------------------
export class Input extends AObject {
toggleFullscreen: boolean;
mouseGrabbed: boolean;
mouseMode: MouseMode;
screenKeyboardVisible: boolean;
touchEmulation: boolean;
qualifiers: number;
mousePosition: IntVector2;
mouseMove: IntVector2;
mouseMoveX: number;
mouseMoveY: number;
mouseMoveWheel: number;
numTouches: number;
numJoysticks: number;
screenKeyboardSupport: boolean;
// Construct.
constructor();
// Poll for window messages. Called by HandleBeginFrame().
update(): void;
// Set whether ALT-ENTER fullscreen toggle is enabled.
setToggleFullscreen(enable: boolean): void;
// Set whether the operating system mouse cursor is visible. When not visible (default), is kept centered to prevent leaving the window. Mouse visibility event can be suppressed-- this also recalls any unsuppressed SetMouseVisible which can be returned by ResetMouseVisible().
setMouseVisible(enable: boolean, suppressEvent?: boolean): void;
// Reset last mouse visibility that was not suppressed in SetMouseVisible.
resetMouseVisible(): void;
// Set whether the mouse is currently being grabbed by an operation.
setMouseGrabbed(grab: boolean): void;
setMouseMode(mode: MouseMode): void;
// Show or hide on-screen keyboard on platforms that support it. When shown, keypresses from it are delivered as key events.
setScreenKeyboardVisible(enable: boolean): void;
// Set touch emulation by mouse. Only available on desktop platforms. When enabled, actual mouse events are no longer sent and the mouse cursor is forced visible.
setTouchEmulation(enable: boolean): void;
// Begin recording a touch gesture. Return true if successful. The E_GESTURERECORDED event (which contains the ID for the new gesture) will be sent when recording finishes.
recordGesture(): boolean;
// Remove an in-memory gesture by ID. Return true if was found.
removeGesture(gestureID: number): boolean;
// Remove all in-memory gestures.
removeAllGestures(): void;
// Return keycode from key name.
getKeyFromName(name: string): number;
// Return keycode from scancode.
getKeyFromScancode(scancode: number): number;
// Return name of key from keycode.
getKeyName(key: number): string;
// Return scancode from keycode.
getScancodeFromKey(key: number): number;
// Return scancode from key name.
getScancodeFromName(name: string): number;
// Return name of key from scancode.
getScancodeName(scancode: number): string;
// Check if a key is held down.
getKeyDown(key: number): boolean;
// Check if a key has been pressed on this frame.
getKeyPress(key: number): boolean;
// Check if a key is held down by scancode.
getScancodeDown(scancode: number): boolean;
// Check if a key has been pressed on this frame by scancode.
getScancodePress(scancode: number): boolean;
// Check if a mouse button is held down.
getMouseButtonDown(button: number): boolean;
// Check if a mouse button has been pressed on this frame.
getMouseButtonPress(button: number): boolean;
// Check if a qualifier key is held down.
getQualifierDown(qualifier: number): boolean;
// Check if a qualifier key has been pressed on this frame.
getQualifierPress(qualifier: number): boolean;
// Return the currently held down qualifiers.
getQualifiers(): number;
// Return mouse position within window. Should only be used with a visible mouse cursor.
getMousePosition(): IntVector2;
// Return mouse movement since last frame.
getMouseMove(): IntVector2;
// Return horizontal mouse movement since last frame.
getMouseMoveX(): number;
// Return vertical mouse movement since last frame.
getMouseMoveY(): number;
// Return mouse wheel movement since last frame.
getMouseMoveWheel(): number;
// Return number of active finger touches.
getNumTouches(): number;
// Return number of connected joysticks.
getNumJoysticks(): number;
// Return whether fullscreen toggle is enabled.
getToggleFullscreen(): boolean;
// Return whether on-screen keyboard is supported.
getScreenKeyboardSupport(): boolean;
// Return whether on-screen keyboard is being shown.
isScreenKeyboardVisible(): boolean;
// Return whether touch emulation is enabled.
getTouchEmulation(): boolean;
// Return whether the operating system mouse cursor is visible.
isMouseVisible(): boolean;
// Return whether the mouse is currently being grabbed by an operation.
isMouseGrabbed(): boolean;
// Return the mouse mode.
getMouseMode(): MouseMode;
// Return whether application window has input focus.
hasFocus(): boolean;
// Return whether application window is minimized.
isMinimized(): boolean;
}
//----------------------------------------------------
// MODULE: UI
//----------------------------------------------------
export class UI extends AObject {
keyboardDisabled: boolean;
inputDisabled: boolean;
skinLoaded: boolean;
// Construct.
constructor();
setKeyboardDisabled(disabled: boolean): void;
setInputDisabled(disabled: boolean): void;
render(resetRenderTargets?: boolean): void;
initialize(languageFile: string): void;
shutdown(): void;
loadSkin(skin: string, overrideSkin?: string): void;
getSkinLoaded(): boolean;
loadDefaultPlayerSkin(): void;
addFont(fontFile: string, name: string): void;
setDefaultFont(name: string, size: number): void;
debugGetWrappedWidgetCount(): number;
pruneUnreachableWidgets(): void;
}
export class UIButton extends UIWidget {
squeezable: boolean;
constructor(createWidget?: boolean);
setSqueezable(value: boolean): void;
onClick: () => void;
}
export class UICheckBox extends UIWidget {
constructor(createWidget?: boolean);
}
export class UIClickLabel extends UIWidget {
constructor(createWidget?: boolean);
}
export class UIContainer extends UIWidget {
constructor(createWidget?: boolean);
}
export class UIDimmer extends UIWidget {
constructor(createWidget?: boolean);
}
export class UIDragObject extends AObject {
text: string;
icon: string;
object: AObject;
filenames: string[];
// Construct.
constructor(object?: AObject, text?: string, icon?: string);
getText(): string;
getIcon(): string;
getObject(): AObject;
getFilenames(): string[];
setText(text: string): void;
setIcon(icon: string): void;
setObject(object: AObject): void;
addFilename(filename: string): void;
}
export class UIEditField extends UIWidget {
textAlign: TEXT_ALIGN;
editType: UI_EDIT_TYPE;
readOnly: boolean;
wrapping: boolean;
constructor(createWidget?: boolean);
appendText(text: string): void;
setTextAlign(align: TEXT_ALIGN): void;
setEditType(type: UI_EDIT_TYPE): void;
setReadOnly(readonly: boolean): void;
scrollTo(x: number, y: number): void;
setWrapping(wrap: boolean): void;
getWrapping(): boolean;
}
export class UIFontDescription extends AObject {
id: string;
size: number;
constructor();
setId(id: string): void;
setSize(size: number): void;
}
export class UIImageWidget extends UIWidget {
image: string;
constructor(createWidget?: boolean);
setImage(imagePath: string): void;
}
export class UIInlineSelect extends UIWidget {
editFieldLayoutParams: UILayoutParams;
constructor(createWidget?: boolean);
setLimits(minimum: number, maximum: number): void;
setEditFieldLayoutParams(params: UILayoutParams): void;
}
export class UILayoutParams extends AObject {
width: number;
height: number;
minWidth: number;
minHeight: number;
maxWidth: number;
maxHeight: number;
constructor();
setWidth(width: number): void;
setHeight(height: number): void;
setMinWidth(width: number): void;
setMinHeight(height: number): void;
setMaxWidth(width: number): void;
setMaxHeight(height: number): void;
}
export class UILayout extends UIWidget {
spacing: number;
axis: UI_AXIS;
layoutSize: UI_LAYOUT_SIZE;
layoutPosition: UI_LAYOUT_POSITION;
layoutDistribution: UI_LAYOUT_DISTRIBUTION;
layoutDistributionPosition: UI_LAYOUT_DISTRIBUTION_POSITION;
constructor(axis?: UI_AXIS, createWidget?: boolean);
setSpacing(spacing: number): void;
setAxis(axis: UI_AXIS): void;
setLayoutSize(size: UI_LAYOUT_SIZE): void;
setLayoutPosition(position: UI_LAYOUT_POSITION): void;
setLayoutDistribution(distribution: UI_LAYOUT_DISTRIBUTION): void;
setLayoutDistributionPosition(distribution_pos: UI_LAYOUT_DISTRIBUTION_POSITION): void;
}
export class UIListView extends UIWidget {
hoverItemID: string;
selectedItemID: string;
rootList: UISelectList;
// Construct.
constructor(createWidget?: boolean);
addRootItem(text: string, icon: string, id: string): number;
addChildItem(parentItemID: number, text: string, icon: string, id: string): number;
setItemText(id: string, text: string): void;
setItemTextSkin(id: string, skin: string): void;
setItemIcon(id: string, icon: string): void;
deleteItemByID(id: string): void;
setExpanded(itemID: number, value: boolean): void;
deleteAllItems(): void;
selectItemByID(id: string): void;
getHoverItemID(): string;
getSelectedItemID(): string;
getRootList(): UISelectList;
}
export class UIMenuItem extends UISelectItem {
constructor(str?: string, id?: string, shortcut?: string, skinBg?: string);
}
export class UIMenuItemSource extends UISelectItemSource {
constructor();
}
export class UIMenuWindow extends UIWidget {
constructor(target: UIWidget, id: string);
show(source: UISelectItemSource, x?: number, y?: number): void;
close(): void;
}
export class UIMessageWindow extends UIWindow {
constructor(target: UIWidget, id: string, createWidget?: boolean);
show(title: string, message: string, settings: UI_MESSAGEWINDOW_SETTINGS, dimmer: boolean, width: number, height: number): void;
}
export class UIPreferredSize extends RefCounted {
minWidth: number;
minHeight: number;
maxWidth: number;
maxHeight: number;
prefWidth: number;
prefHeight: number;
sizeDep: UI_SIZE_DEP;
constructor(w?: number, h?: number);
getMinWidth(): number;
getMinHeight(): number;
getMaxWidth(): number;
getMaxHeight(): number;
getPrefWidth(): number;
getPrefHeight(): number;
getSizeDep(): UI_SIZE_DEP;
setMinWidth(w: number): void;
setMinHeight(h: number): void;
setMaxWidth(w: number): void;
setMaxHeight(h: number): void;
setPrefWidth(w: number): void;
setPrefHeight(h: number): void;
setSizeDep(dep: UI_SIZE_DEP): void;
}
export class UISceneView extends UIWidget {
format: number;
autoUpdate: boolean;
scene: Scene;
cameraNode: Node;
renderTexture: Texture2D;
depthTexture: Texture2D;
viewport: Viewport;
size: IntVector2;
constructor(createWidget?: boolean);
// React to resize.
onResize(newSize: IntVector2): void;
// Define the scene and camera to use in rendering. When ownScene is true the View3D will take ownership of them with shared pointers.
setView(scene: Scene, camera: Camera): void;
// Set render texture pixel format. Default is RGB.
setFormat(format: number): void;
// Set render target auto update mode. Default is true.
setAutoUpdate(enable: boolean): void;
// Queue manual update on the render texture.
queueUpdate(): void;
// Return render texture pixel format.
getFormat(): number;
// Return whether render target updates automatically.
getAutoUpdate(): boolean;
// Return scene.
getScene(): Scene;
// Return camera scene node.
getCameraNode(): Node;
// Return render texture.
getRenderTexture(): Texture2D;
// Return depth stencil texture.
getDepthTexture(): Texture2D;
// Return viewport.
getViewport(): Viewport;
setResizeRequired(): void;
getSize(): IntVector2;
}
export class UIScrollContainer extends UIWidget {
scrollMode: UI_SCROLL_MODE;
adaptToContentSize: boolean;
adaptContentSize: boolean;
constructor(createWidget?: boolean);
setScrollMode(mode: UI_SCROLL_MODE): void;
getScrollMode(): UI_SCROLL_MODE;
// Set to true if the preferred size of this container should adapt to the preferred size of the content. This is disabled by default.
setAdaptToContentSize(adapt: boolean): void;
getAdaptToContentSize(): boolean;
// Set to true if the content should adapt to the available size of this container when it's larger than the preferred size.
setAdaptContentSize(adapt: boolean): void;
getAdaptContentSize(): boolean;
}
export class UISection extends UIWidget {
constructor(createWidget?: boolean);
}
export class UISelectItem extends AObject {
string: string;
id: string;
skinImage: string;
subSource: UISelectItemSource;
constructor(str?: string, id?: string, skinImage?: string);
setString(str: string): void;
setID(id: string): void;
setSkinImage(skinImage: string): void;
setSubSource(subSource: UISelectItemSource): void;
}
export class UISelectItemSource extends AObject {
constructor();
addItem(item: UISelectItem): void;
clear(): void;
}
export class UISelectList extends UIWidget {
filter: string;
source: UISelectItemSource;
value: number;
hoverItemID: string;
selectedItemID: string;
constructor(createWidget?: boolean);
setFilter(filter: string): void;
setSource(source: UISelectItemSource): void;
invalidateList(): void;
setValue(value: number): void;
getValue(): number;
getHoverItemID(): string;
getSelectedItemID(): string;
}
export class UISeparator extends UIWidget {
constructor(createWidget?: boolean);
}
export class UISkinImage extends UIWidget {
constructor(bitmapID: string, createWidget?: boolean);
}
export class UITabContainer extends UIWidget {
numPages: number;
currentPage: number;
currentPageWidget: UIWidget;
constructor(createWidget?: boolean);
getNumPages(): number;
setCurrentPage(page: number): void;
getCurrentPageWidget(): UIWidget;
}
export class UITextField extends UIWidget {
textAlign: UI_TEXT_ALIGN;
constructor(createWidget?: boolean);
setTextAlign(align: UI_TEXT_ALIGN): void;
}
export class UITextureWidget extends UIWidget {
texture: Texture;
constructor(createWidget?: boolean);
setTexture(texture: Texture): void;
getTexture(): Texture;
}
export class UIView extends UIWidget {
constructor();
}
export class UIWidget extends AObject {
id: string;
parent: UIWidget;
contentRoot: UIWidget;
rect: IntRect;
preferredSize: UIPreferredSize;
text: string;
skinBg: string;
layoutParams: UILayoutParams;
fontDescription: UIFontDescription;
gravity: UI_GRAVITY;
value: number;
focus: boolean;
visibility: UI_WIDGET_VISIBILITY;
stateRaw: number;
dragObject: UIDragObject;
firstChild: UIWidget;
next: UIWidget;
isFocusable: boolean;
view: UIView;
constructor(createWidget?: boolean);
load(filename: string): boolean;
getId(): string;
getParent(): UIWidget;
getContentRoot(): UIWidget;
getRect(): IntRect;
getPreferredSize(): UIPreferredSize;
getText(): string;
setRect(r: IntRect): void;
setSize(width: number, height: number): void;
setPosition(x: number, y: number): void;
setText(text: string): void;
setSkinBg(id: string): void;
setLayoutParams(params: UILayoutParams): void;
setFontDescription(fd: UIFontDescription): void;
removeChild(child: UIWidget, cleanup?: boolean): void;
deleteAllChildren(): void;
setId(id: string): void;
center(): void;
setGravity(gravity: UI_GRAVITY): void;
setValue(value: number): void;
getValue(): number;
setFocus(): void;
getFocus(): boolean;
// Set focus to first widget which accepts it
setFocusRecursive(): void;
onFocusChanged(focused: boolean): void;
setState(state: number, on: boolean): void;
getState(state: number): boolean;
setVisibility(visibility: UI_WIDGET_VISIBILITY): void;
getVisibility(): UI_WIDGET_VISIBILITY;
setStateRaw(state: number): void;
getStateRaw(): number;
invalidate(): void;
die(): void;
setDragObject(object: UIDragObject): void;
getDragObject(): UIDragObject;
getFirstChild(): UIWidget;
getNext(): UIWidget;
isAncestorOf(widget: UIWidget): boolean;
setIsFocusable(value: boolean): void;
getWidget(id: string): UIWidget;
getView(): UIView;
addChild(child: UIWidget): void;
// This takes a relative Z and insert the child before or after the given reference widget.
addChildRelative(child: UIWidget, z: UI_WIDGET_Z_REL, reference: UIWidget): void;
}
export class UIWindow extends UIWidget {
settings: UI_WINDOW_SETTINGS;
constructor(createWidget?: boolean);
getSettings(): UI_WINDOW_SETTINGS;
setSettings(settings: UI_WINDOW_SETTINGS): void;
resizeToFitContent(): void;
addChild(child: UIWidget): void;
close(): void;
}
//----------------------------------------------------
// MODULE: Resource
//----------------------------------------------------
export class Image extends Resource {
width: number;
height: number;
depth: number;
components: number;
compressedFormat: CompressedFormat;
numCompressedLevels: number;
nextLevel: Image;
// Construct empty.
constructor();
// Flip image horizontally. Return true if successful.
flipHorizontal(): boolean;
// Flip image vertically. Return true if successful.
flipVertical(): boolean;
// Resize image by bilinear resampling. Return true if successful.
resize(width: number, height: number): boolean;
// Clear the image with a color.
clear(color: Color): void;
// Clear the image with an integer color. R component is in the 8 lowest bits.
clearInt(uintColor: number): void;
// Save in BMP format. Return true if successful.
saveBMP(fileName: string): boolean;
// Save in PNG format. Return true if successful.
savePNG(fileName: string): boolean;
// Save in TGA format. Return true if successful.
saveTGA(fileName: string): boolean;
// Save in JPG format with compression quality. Return true if successful.
saveJPG(fileName: string, quality: number): boolean;
// Return a bilinearly sampled 2D pixel color. X and Y have the range 0-1.
getPixelBilinear(x: number, y: number): Color;
// Return a trilinearly sampled 3D pixel color. X, Y and Z have the range 0-1.
getPixelTrilinear(x: number, y: number, z: number): Color;
// Return width.
getWidth(): number;
// Return height.
getHeight(): number;
// Return depth.
getDepth(): number;
// Return number of color components.
getComponents(): number;
// Return whether is compressed.
isCompressed(): boolean;
// Return compressed format.
getCompressedFormat(): CompressedFormat;
// Return number of compressed mip levels.
getNumCompressedLevels(): number;
// Return next mip level by bilinear filtering.
getNextLevel(): Image;
// Return image converted to 4-component (RGBA) to circumvent modern rendering API's not supporting e.g. the luminance-alpha format.
convertToRGBA(): Image;
// Return subimage from the image by the defined rect or null if failed. 3D images are not supported. You must free the subimage yourself.
getSubimage(rect: IntRect): Image;
// Precalculate the mip levels. Used by asynchronous texture loading.
precalculateLevels(): void;
}
export class JSONFile extends Resource {
// Construct.
constructor();
}
export class PListFile extends Resource {
// Construct.
constructor();
}
export class Resource extends AObject {
name: string;
memoryUse: number;
asyncLoadState: AsyncLoadState;
nameHash: string;
useTimer: number;
// Construct.
constructor();
// Finish resource loading. Always called from the main thread. Return true if successful.
endLoad(): boolean;
// Set name.
setName(name: string): void;
// Set memory use in bytes, possibly approximate.
setMemoryUse(size: number): void;
// Reset last used timer.
resetUseTimer(): void;
// Set the asynchronous loading state. Called by ResourceCache. Resources in the middle of asynchronous loading are not normally returned to user.
setAsyncLoadState(newState: AsyncLoadState): void;
// Return name.
getName(): string;
// Return name hash.
getNameHash(): string;
// Return memory use in bytes, possibly approximate.
getMemoryUse(): number;
// Return time since last use in milliseconds. If referred to elsewhere than in the resource cache, returns always zero.
getUseTimer(): number;
// Return the asynchronous loading state.
getAsyncLoadState(): AsyncLoadState;
}
export class ResourceCache extends AObject {
autoReloadResources: boolean;
returnFailedResources: boolean;
searchPackagesFirst: boolean;
finishBackgroundResourcesMs: number;
numBackgroundLoadResources: number;
resourceDirs: string[];
totalMemoryUse: number;
// Construct.
constructor();
// Add a resource load directory. Optional priority parameter which will control search order.
addResourceDir(pathName: string, priority?: number): boolean;
// Add a package file for loading resources from by name. Optional priority parameter which will control search order.
addPackageFile(fileName: string, priority?: number): boolean;
// Add a manually created resource. Must be uniquely named.
addManualResource(resource: Resource): boolean;
// Remove a resource load directory.
removeResourceDir(pathName: string): void;
// Remove a package file by name. Optionally release the resources loaded from it.
removePackageFile(fileName: string, releaseResources?: boolean, forceRelease?: boolean): void;
// Release a resource by name.
releaseResource(type: string, name: string, force?: boolean): void;
// Release all resources. When called with the force flag false, releases all currently unused resources.
releaseAllResources(force?: boolean): void;
// Reload a resource. Return true on success. The resource will not be removed from the cache in case of failure.
reloadResource(resource: Resource): boolean;
// Reload a resource based on filename. Causes also reload of dependent resources if necessary.
reloadResourceWithDependencies(fileName: string): void;
// Set memory budget for a specific resource type, default 0 is unlimited.
setMemoryBudget(type: string, budget: number): void;
// Enable or disable automatic reloading of resources as files are modified. Default false.
setAutoReloadResources(enable: boolean): void;
// Enable or disable returning resources that failed to load. Default false. This may be useful in editing to not lose resource ref attributes.
setReturnFailedResources(enable: boolean): void;
// Define whether when getting resources should check package files or directories first. True for packages, false for directories.
setSearchPackagesFirst(value: boolean): void;
// Set how many milliseconds maximum per frame to spend on finishing background loaded resources.
setFinishBackgroundResourcesMs(ms: number): void;
// Open and return a file from the resource load paths or from inside a package file. If not found, use a fallback search with absolute path. Return null if fails. Can be called from outside the main thread.
getFile(name: string, sendEventOnFailure?: boolean): File;
// Return a resource by type and name. Load if not loaded yet. Return null if not found or if fails, unless SetReturnFailedResources(true) has been called. Can be called only from the main thread.
getResource(type: string, name: string, sendEventOnFailure?: boolean): Resource;
// Load a resource without storing it in the resource cache. Return null if not found or if fails. Can be called from outside the main thread if the resource itself is safe to load completely (it does not possess for example GPU data.)
getTempResource(type: string, name: string, sendEventOnFailure?: boolean): Resource;
// Background load a resource. An event will be sent when complete. Return true if successfully stored to the load queue, false if eg. already exists. Can be called from outside the main thread.
backgroundLoadResource(type: string, name: string, sendEventOnFailure?: boolean, caller?: Resource): boolean;
// Return number of pending background-loaded resources.
getNumBackgroundLoadResources(): number;
// Return an already loaded resource of specific type & name, or null if not found. Will not load if does not exist.
getExistingResource(type: string, name: string): Resource;
// Return added resource load directories.
getResourceDirs(): string[];
// Return whether a file exists by name.
exists(name: string): boolean;
// Return memory budget for a resource type.
getMemoryBudget(type: string): number;
// Return total memory use for a resource type.
getMemoryUse(type: string): number;
// Return total memory use for all resources.
getTotalMemoryUse(): number;
// Return full absolute file name of resource if possible.
getResourceFileName(name: string): string;
// Return whether automatic resource reloading is enabled.
getAutoReloadResources(): boolean;
// Return whether resources that failed to load are returned.
getReturnFailedResources(): boolean;
// Return whether when getting resources should check package files or directories first.
getSearchPackagesFirst(): boolean;
// Return how many milliseconds maximum to spend on finishing background loaded resources.
getFinishBackgroundResourcesMs(): number;
// Return either the path itself or its parent, based on which of them has recognized resource subdirectories.
getPreferredResourceDir(path: string): string;
// Remove unsupported constructs from the resource name to prevent ambiguity, and normalize absolute filename to resource path relative if possible.
sanitateResourceName(name: string): string;
// Remove unnecessary constructs from a resource directory name and ensure it to be an absolute path.
sanitateResourceDirName(name: string): string;
// Store a dependency for a resource. If a dependency file changes, the resource will be reloaded.
storeResourceDependency(resource: Resource, dependency: string): void;
// Reset dependencies for a resource.
resetDependencies(resource: Resource): void;
}
export class XMLFile extends Resource {
// Construct.
constructor();
// Deserialize from a string. Return true if successful.
fromString(source: string): boolean;
// Serialize the XML content to a string.
toString(indentation?: string): string;
// Patch the XMLFile with another XMLFile. Based on RFC 5261.
patch(patchFile: XMLFile): void;
}
//----------------------------------------------------
// MODULE: Network
//----------------------------------------------------
export class HttpRequest extends RefCounted {
url: string;
verb: string;
error: string;
state: HttpRequestState;
availableSize: number;
// Construct with parameters.
constructor(url: string, verb: string, headers: string[], postData: string);
// Process the connection in the worker thread until closed.
threadFunction(): void;
// Set position from the beginning of the stream. Not supported.
seek(position: number): number;
// Return URL used in the request.
getURL(): string;
// Return verb used in the request. Default GET if empty verb specified on construction.
getVerb(): string;
// Return error. Only non-empty in the error state.
getError(): string;
// Return connection state.
getState(): HttpRequestState;
// Return amount of bytes in the read buffer.
getAvailableSize(): number;
// Return whether connection is in the open state.
isOpen(): boolean;
}
export class Network extends AObject {
updateFps: number;
simulatedLatency: number;
simulatedPacketLoss: number;
packageCacheDir: string;
// Construct.
constructor();
// Disconnect the connection to the server. If wait time is non-zero, will block while waiting for disconnect to finish.
disconnect(waitMSec?: number): void;
// Start a server on a port using UDP protocol. Return true if successful.
startServer(port: number): boolean;
// Stop the server.
stopServer(): void;
// Set network update FPS.
setUpdateFps(fps: number): void;
// Set simulated latency in milliseconds. This adds a fixed delay before sending each packet.
setSimulatedLatency(ms: number): void;
// Set simulated packet loss probability between 0.0 - 1.0.
setSimulatedPacketLoss(probability: number): void;
// Register a remote event as allowed to be received. There is also a fixed blacklist of events that can not be allowed in any case, such as ConsoleCommand.
registerRemoteEvent(eventType: string): void;
// Unregister a remote event as allowed to received.
unregisterRemoteEvent(eventType: string): void;
// Unregister all remote events.
unregisterAllRemoteEvents(): void;
// Set the package download cache directory.
setPackageCacheDir(path: string): void;
// Perform an HTTP request to the specified URL. Empty verb defaults to a GET request. Return a request object which can be used to read the response data.
makeHttpRequest(url: string, verb?: string, headers?: string[], postData?: string): HttpRequest;
// Return network update FPS.
getUpdateFps(): number;
// Return simulated latency in milliseconds.
getSimulatedLatency(): number;
// Return simulated packet loss probability.
getSimulatedPacketLoss(): number;
// Return whether the server is running.
isServerRunning(): boolean;
// Return whether a remote event is allowed to be received.
checkRemoteEvent(eventType: string): boolean;
// Return the package download cache directory.
getPackageCacheDir(): string;
// Process incoming messages from connections. Called by HandleBeginFrame.
update(timeStep: number): void;
// Send outgoing messages after frame logic. Called by HandleRenderUpdate.
postUpdate(timeStep: number): void;
}
export class NetworkPriority extends Component {
basePriority: number;
distanceFactor: number;
minPriority: number;
alwaysUpdateOwner: boolean;
// Construct.
constructor();
// Set base priority. Default 100 (send updates at full frequency.)
setBasePriority(priority: number): void;
// Set priority reduction distance factor. Default 0 (no effect.)
setDistanceFactor(factor: number): void;
// Set minimum priority. Default 0 (no updates when far away enough.)
setMinPriority(priority: number): void;
// Set whether updates to owner should be sent always at full rate. Default true.
setAlwaysUpdateOwner(enable: boolean): void;
// Return base priority.
getBasePriority(): number;
// Return priority reduction distance factor.
getDistanceFactor(): number;
// Return minimum priority.
getMinPriority(): number;
// Return whether updates to owner should be sent always at full rate.
getAlwaysUpdateOwner(): boolean;
}
//----------------------------------------------------
// MODULE: IO
//----------------------------------------------------
export class File extends AObject {
name: string;
checksum: number;
fullPath: string;
mode: FileMode;
// Construct and open a filesystem file.
constructor(fileName: string, mode?: FileMode);
// Set position from the beginning of the file.
seek(position: number): number;
// Return the file name.
getName(): string;
// Return a checksum of the file contents using the SDBM hash algorithm.
getChecksum(): number;
// Open a filesystem file. Return true if successful.
open(fileName: string, mode?: FileMode): boolean;
// Close the file.
close(): void;
// Flush any buffered output to the file.
flush(): void;
// Change the file name. Used by the resource system.
setName(name: string): void;
// Set the fullpath to the file
setFullPath(path: string): void;
// Return the open mode.
getMode(): FileMode;
// Return whether is open.
isOpen(): boolean;
// Return whether the file originates from a package.
isPackaged(): boolean;
// Return the fullpath to the file
getFullPath(): string;
// Unlike FileSystem.Copy this copy works when the source file is in a package file
copy(srcFile: File): boolean;
readText():string;
writeString(text:string):void;
}
export class FileSystem extends AObject {
executeConsoleCommands: boolean;
currentDir: string;
programDir: string;
userDocumentsDir: string;
appBundleResourceFolder: string;
// Construct.
constructor();
// Set the current working directory.
setCurrentDir(pathName: string): boolean;
// Create a directory.
createDir(pathName: string): boolean;
// Set whether to execute engine console commands as OS-specific system command.
setExecuteConsoleCommands(enable: boolean): void;
// Run a program using the command interpreter, block until it exits and return the exit code. Will fail if any allowed paths are defined.
systemCommand(commandLine: string, redirectStdOutToLog?: boolean): number;
// Run a specific program, block until it exits and return the exit code. Will fail if any allowed paths are defined.
systemRun(fileName: string, args: string[]): number;
// Run a program using the command interpreter asynchronously. Return a request ID or M_MAX_UNSIGNED if failed. The exit code will be posted together with the request ID in an AsyncExecFinished event. Will fail if any allowed paths are defined.
systemCommandAsync(commandLine: string): number;
// Run a specific program asynchronously. Return a request ID or M_MAX_UNSIGNED if failed. The exit code will be posted together with the request ID in an AsyncExecFinished event. Will fail if any allowed paths are defined.
systemRunAsync(fileName: string, args: string[]): number;
// Open a file in an external program, with mode such as "edit" optionally specified. Will fail if any allowed paths are defined.
systemOpen(fileName: string, mode?: string): boolean;
// Copy a file. Return true if successful.
copy(srcFileName: string, destFileName: string): boolean;
// Rename a file. Return true if successful.
rename(srcFileName: string, destFileName: string): boolean;
// Delete a file. Return true if successful.
delete(fileName: string): boolean;
// Register a path as allowed to access. If no paths are registered, all are allowed. Registering allowed paths is considered securing the Atomic execution environment: running programs and opening files externally through the system will fail afterward.
registerPath(pathName: string): void;
// Set a file's last modified time as seconds since 1.1.1970. Return true on success.
setLastModifiedTime(fileName: string, newTime: number): boolean;
// Return the absolute current working directory.
getCurrentDir(): string;
// Return whether is executing engine console commands as OS-specific system command.
getExecuteConsoleCommands(): boolean;
// Return whether paths have been registered.
hasRegisteredPaths(): boolean;
// Check if a path is allowed to be accessed. If no paths are registered, all are allowed.
checkAccess(pathName: string): boolean;
// Returns the file's last modified time as seconds since 1.1.1970, or 0 if can not be accessed.
getLastModifiedTime(fileName: string): number;
// Check if a file exists.
fileExists(fileName: string): boolean;
// Check if a directory exists.
dirExists(pathName: string): boolean;
// Return the program's directory. If it does not contain the Atomic default CoreData and Data directories, and the current working directory does, return the working directory instead.
getProgramDir(): string;
// Return the user documents directory.
getUserDocumentsDir(): string;
// Return the application preferences directory.
getAppPreferencesDir(org: string, app: string): string;
getAppBundleResourceFolder(): string;
// Remove a directory
removeDir(directoryIn: string, recursive: boolean): boolean;
// Create directory and all necessary subdirectories below a given root
createDirs(root: string, subdirectory: string): boolean;
// Copy a directory, directoryOut must not exist
copyDir(directoryIn: string, directoryOut: string): boolean;
// Check if a file or directory exists at the specified path
exists(pathName: string): boolean;
createDirsRecursive(directoryIn: string, directoryOut: string): boolean;
scanDir(pathName:string, filter:string, flags:number, recursive:boolean):Array<string>;
}
export class FileWatcher extends AObject {
delay: number;
path: string;
// Construct.
constructor();
// Directory watching loop.
threadFunction(): void;
// Start watching a directory. Return true if successful.
startWatching(pathName: string, watchSubDirs: boolean): boolean;
// Stop watching the directory.
stopWatching(): void;
// Set the delay in seconds before file changes are notified. This (hopefully) avoids notifying when a file save is still in progress. Default 1 second.
setDelay(interval: number): void;
// Add a file change into the changes queue.
addChange(fileName: string): void;
// Return the path being watched, or empty if not watching.
getPath(): string;
// Return the delay in seconds for notifying file changes.
getDelay(): number;
}
export class Log extends AObject {
level: number;
timeStamp: boolean;
quiet: boolean;
lastMessage: string;
// Construct.
constructor();
// Open the log file.
open(fileName: string): void;
// Close the log file.
close(): void;
// Set logging level.
setLevel(level: number): void;
// Set whether to timestamp log messages.
setTimeStamp(enable: boolean): void;
// Set quiet mode ie. only print error entries to standard error stream (which is normally redirected to console also). Output to log file is not affected by this mode.
setQuiet(quiet: boolean): void;
// Return logging level.
getLevel(): number;
// Return whether log messages are timestamped.
getTimeStamp(): boolean;
// Return last log message.
getLastMessage(): string;
// Return whether log is in quiet mode (only errors printed to standard error stream).
isQuiet(): boolean;
// Write to the log. If logging level is higher than the level of the message, the message is ignored.
write(level: number, message: string): void;
// Write raw output to the log.
writeRaw(message: string, error?: boolean): void;
}
//----------------------------------------------------
// MODULE: Engine
//----------------------------------------------------
export class Engine extends AObject {
minFps: number;
maxFps: number;
maxInactiveFps: number;
timeStepSmoothing: number;
pauseMinimized: boolean;
autoExit: boolean;
nextTimeStep: number;
// Construct.
constructor();
// Run one frame.
runFrame(): void;
// Set minimum frames per second. If FPS goes lower than this, time will appear to slow down.
setMinFps(fps: number): void;
// Set maximum frames per second. The engine will sleep if FPS is higher than this.
setMaxFps(fps: number): void;
// Set maximum frames per second when the application does not have input focus.
setMaxInactiveFps(fps: number): void;
// Set how many frames to average for timestep smoothing. Default is 2. 1 disables smoothing.
setTimeStepSmoothing(frames: number): void;
// Set whether to pause update events and audio when minimized.
setPauseMinimized(enable: boolean): void;
// Set whether to exit automatically on exit request (window close button.)
setAutoExit(enable: boolean): void;
// Override timestep of the next frame. Should be called in between RunFrame() calls.
setNextTimeStep(seconds: number): void;
// Close the graphics window and set the exit flag. No-op on iOS, as an iOS application can not legally exit.
exit(): void;
// Dump profiling information to the log.
dumpProfiler(): void;
// Dump information of all resources to the log.
dumpResources(dumpFileName?: boolean): void;
// Dump information of all memory allocations to the log. Supported in MSVC debug mode only.
dumpMemory(): void;
// Get timestep of the next frame. Updated by ApplyFrameLimit().
getNextTimeStep(): number;
// Return the minimum frames per second.
getMinFps(): number;
// Return the maximum frames per second.
getMaxFps(): number;
// Return the maximum frames per second when the application does not have input focus.
getMaxInactiveFps(): number;
// Return how many frames to average for timestep smoothing.
getTimeStepSmoothing(): number;
// Return whether to pause update events and audio when minimized.
getPauseMinimized(): boolean;
// Return whether to exit automatically on exit request.
getAutoExit(): boolean;
// Return whether engine has been initialized.
isInitialized(): boolean;
// Return whether exit has been requested.
isExiting(): boolean;
// Return whether the engine has been created in headless mode.
isHeadless(): boolean;
// Send frame update events.
update(): void;
// Render after frame update.
render(): void;
// Get the timestep for the next frame and sleep for frame limiting if necessary.
applyFrameLimit(): void;
}
//----------------------------------------------------
// MODULE: Javascript
//----------------------------------------------------
export class JSComponent extends Component {
componentFile: JSComponentFile;
updateEventMask: number;
// Construct.
constructor();
applyAttributes(): void;
getComponentFile(): JSComponentFile;
// Match script name
matchScriptName(path: string): boolean;
// Handle enabled/disabled state change. Changes update event subscription.
onSetEnabled(): void;
// Set what update events should be subscribed to. Use this for optimization: by default all are in use. Note that this is not an attribute and is not saved or network-serialized, therefore it should always be called eg. in the subclass constructor.
setUpdateEventMask(mask: number): void;
// Return what update events are subscribed to.
getUpdateEventMask(): number;
// Return whether the DelayedStart() function has been called.
isDelayedStartCalled(): boolean;
setComponentFile(cfile: JSComponentFile): void;
setDestroyed(): void;
initInstance(hasArgs?: boolean, argIdx?: number): void;
}
export class JSComponentFile extends Resource {
scriptClass: boolean;
// Construct.
constructor();
getScriptClass(): boolean;
createJSComponent(): JSComponent;
pushModule(): boolean;
}
export class JSEventHelper extends AObject {
// Construct.
constructor(object: AObject);
}
export class ScriptObject extends AObject {
// Construct.
constructor();
}
//----------------------------------------------------
// MODULE: Environment
//----------------------------------------------------
export class ProcSky extends Drawable {
dayTime: number;
autoUpdate: boolean;
updateGeometryType: UpdateGeometryType;
timeOfDay: number;
constructor();
setDayTime(time: number): number;
getDayTime(): number;
setAutoUpdate(autoUpdate: boolean): void;
// Return whether a geometry update is necessary, and if it can happen in a worker thread.
getUpdateGeometryType(): UpdateGeometryType;
getTimeOfDay(): number;
}
} | the_stack |
import * as React from "react";
import { getColor, makePattern, reverseMap, palette, hashString, makeBlockSizeLog2MapByValue, HEAT_COLORS, Decoder, Rectangle, Size, AnalyzerFrame, loadFramesFromJson, downloadFile, Histogram, Accounting, AccountingSymbolMap, clamp, Vector, localFiles, localFileProtocol } from "./analyzerTools";
import { HistogramComponent } from "./Histogram";
import { TRACE_RENDERING, padLeft, log2, assert, unreachable } from "./analyzerTools";
import {
Checkbox,
Dialog,
DialogActions,
DialogContent, DialogTitle, Divider, FormControlLabel, FormGroup, IconButton, Menu, MenuItem, Select, Slider, Tab,
Table,
TableBody,
TableCell,
TableHead,
TableRow, Tabs, TextField, Toolbar, Tooltip, Typography
} from "@material-ui/core";
import Button from "@material-ui/core/Button";
import { TextAlignProperty } from "csstype";
import LayersIcon from "@material-ui/icons/Layers";
import Replay30Icon from "@material-ui/icons/Replay30";
import ZoomInIcon from "@material-ui/icons/ZoomIn";
import ZoomOutIcon from "@material-ui/icons/ZoomOut";
import StopIcon from "@material-ui/icons/Stop";
import SkipNextIcon from "@material-ui/icons/SkipNext";
import PlayArrowIcon from "@material-ui/icons/PlayArrow";
import SkipPreviousIcon from "@material-ui/icons/SkipPrevious";
import ImageIcon from "@material-ui/icons/Image";
import ClearIcon from "@material-ui/icons/Clear";
import ShareIcon from "@material-ui/icons/Share";
import {red, grey} from "@material-ui/core/colors";
declare const Mousetrap;
declare var shortenUrl;
declare var document;
declare var window;
const SUPER_BLOCK_SIZE = 64;
const ZOOM_WIDTH = 500;
const ZOOM_SOURCE = 64;
const DEFAULT_CONFIG = "--disable-multithread --disable-runtime-cpu-detect --target=generic-gnu --enable-accounting --enable-analyzer --enable-aom_highbitdepth --extra-cflags=-D_POSIX_SOURCE --enable-inspection --disable-docs --disable-webm-io --enable-experimental";
const DERING_STRENGTHS = 21;
const CLPF_STRENGTHS = 4;
enum VisitMode {
Block,
SuperBlock,
TransformBlock,
Tile
}
enum HistogramTab {
Bits,
Symbols,
BlockSize,
TransformSize,
TransformType,
PredictionMode,
UVPredictionMode,
Skip,
DualFilterType
}
function colorScale(v, colors) {
return colors[Math.round(v * (colors.length - 1))];
}
function keyForValue(o: Object, value: any): string {
if (o) {
for (let k in o) {
if (o[k] === value) {
return k;
}
}
}
return String(value);
}
function shuffle(array: any[], count: number) {
// Shuffle Indices
for (let j = 0; j < count; j++) {
let a = Math.random() * array.length | 0;
let b = Math.random() * array.length | 0;
let t = array[a];
array[a] = array[b];
array[b] = t;
}
}
function blockSizeArea(frame: AnalyzerFrame, size: number) {
const map = frame.blockSizeLog2Map;
return (1 << map[size][0]) * (1 << map[size][1]);
}
function forEachValue(o: any, fn: (v: any) => void) {
for (let n in o) {
fn(o[n]);
}
}
function fractionalBitsToString(v: number) {
if (v > 16) {
return ((v / 8) | 0).toLocaleString();
}
return (v / 8).toLocaleString();
}
function toPercent(v: number) {
return (v * 100).toFixed(1);
}
function withCommas(v: number) {
return v.toLocaleString();
}
function toByteSize(v: number) {
return withCommas(v) + " Bytes";
}
function getLineOffset(lineWidth: number) {
return lineWidth % 2 == 0 ? 0 : 0.5;
}
function toCflAlphas(cfl_alpha_idx: number, cfl_alpha_sign: number) {
cfl_alpha_idx &= 255;
cfl_alpha_sign &= 7;
let sign_u = ((cfl_alpha_sign + 1) * 11) >> 5;
let sign_v = cfl_alpha_sign + 1 - 3 * sign_u;
let alpha_u = 1 + (cfl_alpha_idx >> 4);
let alpha_v = 1 + (cfl_alpha_idx & 15);
let cfl_alpha_u = [0, -1, 1][sign_u] * alpha_u;
let cfl_alpha_v = [0, -1, 1][sign_v] * alpha_v;
return [cfl_alpha_u, cfl_alpha_v];
}
function drawVector(ctx: CanvasRenderingContext2D, a: Vector, b: Vector) {
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.closePath();
ctx.stroke();
return;
}
function drawLine(ctx: CanvasRenderingContext2D, x, y, dx, dy) {
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + dx, y + dy);
ctx.closePath();
ctx.stroke();
}
interface BlockVisitor {
(blockSize: number, c: number, r: number, sc: number, sr: number, bounds: Rectangle, scale: number): void;
}
interface AnalyzerViewProps {
groups: AnalyzerFrame[][],
groupNames?: string[],
playbackFrameRate?: number;
blind?: number;
onDecodeAdditionalFrames: (count: number) => void;
decoderVideoUrlPairs?: { decoderUrl: string, videoUrl: string, decoderName: string }[];
}
interface AlertProps {
open: boolean;
onClose: (value: boolean) => void;
title: string;
description: string;
}
export class Alert extends React.Component<AlertProps, {
}> {
constructor(props: AlertProps) {
super(props);
}
handleAction(value) {
this.props.onClose(value);
}
render() {
return <div>
<Dialog open={this.props.open}>
<DialogTitle>{this.props.title}</DialogTitle>
<DialogContent>
{this.props.description}
</DialogContent>
<DialogActions>
<Button
onClick={this.handleAction.bind(this, false)}
>Cancel</Button>
<Button
color="primary"
onClick={this.handleAction.bind(this, true)}
>OK</Button>
</DialogActions>
</Dialog>
</div>
}
}
export class AccountingComponent extends React.Component<{
symbols: AccountingSymbolMap;
}, {
}> {
render() {
let symbols = this.props.symbols;
let total = 0;
forEachValue(symbols, (symbol) => {
total += symbol.bits;
});
let rows = []
for (let name in symbols) {
let symbol = symbols[name];
rows.push(<TableRow key={name}>
<TableCell>{name}</TableCell>
<TableCell align="right">{fractionalBitsToString(symbol.bits)}</TableCell>
<TableCell align="right">{toPercent(symbol.bits / total)}</TableCell>
<TableCell align="right">{withCommas(symbol.samples)}</TableCell>
</TableRow>);
}
return <div>
<Table size="small">
<TableHead>
<TableRow>
<TableCell style={{ color: red[200] }}>Symbol</TableCell>
<TableCell style={{ color: red[200] }} align="right">Bits {fractionalBitsToString(total)}</TableCell>
<TableCell style={{ color: red[200] }} align="right">%</TableCell>
<TableCell style={{ color: red[200] }} align="right">Samples</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows}
</TableBody>
</Table>
</div>
}
}
export class FrameInfoComponent extends React.Component<{
frame: AnalyzerFrame;
activeFrame: number;
activeGroup: number;
}, {
}> {
render() {
let frame = this.props.frame;
let valueStyle = { textAlign: "right" as TextAlignProperty, fontSize: "12px" };
return <div>
<Table size="small">
<TableBody>
<TableRow>
<TableCell>Video</TableCell><TableCell style={valueStyle}>{this.props.activeGroup}</TableCell>
</TableRow>
<TableRow>
<TableCell>Frame</TableCell><TableCell style={valueStyle}>{this.props.activeFrame + 1}</TableCell>
</TableRow>
<TableRow>
<TableCell>Frame Type</TableCell><TableCell style={valueStyle}>{frame.json.frameType}</TableCell>
</TableRow>
<TableRow>
<TableCell>Show Frame</TableCell><TableCell style={valueStyle}>{frame.json.showFrame}</TableCell>
</TableRow>
<TableRow>
<TableCell>BaseQIndex</TableCell><TableCell style={valueStyle}>{frame.json.baseQIndex}</TableCell>
</TableRow>
<TableRow>
<TableCell>Frame Size</TableCell><TableCell style={valueStyle}>{frame.image.width} x {frame.image.height}</TableCell>
</TableRow>
<TableRow>
<TableCell>MI Size</TableCell><TableCell style={valueStyle}>{1 << frame.miSizeLog2}</TableCell>
</TableRow>
<TableRow>
<TableCell>DeltaQ Res / Present Flag</TableCell><TableCell style={valueStyle}>{frame.json.deltaQRes} / {frame.json.deltaQPresentFlag}</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
}
}
export class ModeInfoComponent extends React.Component<{
frame: AnalyzerFrame;
position: Vector;
}, {
}> {
render() {
let c = this.props.position.x;
let r = this.props.position.y;
let json = this.props.frame.json;
function getProperty(name: string): string {
if (!json[name]) return "N/A";
let v = json[name][r][c];
if (!json[name + "Map"]) return String(v);
return keyForValue(json[name + "Map"], v);
}
function getSuperBlockProperty(name: string): string {
if (!json[name]) return "N/A";
let v = json[name][r & ~7][c & ~7];
if (!json[name + "Map"]) return String(v);
return keyForValue(json[name + "Map"], v);
}
function getMotionVector() {
let motionVectors = json["motionVectors"];
if (!motionVectors) return "N/A";
let v = motionVectors[r][c];
return `${v[0]},${v[1]} ${v[2]},${v[3]}`;
}
function getReferenceFrame() {
let referenceFrame = json["referenceFrame"];
if (!referenceFrame) return "N/A";
let map = json["referenceFrameMap"];
let v = referenceFrame[r][c];
let a = v[0] >= 0 ? keyForValue(map, v[0]) : "N/A";
let b = v[1] >= 0 ? keyForValue(map, v[1]) : "N/A";
return `${a}, ${b}`;
}
function getCFL() {
if (json["cfl_alpha_idx"] === undefined) {
return "N/A";
}
let cfl_alpha_idx = json["cfl_alpha_idx"][r][c];
let cfl_alpha_sign = json["cfl_alpha_sign"][r][c];
let [cfl_alpha_u, cfl_alpha_v] = toCflAlphas(cfl_alpha_idx, cfl_alpha_sign);
return `${cfl_alpha_u},${cfl_alpha_v}`;
}
function getDualFilterType() {
if (json["dualFilterType"] === undefined) {
return "N/A";
}
let map = json["dualFilterTypeMap"];
return keyForValue(map, json["dualFilterType"][r][c]);
}
function getDeltaQIndex() {
if (json["delta_q"] === undefined) {
return "N/A";
}
return json["delta_q"][r][c];
}
function getSegId() {
if (json["seg_id"] === undefined) {
return "N/A";
}
return json["seg_id"][r][c];
}
let valueStyle = { textAlign: "right" as TextAlignProperty, fontSize: "12px" };
return <div>
<Table size="small">
<TableBody>
<TableRow>
<TableCell>Block Position: MI (col, row)</TableCell><TableCell style={valueStyle}>({c}, {r})</TableCell>
</TableRow>
<TableRow>
<TableCell>Block Size</TableCell><TableCell style={valueStyle}>{getProperty("blockSize")}</TableCell>
</TableRow>
<TableRow>
<TableCell>Transform Size</TableCell><TableCell style={valueStyle}>{getProperty("transformSize")}</TableCell>
</TableRow>
<TableRow>
<TableCell>Transform Type</TableCell><TableCell style={valueStyle}>{getProperty("transformType")}</TableCell>
</TableRow>
<TableRow>
<TableCell>Mode</TableCell><TableCell style={valueStyle}>{getProperty("mode")}</TableCell>
</TableRow>
<TableRow>
<TableCell>UV Mode</TableCell><TableCell style={valueStyle}>{getProperty("uv_mode")}</TableCell>
</TableRow>
<TableRow>
<TableCell>Skip</TableCell><TableCell style={valueStyle}>{getProperty("skip")}</TableCell>
</TableRow>
<TableRow>
<TableCell>CDEF</TableCell><TableCell style={valueStyle}>{getSuperBlockProperty("cdef_level")} / {getSuperBlockProperty("cdef_strength")}</TableCell>
</TableRow>
<TableRow>
<TableCell>Motion Vectors</TableCell><TableCell style={valueStyle}>{getMotionVector()}</TableCell>
</TableRow>
<TableRow>
<TableCell>Reference Frame</TableCell><TableCell style={valueStyle}>{getReferenceFrame()}</TableCell>
</TableRow>
<TableRow>
<TableCell>CFL</TableCell><TableCell style={valueStyle}>{getCFL()}</TableCell>
</TableRow>
<TableRow>
<TableCell>Dual Filter Type</TableCell><TableCell style={valueStyle}>{getDualFilterType()}</TableCell>
</TableRow>
<TableRow>
<TableCell>DeltaQ Index</TableCell><TableCell style={valueStyle}>{getDeltaQIndex()}</TableCell>
</TableRow>
<TableRow>
<TableCell>Segment ID</TableCell><TableCell style={valueStyle}>{getSegId()}</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
}
}
export class AnalyzerView extends React.Component<AnalyzerViewProps, {
activeFrame: number;
activeGroup: number;
scale: number;
showDecodedImage: boolean;
showMotionVectors: boolean;
showReferenceFrames: boolean;
showBlockGrid: boolean;
showTileGrid: boolean;
showSuperBlockGrid: boolean;
showTransformGrid: boolean;
showSkip: boolean;
showFilters: boolean;
showCDEF: boolean;
showMode: boolean;
showUVMode: boolean;
showSegment: boolean;
showBits: boolean;
showBitsScale: "frame" | "video" | "videos";
showBitsMode: "linear" | "heat" | "heat-opaque";
showBitsFilter: "";
showTransformType: boolean;
showTools: boolean;
showFrameComment: boolean;
activeHistogramTab: number;
layerMenuIsOpen: boolean;
showDecodeDialog: boolean;
decodeFrameCount: number;
activeTab: number;
playInterval: any;
showLayersInZoom: boolean;
lockSelection: boolean;
layerAlpha: number;
shareUrl: string;
showShareUrlDialog: boolean;
}> {
public static defaultProps: AnalyzerViewProps = {
groups: [],
groupNames: null,
playbackFrameRate: 30,
blind: 0,
onDecodeAdditionalFrames: null,
decoderVideoUrlPairs: []
};
activeGroupScore: number[][];
ratio: number;
frameSize: Size;
frameCanvas: HTMLCanvasElement;
frameContext: CanvasRenderingContext2D;
displayCanvas: HTMLCanvasElement;
displayContext: CanvasRenderingContext2D;
overlayCanvas: HTMLCanvasElement;
overlayContext: CanvasRenderingContext2D;
canvasContainer: HTMLDivElement;
zoomCanvas: HTMLCanvasElement;
zoomContext: CanvasRenderingContext2D;
compositionCanvas: HTMLCanvasElement;
compositionContext: CanvasRenderingContext2D = null;
mousePosition: Vector;
mouseZoomPosition: Vector;
downloadLink: HTMLAnchorElement = null;
layerMenuAnchorEl: React.RefObject<any>;
options = {
// showY: {
// key: "y",
// description: "Y",
// detail: "Display Y image plane.",
// updatesImage: true,
// default: true,
// value: undefined
// },
// showU: {
// key: "u",
// description: "U",
// detail: "Display U image plane.",
// updatesImage: true,
// default: true,
// value: undefined
// },
// showV: {
// key: "v",
// description: "V",
// detail: "Display V image plane.",
// updatesImage: true,
// default: true,
// value: undefined
// },
// showOriginalImage: {
// key: "w",
// description: "Original Image",
// detail: "Display loaded .y4m file.",
// updatesImage: true,
// default: false,
// disabled: true,
// value: undefined
// },
showDecodedImage: {
key: "i",
description: "Decoded Image",
detail: "Display decoded image.",
updatesImage: true,
default: true,
value: undefined,
icon: "glyphicon glyphicon-picture" // glyphicon glyphicon-film
},
// showPredictedImage: {
// key: "p",
// description: "Predicted Image",
// detail: "Display the predicted image, or the residual if the decoded image is displayed.",
// updatesImage: true,
// default: false,
// value: undefined
// },
showSuperBlockGrid: {
key: "g",
description: "Super Block Grid",
detail: "Display the 64x64 super block grid.",
default: false,
value: undefined,
icon: "glyphicon glyphicon-th-large"
},
showBlockGrid: {
key: "s",
description: "Split Grid",
detail: "Display block partitions.",
default: false,
value: undefined,
icon: "glyphicon glyphicon-th"
},
showTransformGrid: {
key: "t",
description: "Transform Grid",
detail: "Display transform blocks.",
default: false,
value: undefined,
icon: "icon-j"
},
showTransformType: {
key: "y",
description: "Transform Type",
detail: "Display transform type.",
default: false,
value: undefined,
icon: "icon-m"
},
showMotionVectors: {
key: "m",
description: "Motion Vectors",
detail: "Display motion vectors.",
default: false,
value: undefined,
icon: "icon-u"
},
showReferenceFrames: {
key: "f",
description: "Frame References",
detail: "Display frame references.",
default: false,
value: undefined,
icon: "glyphicon glyphicon-transfer"
},
showMode: {
key: "o",
description: "Mode",
detail: "Display prediction modes.",
default: false,
value: undefined,
icon: "icon-l"
},
showUVMode: {
key: "p",
description: "UV Mode",
detail: "Display UV prediction modes.",
default: false,
value: undefined,
icon: "icon-l"
},
showSegment: {
key: "v",
description: "Show Segment",
detail: "Display segment.",
default: false,
value: undefined,
icon: "icon-l"
},
showBits: {
key: "b",
description: "Bits",
detail: "Display bits.",
default: false,
value: undefined,
icon: "icon-n"
},
showSkip: {
key: "k",
description: "Skip",
detail: "Display skip flags.",
default: false,
value: undefined,
icon: "icon-t"
},
showFilters: {
key: "e",
description: "Filters",
detail: "Display filters.",
default: false,
value: undefined,
icon: "icon-t"
},
showCDEF: {
key: "d",
description: "CDEF",
detail: "Display blocks where the CDEF filter is applied.",
default: false,
value: undefined
},
showTileGrid: {
key: "l",
description: "Tiles",
detail: "Display tile grid.",
default: false,
value: undefined
}
};
constructor(props: AnalyzerViewProps) {
super(props);
let ratio = window.devicePixelRatio || 1;
let activeGroupScore = [];
this.state = {
activeFrame: -1,
activeGroup: 0,
scale: 1,
showBlockGrid: false,
showTileGrid: false,
showSuperBlockGrid: false,
showTransformGrid: false,
showSkip: false,
showCDEF: false,
showMode: false,
showUVMode: false,
showSegment: false,
showBits: false,
showBitsScale: "frame",
showBitsMode: "heat",
showBitsFilter: "",
showDecodedImage: true,
showMotionVectors: false,
showReferenceFrames: false,
showTools: !props.blind,
showFrameComment: false,
activeHistogramTab: HistogramTab.Bits,
layerMenuIsOpen: false,
showDecodeDialog: false,
decodeFrameCount: 1,
activeTab: 0,
showLayersInZoom: false,
lockSelection: true,
layerAlpha: 1,
shareUrl: "",
showShareUrlDialog: false
} as any;
this.ratio = ratio;
this.frameCanvas = document.createElement("canvas") as any;
this.frameContext = this.frameCanvas.getContext("2d");
this.compositionCanvas = document.createElement("canvas") as any;
this.compositionContext = this.compositionCanvas.getContext("2d");
this.mousePosition = new Vector(128, 128);
this.mouseZoomPosition = new Vector(128, 128);
this.activeGroupScore = activeGroupScore;
this.layerMenuAnchorEl = React.createRef();
}
resetCanvas(w: number, h: number) {
let scale = this.state.scale;
// Pad to SUPER_BLOCK_SIZE
w = (w + (SUPER_BLOCK_SIZE - 1)) & ~(SUPER_BLOCK_SIZE - 1);
h = (h + (SUPER_BLOCK_SIZE - 1)) & ~(SUPER_BLOCK_SIZE - 1);
this.frameSize = new Size(w, h);
this.frameCanvas.width = w;
this.frameCanvas.height = h;
this.compositionCanvas.width = w;
this.compositionCanvas.height = h;
this.displayCanvas.style.width = (w * scale) + "px";
this.displayCanvas.style.height = (h * scale) + "px";
this.canvasContainer.style.width = (w * scale) + "px";
this.displayCanvas.width = w * scale * this.ratio;
this.displayCanvas.height = h * scale * this.ratio;
this.displayContext = this.displayCanvas.getContext("2d");
this.overlayCanvas.style.width = (w * scale) + "px";
this.overlayCanvas.style.height = (h * scale) + "px";
this.overlayCanvas.width = w * scale * this.ratio;
this.overlayCanvas.height = h * scale * this.ratio;
this.overlayContext = this.overlayCanvas.getContext("2d");
this.resetZoomCanvas(null);
}
resetZoomCanvas(canvas: HTMLCanvasElement) {
this.zoomCanvas = canvas;
if (!this.zoomCanvas) {
this.zoomContext = null;
return;
}
this.zoomCanvas.style.width = ZOOM_WIDTH + "px";
this.zoomCanvas.style.height = ZOOM_WIDTH + "px";
this.zoomCanvas.width = ZOOM_WIDTH * this.ratio;
this.zoomCanvas.height = ZOOM_WIDTH * this.ratio;
this.zoomContext = this.zoomCanvas.getContext("2d");
}
draw(group: number, index: number) {
let frame = this.props.groups[group][index];
// this.frameContext.putImageData(frame.imageData, 0, 0);
this.frameContext.drawImage(frame.image as any, 0, 0);
// Draw frameCanvas to displayCanvas
(this.displayContext as any).imageSmoothingEnabled = false;
let dw = this.frameSize.w * this.state.scale * this.ratio;
let dh = this.frameSize.h * this.state.scale * this.ratio;
if (this.state.showDecodedImage) {
this.displayContext.drawImage(this.frameCanvas, 0, 0, dw, dh);
} else {
this.displayContext.fillStyle = "#333333";
this.displayContext.fillRect(0, 0, dw, dh);
}
if (this.props.blind) {
return;
}
// Draw Layers
let scale = this.state.scale;
let ctx = this.overlayContext;
let ratio = window.devicePixelRatio || 1;
ctx.clearRect(0, 0, this.frameSize.w * scale * ratio, this.frameSize.h * scale * ratio);
let src = Rectangle.createRectangleFromSize(this.frameSize);
let dst = src.clone().multiplyScalar(scale * this.ratio);
this.drawLayers(frame, ctx, src, dst);
}
drawZoom(group: number, index: number) {
if (!this.zoomCanvas) {
return;
}
TRACE_RENDERING && console.log("drawZoom");
let frame = this.props.groups[group][index];
let mousePosition = this.mouseZoomPosition.clone().divideScalar(this.state.scale).snap();
let src = Rectangle.createRectangleCenteredAtPoint(mousePosition, ZOOM_SOURCE, ZOOM_SOURCE);
let dst = new Rectangle(0, 0, ZOOM_WIDTH * this.ratio, ZOOM_WIDTH * this.ratio);
this.zoomContext.clearRect(0, 0, dst.w, dst.h);
if (this.state.showDecodedImage) {
(this.zoomContext as any).imageSmoothingEnabled = false;
this.zoomContext.clearRect(dst.x, dst.y, dst.w, dst.h);
this.zoomContext.drawImage(this.frameCanvas,
src.x, src.y, src.w, src.h,
dst.x, dst.y, dst.w, dst.h);
}
if (this.state.showLayersInZoom) {
this.drawLayers(frame, this.zoomContext, src, dst);
}
}
drawLayers(frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle) {
ctx.save();
ctx.globalAlpha = 0.5;
this.state.showSkip && this.drawSkip(frame, ctx, src, dst);
this.state.showFilters && this.drawFilters(frame, ctx, src, dst);
this.state.showMode && this.drawMode("mode", frame, ctx, src, dst);
this.state.showUVMode && this.drawMode("uv_mode", frame, ctx, src, dst);
this.state.showSegment && this.drawSegment(frame, ctx, src, dst);
this.state.showBits && this.drawBits(frame, ctx, src, dst);
this.state.showCDEF && this.drawCDEF(frame, ctx, src, dst);
this.state.showTransformType && this.drawTransformType(frame, ctx, src, dst);
this.state.showMotionVectors && this.drawMotionVectors(frame, ctx, src, dst);
this.state.showReferenceFrames && this.drawReferenceFrames(frame, ctx, src, dst);
ctx.globalAlpha = 1;
this.state.showSuperBlockGrid && this.drawGrid(frame, VisitMode.SuperBlock, "#87CEEB", ctx, src, dst, 2);
this.state.showTransformGrid && this.drawGrid(frame, VisitMode.TransformBlock, "yellow", ctx, src, dst);
this.state.showBlockGrid && this.drawGrid(frame, VisitMode.Block, "white", ctx, src, dst);
this.state.showTileGrid && this.drawGrid(frame, VisitMode.Tile, "orange", ctx, src, dst, 5);
this.state.showTools && this.drawSelection(frame, ctx, src, dst);
ctx.restore();
}
drawSelection(frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle) {
let scale = dst.w / src.w;
let ratio = 1;
ctx.save();
let lineOffset = getLineOffset(3);
ctx.translate(lineOffset, lineOffset);
ctx.translate(-src.x * scale, -src.y * scale);
// ctx.strokeStyle = "white";
// ctx.setLineDash([2, 4]);
// let w = ZOOM_SOURCE * ratio * scale;
// ctx.strokeRect(this.mouseZoomPosition.x * ratio - w / 2, this.mouseZoomPosition.y * ratio - w / 2, w, w);
let r = this.getParentMIRect(frame, this.mousePosition);
if (r) {
ctx.strokeStyle = "orange";
ctx.lineWidth = 3;
ctx.setLineDash([]);
ctx.strokeRect(r.x * ratio * scale, r.y * ratio * scale, r.w * ratio * scale, r.h * ratio * scale);
}
ctx.restore();
}
drawGrid(frame: AnalyzerFrame, mode: VisitMode, color: string, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle, lineWidth = 1) {
let scale = dst.w / src.w;
ctx.save();
ctx.lineWidth = 1;
ctx.strokeStyle = color;
let lineOffset = getLineOffset(lineWidth);
ctx.translate(lineOffset, lineOffset);
ctx.translate(-src.x * scale, -src.y * scale);
ctx.lineWidth = lineWidth;
this.visitBlocks(mode, frame, (blockSize, c, r, sc, sr, bounds) => {
bounds.multiplyScalar(scale);
ctx.strokeRect(bounds.x, bounds.y, bounds.w, bounds.h);
});
ctx.restore();
}
componentDidMount() {
if (!this.props.groups.length)
return;
this.reset();
this.installKeyboardShortcuts();
this.advanceFrame(1);
this.overlayCanvas.addEventListener("mousemove", this.onMouseMove.bind(this));
this.overlayCanvas.addEventListener("mousedown", this.onMouseDown.bind(this));
}
componentDidUpdate(prevProps, prevState) {
let image = this.props.groups[this.state.activeGroup][0].image;
let w = image.width;
let h = image.height;
w = (w + (SUPER_BLOCK_SIZE - 1)) & ~(SUPER_BLOCK_SIZE - 1);
h = (h + (SUPER_BLOCK_SIZE - 1)) & ~(SUPER_BLOCK_SIZE - 1);
let frameSizeChanged = this.frameSize.w !== w || this.frameSize.h != h;
if (this.state.scale != prevState.scale || frameSizeChanged) {
this.reset();
}
if (this.state.activeFrame >= 0) {
this.draw(this.state.activeGroup, this.state.activeFrame);
if (this.state.showTools) {
this.drawZoom(this.state.activeGroup, this.state.activeFrame);
}
}
}
reset() {
let image = this.props.groups[this.state.activeGroup][0].image;
let w = image.width, h = image.height;
this.resetCanvas(w, h);
}
handleSelect(frame) {
this.setState({
activeFrame: frame
} as any);
}
playPause() {
let playInterval = this.state.playInterval;
if (!playInterval) {
playInterval = setInterval(() => {
this.advanceFrame(1);
}, 1000 / this.props.playbackFrameRate);
} else {
clearInterval(playInterval);
playInterval = 0;
}
this.setState({playInterval} as any);
}
advanceGroup(delta) {
let activeGroup = this.state.activeGroup + delta;
if (activeGroup < 0) {
activeGroup += this.props.groups.length;
}
activeGroup = activeGroup % this.props.groups.length;
this.setActiveGroup(activeGroup);
}
advanceFrame(delta) {
let activeFrame = this.state.activeFrame + delta;
if (activeFrame < 0) {
activeFrame += this.props.groups[0].length;
}
activeFrame = activeFrame % this.props.groups[0].length;
this.setActiveFrame(activeFrame);
}
zoom(value) {
let scale = this.state.scale * value;
this.setState({ scale } as any);
}
installKeyboardShortcuts() {
let playInterval;
Mousetrap.bind(['`'], (e) => {
this.setState({ showFrameComment: !this.state.showFrameComment } as any);
e.preventDefault();
});
Mousetrap.bind(['enter'], (e) => {
this.activeGroupScore[this.state.activeFrame][this.state.activeGroup] = 1;
this.forceUpdate();
e.preventDefault();
});
Mousetrap.bind(['space'], (e) => {
this.playPause();
e.preventDefault();
});
Mousetrap.bind(['.'], (e) => {
this.advanceFrame(1);
e.preventDefault();
});
Mousetrap.bind([','], () => {
this.advanceFrame(-1);
});
Mousetrap.bind(['='], (e) => {
this.advanceGroup(1);
e.preventDefault();
});
Mousetrap.bind(['-'], () => {
this.advanceGroup(-1);
});
Mousetrap.bind([']'], () => {
this.zoom(2);
});
Mousetrap.bind(['['], () => {
this.zoom(1 / 2);
});
Mousetrap.bind(['r'], () => {
this.resetLayersAndActiveFrame();
});
Mousetrap.bind(['tab'], (e) => {
this.toggleTools();
e.preventDefault();
});
Mousetrap.bind(['z'], (e) => {
this.setState({showLayersInZoom: !this.state.showLayersInZoom} as any);
e.preventDefault();
});
Mousetrap.bind(['x'], (e) => {
this.setState({lockSelection: !this.state.lockSelection} as any);
e.preventDefault();
});
let self = this;
function toggle(name, event) {
self.toggleLayer(name);
event.preventDefault();
}
let installedKeys = {};
for (let name in this.options) {
let option = this.options[name];
if (option.key) {
if (installedKeys[option.key]) {
console.error("Key: " + option.key + " for " + option.description + ", is already mapped to " + installedKeys[option.key].description);
}
installedKeys[option.key] = option;
Mousetrap.bind([option.key], toggle.bind(this, name));
}
}
function toggleFrame(i) {
this.setActiveGroup(i);
}
for (let i = 1; i <= this.props.groups.length; i++) {
Mousetrap.bind([String(i)], toggleFrame.bind(this, i - 1));
}
}
setActiveGroup(activeGroup) {
this.setState({ activeGroup } as any);
}
setActiveFrame(activeFrame) {
this.setState({ activeFrame } as any);
}
setActiveGroupAndFrame(activeGroup, activeFrame) {
this.setState({ activeGroup, activeFrame } as any);
}
toggleTools() {
if (this.props.blind) {
return;
}
this.setState({ showTools: !this.state.showTools, layerMenuIsOpen: false } as any);
}
resetLayers() {
let o: any = {};
for (let name in this.options) {
o[name] = false;
}
o.showDecodedImage = true;
this.setState(o as any);
}
resetLayersAndActiveFrame() {
let o: any = {};
o.activeFrame = 0;
o.activeGroup = 0;
this.setState(o as any);
this.resetLayers();
}
toggleLayer(name) {
let o = {};
o[name] = !this.state[name];
this.setState(o as any);
}
onMouseDown(event: MouseEvent) {
this.handleMouseEvent(event, true);
}
onMouseMove(event: MouseEvent) {
this.handleMouseEvent(event, false);
}
handleMouseEvent(event: MouseEvent, click: boolean) {
function getMousePosition(canvas: HTMLCanvasElement, event: MouseEvent) {
let rect = canvas.getBoundingClientRect();
return new Vector(
event.clientX - rect.left,
event.clientY - rect.top
);
}
if (click || !this.state.lockSelection) {
this.mousePosition = getMousePosition(this.overlayCanvas, event);
this.mouseZoomPosition = this.mousePosition;
this.updateBlockInfo();
}
}
getMIBlockSize(frame: AnalyzerFrame, c: number, r: number): number {
let blockSize = frame.json["blockSize"];
if (!blockSize) {
return undefined;
}
if (r >= blockSize.length || r < 0) {
return undefined;
}
if (c >= blockSize[r].length || c < 0) {
return undefined;
}
return blockSize[r][c];
}
getParentMIPosition(frame: AnalyzerFrame, v: Vector): Vector {
let p = this.getMIPosition(frame, v);
let c = p.x;
let r = p.y;
let size = this.getMIBlockSize(frame, c, r);
if (size === undefined) {
return null;
}
c = c & ~(((1 << frame.blockSizeLog2Map[size][0]) - 1) >> frame.miSizeLog2);
r = r & ~(((1 << frame.blockSizeLog2Map[size][1]) - 1) >> frame.miSizeLog2);
return new Vector(c, r);
}
getParentMIRect(frame: AnalyzerFrame, v: Vector): Rectangle {
let p = this.getMIPosition(frame, v);
let c = p.x;
let r = p.y;
let size = this.getMIBlockSize(frame, c, r);
if (size === undefined) {
return null;
}
const miSizeLog2 = frame.miSizeLog2;
const log2Map = frame.blockSizeLog2Map[size];
c = c & ~(((1 << log2Map[0]) - 1) >> miSizeLog2);
r = r & ~(((1 << log2Map[1]) - 1) >> miSizeLog2);
return new Rectangle((c << miSizeLog2), (r << miSizeLog2), 1 << log2Map[0], 1 << log2Map[1]);
}
/**
* Calculate MI coordinates.
*/
getMIPosition(frame: AnalyzerFrame, v: Vector): Vector {
const miSizeLog2 = frame.miSizeLog2;
let c = (v.x / this.state.scale) >> miSizeLog2;
let r = (v.y / this.state.scale) >> miSizeLog2;
return new Vector(c, r);
}
getActiveFrame(): AnalyzerFrame {
return this.props.groups[this.state.activeGroup][this.state.activeFrame];
}
getActiveGroup(): AnalyzerFrame[] {
return this.props.groups[this.state.activeGroup];
}
updateBlockInfo() {
this.forceUpdate();
}
getSymbolHist(frames: AnalyzerFrame[]): Histogram[] {
let data = [];
let names = Accounting.getSortedSymbolNames(frames.map(frame => frame.accounting));
frames.forEach((frame, i) => {
let row = { frame: i, total: 0 };
let symbols = frame.accounting.createFrameSymbols();
let total = 0;
names.forEach(name => {
let symbol = symbols[name];
let bits = symbol ? symbol.bits : 0;
total += bits;
});
names.forEach((name, i) => {
let symbol = symbols[name];
let bits = symbol ? symbol.bits : 0;
row[i] = bits;
});
data.push(row);
});
let nameMap = {};
names.forEach((name, i) => {
nameMap[name] = i;
});
return data.map(data => new Histogram(data, nameMap));
}
onBitsScaleSelect(eventKey: any, event: Object) {
let showBitsScale = eventKey;
this.setState({ showBitsScale } as any);
}
onBitsModeSelect(eventKey: any, event: Object) {
let showBitsMode = eventKey;
this.setState({ showBitsMode } as any);
}
onBitsFilterSelect(eventKey: any, event: Object) {
let showBitsFilter = eventKey;
this.setState({ showBitsFilter } as any);
}
getActiveGroupScore() {
let s = 0;
let j = this.state.activeGroup;
for (let i = 0; i < this.activeGroupScore.length; i++) {
s += this.activeGroupScore[i][j];
}
return s;
}
downloadImage() {
this.downloadLink.href = this.frameCanvas.toDataURL("image/png");
this.downloadLink.download = "frame.png";
if (this.downloadLink.href as any != document.location) {
this.downloadLink.click();
}
}
alertDecodeAdditionalFrames(count: number) {
if (count <= 5) {
if (this.props.onDecodeAdditionalFrames) {
this.props.onDecodeAdditionalFrames(count);
}
} else {
this.setState({
showDecodeDialog: true,
decodeFrameCount: count
} as any);
}
}
analyze() {
window.location.reload();
}
decodeAdditionalFrames(value: boolean) {
this.setState({
showDecodeDialog: false
} as any);
if (value) {
let count = this.state.decodeFrameCount;
if (this.props.onDecodeAdditionalFrames) {
this.props.onDecodeAdditionalFrames(count);
}
}
}
getHistogram(tab: HistogramTab, frames: AnalyzerFrame[]): Histogram[] {
switch (tab) {
case HistogramTab.Bits:
case HistogramTab.Symbols:
return this.getSymbolHist(frames);
case HistogramTab.BlockSize:
return frames.map(x => x.blockSizeHist);
case HistogramTab.TransformSize:
return frames.map(x => x.transformSizeHist);
case HistogramTab.TransformType:
return frames.map(x => x.transformTypeHist);
case HistogramTab.PredictionMode:
return frames.map(x => x.predictionModeHist);
case HistogramTab.UVPredictionMode:
return frames.map(x => x.uvPredictionModeHist);
case HistogramTab.Skip:
return frames.map(x => x.skipHist);
case HistogramTab.DualFilterType:
return frames.map(x => x.dualFilterTypeHist);
}
return null;
}
getHistogramColor(tab: HistogramTab, name: string) {
let color = null;
switch (tab) {
case HistogramTab.BlockSize:
color = getColor(name, palette.blockSize);
break;
case HistogramTab.TransformSize:
color = getColor(name, palette.transformSize);
break;
case HistogramTab.TransformType:
color = getColor(name, palette.transformType);
break;
case HistogramTab.PredictionMode:
case HistogramTab.UVPredictionMode:
color = getColor(name, palette.predictionMode);
break;
case HistogramTab.Skip:
color = getColor(name, palette.skip);
break;
case HistogramTab.DualFilterType:
color = getColor(name, palette.dualFilterType);
break;
default:
color = getColor(name);
}
return color;
}
showLayerMenu(event) {
this.setState({
layerMenuIsOpen: true,
} as any);
}
hideLayerMenu(event) {
this.setState({
layerMenuIsOpen: false,
} as any);
}
getGroupName(group: number): string {
return this.props.groupNames ? this.props.groupNames[group] : String(group);
}
getActiveFrameConfig() {
// Ignore default options.
let defaultOptions = DEFAULT_CONFIG.split(" ");
let options = this.getActiveFrame().config.split(" ");
return options.filter(option => defaultOptions.indexOf(option) < 0).join(" ");
}
downloadIvf() {
document.location = this.props.decoderVideoUrlPairs[this.state.activeGroup].videoUrl;
}
downloadY4m() {
let decoder = this.props.decoderVideoUrlPairs[this.state.activeGroup].decoderUrl;
let file = this.props.decoderVideoUrlPairs[this.state.activeGroup].videoUrl;
window.open("?download=1&decoder=" + encodeURIComponent(decoder) + "&file=" + encodeURIComponent(file),'_blank');
}
render() {
let sidePanel = null;
let frames = this.props.groups[this.state.activeGroup];
let frame = this.getActiveFrame();
if (this.state.showTools) {
if (frame) {
let accounting = this.getActiveFrame().accounting;
let p = this.getParentMIPosition(frame, this.mousePosition);
let bitLayerToolbar = null;
if (this.state.showBits) {
let names = Accounting.getSortedSymbolNames(frames.map(frame => frame.accounting));
bitLayerToolbar = <Toolbar>
<div>
<Select style={{ width: '150px' }} value={this.state.showBitsScale} onChange={(event) => this.setState({ showBitsScale: event.target.value } as any)}>
<MenuItem value="frame">Frame Relative</MenuItem>
<MenuItem value="video">Video Relative</MenuItem>
<MenuItem value="videos">Video Relative (all)</MenuItem>
</Select>
<Select style={{ width: '150px' }} value={this.state.showBitsMode} onChange={(event) => this.setState({ showBitsMode: event.target.value } as any)}>
<MenuItem value="linear">Single Color</MenuItem>
<MenuItem value="heat">Heat Map</MenuItem>
<MenuItem value="heat-opaque">Heat Map (Opaque)</MenuItem>
</Select>
<Select style={{ width: '150px' }} value={this.state.showBitsFilter} onChange={(event) => this.setState({ showBitsFilter: event.target.value } as any)}>
<MenuItem value="">None</MenuItem>
{
names.map(name => <MenuItem key={name} value={name}>{name}</MenuItem>)
}
</Select>
</div>
</Toolbar>
}
let groupTabs = null;
if (this.props.groups.length > 1) {
let tabs = [];
for (let i = 0; i < this.props.groups.length; i++) {
tabs.push(<Tab key={i} label={i + 1} value={i} />);
}
groupTabs = <div><Tabs value={this.state.activeGroup} onChange={(value) => {
this.setState({
activeGroup: value,
} as any);
}}>{tabs}</Tabs>
</div>
}
let layerMenuItems = [];
for (let name in this.options) {
let option = this.options[name];
layerMenuItems.push(
<MenuItem key={name} onClick={this.toggleLayer.bind(this, name)} style={{ justifyContent: 'space-between', backgroundColor: this.state[name] ? grey[500] : undefined }}>
<Typography>{option.description}</Typography><Typography>{option.key.toUpperCase()}</Typography>
</MenuItem>
);
}
sidePanel = <div id="sidePanel">
<Dialog
open={this.state.showShareUrlDialog}
>
<DialogTitle>Share URL</DialogTitle>
<DialogContent>
<TextField defaultValue={this.state.shareUrl} />
</DialogContent>
<DialogActions>
<Button
color="primary"
onClick={() => { this.setState({showShareUrlDialog: false} as any) }}
>Ok</Button>
</DialogActions>
</Dialog>
<Alert
open={this.state.showDecodeDialog}
onClose={this.decodeAdditionalFrames.bind(this)}
title={`Decode ${this.state.decodeFrameCount} Frame(s)?`}
description="Frames will be decoded in the background and may take a while."
/>
{groupTabs}
<div className="activeContent">
Frame: {padLeft(this.state.activeFrame + 1, 2)}, Group: {this.getGroupName(this.state.activeGroup)} {this.getActiveFrameConfig()}
</div>
<Toolbar disableGutters={true} variant="dense">
<div>
<Tooltip title="Layers">
<IconButton ref={this.layerMenuAnchorEl} onClick={this.showLayerMenu.bind(this)}>
<LayersIcon />
</IconButton>
</Tooltip>
<Menu
open={this.state.layerMenuIsOpen}
onClose={this.hideLayerMenu.bind(this)}
anchorEl={this.layerMenuAnchorEl.current}
style={{ width: '320px', marginTop: '48px' }}
>
{layerMenuItems}
<Divider />
<MenuItem onClick={this.resetLayers.bind(this, name)}>Reset Layers</MenuItem>
</Menu>
<Tooltip title="Save Image">
<IconButton onClick={this.downloadImage.bind(this)}>
<ImageIcon />
</IconButton>
</Tooltip>
<Tooltip title="Reset: r">
<IconButton onClick={this.resetLayersAndActiveFrame.bind(this)}>
<ClearIcon />
</IconButton>
</Tooltip>
<Tooltip title="Previous: ,">
<IconButton onClick={this.advanceFrame.bind(this, -1)}>
<SkipPreviousIcon />
</IconButton>
</Tooltip>
<Tooltip title="Pause / Play: space">
<IconButton onClick={this.playPause.bind(this)}>
{!this.state.playInterval ? <PlayArrowIcon /> : <StopIcon />}
</IconButton>
</Tooltip>
<Tooltip title="Next: .">
<IconButton onClick={this.advanceFrame.bind(this, 1)}>
<SkipNextIcon />
</IconButton>
</Tooltip>
<Tooltip title="Zoom Out: [">
<IconButton onClick={this.zoom.bind(this, 1 / 2)}>
<ZoomOutIcon />
</IconButton>
</Tooltip>
<Tooltip title="Zoom In: ]">
<IconButton onClick={this.zoom.bind(this, 2)}>
<ZoomInIcon />
</IconButton>
</Tooltip>
<Tooltip title="Decode 30 Additional Frames">
<IconButton onClick={this.alertDecodeAdditionalFrames.bind(this, 30)}>
<Replay30Icon />
</IconButton>
</Tooltip>
<Tooltip title="Share Link">
<IconButton onClick={this.shareLink.bind(this)}>
<ShareIcon />
</IconButton>
</Tooltip>
</div>
</Toolbar>
{bitLayerToolbar}
<Tabs value={this.state.activeTab} onChange={(event, newValue) => {
this.setState({
activeTab: newValue
});
}} variant="fullWidth">
<Tab style={{ minWidth: 'auto', padding: '0' }} value={0} label="Zoom"/>
<Tab style={{ minWidth: 'auto', padding: '0' }} value={1} label="Histograms"/>
<Tab style={{ minWidth: 'auto', padding: '0' }} value={2} label="Block Info"/>
<Tab style={{ minWidth: 'auto', padding: '0' }} value={3} label="Frame Info"/>
<Tab style={{ minWidth: 'auto', padding: '0' }} value={4} label="More"/>
</Tabs>
{this.state.activeTab === 0 && <div>
<canvas ref={(self: any) => this.resetZoomCanvas(self)} width="256" height="256"/>
<div className="tabContent">
<FormGroup row>
<FormControlLabel control={<Checkbox
checked={this.state.showLayersInZoom}
onChange={(event) => this.setState({ showLayersInZoom: event.target.checked })}
/>} label="Show Layers in Zoom: Z" />
</FormGroup>
<FormGroup row>
<FormControlLabel control={<Checkbox
checked={this.state.lockSelection}
onChange={(event) => this.setState({ lockSelection: event.target.checked })}
/>} label="Lock Selection: X" />
</FormGroup>
<div className="componentHeader">Layer Alpha</div>
<Slider min={0} max={1} step={0.1} defaultValue={1} value={this.state.layerAlpha}
onChange={(event, value) => {
this.setState({layerAlpha: value} as any);
}}
/>
</div>
</div>}
{this.state.activeTab === 1 && <div>
<Toolbar>
<div>
<Select value={this.state.activeHistogramTab} onChange={(event) => this.setState({ activeHistogramTab: event.target.value } as any)}>
<MenuItem value={HistogramTab.Bits}>Bits</MenuItem>
<MenuItem value={HistogramTab.Symbols}>Symbols</MenuItem>
<MenuItem value={HistogramTab.BlockSize}>Block Size</MenuItem>
<MenuItem value={HistogramTab.TransformSize}>Transform Size</MenuItem>
<MenuItem value={HistogramTab.TransformType}>Transform Type</MenuItem>
<MenuItem value={HistogramTab.PredictionMode}>Prediction Mode</MenuItem>
<MenuItem value={HistogramTab.UVPredictionMode}>UV Prediction Mode</MenuItem>
<MenuItem value={HistogramTab.Skip}>Skip</MenuItem>
<MenuItem value={HistogramTab.DualFilterType}>Dual Filter Type</MenuItem>
</Select>
</div>
</Toolbar>
<HistogramComponent
histograms={this.getHistogram(this.state.activeHistogramTab, frames)}
color={this.getHistogramColor.bind(this, this.state.activeHistogramTab)}
highlight={this.state.activeFrame}
height={512} width={500}
scale={this.state.activeHistogramTab == 0 ? "max" : undefined}
></HistogramComponent>
</div>}
{p && this.state.activeTab === 2 && <div>
<ModeInfoComponent frame={frame} position={p}></ModeInfoComponent>
<AccountingComponent symbols={this.getActiveFrame().accounting.createBlockSymbols(p.x, p.y)}></AccountingComponent>
</div>}
{this.state.activeTab === 3 && <div>
<FrameInfoComponent frame={frame} activeFrame={this.state.activeFrame} activeGroup={this.state.activeGroup}></FrameInfoComponent>
<AccountingComponent symbols={accounting.frameSymbols}></AccountingComponent>
</div>}
{this.state.activeTab === 4 && <div className="tabContent">
<Button variant="contained" color="primary" onClick={this.fileIssue.bind(this, "enhancement")}>Feature Request</Button>{' '}
<Button variant="contained" color="secondary" onClick={this.fileIssue.bind(this, "bug")}>File a Bug</Button>
<p><Button variant="contained" onClick={this.downloadIvf.bind(this)}>Download this video (ivf)</Button></p>
<p><Button variant="contained" onClick={this.downloadY4m.bind(this)}>Download this video (y4m)</Button></p>
<h3>Configuration</h3>
<p>
{frame.config}
</p>
<h3>Tips</h3>
<ul>
<li>Click anywhere on the image to lock focus and get mode info details.</li>
<li>All analyzer features have keyboard shortcuts, use them.</li>
<li>Toggle between video sequences by using the number keys: 1, 2, 3, etc.</li>
</ul>
</div>}
</div>
}
}
let activeGroup = this.state.activeGroup;
let groupName = this.props.groupNames ? this.props.groupNames[activeGroup] : String(activeGroup);
let result = <div className="maxWidthAndHeight">
<a style={{ display: "none" }} ref={(self: any) => this.downloadLink = self} />
{this.state.showFrameComment &&
<div id="frameComment">
<div>
<div className="sectionHeader">Config</div>
<div className="propertyValue">{this.getActiveFrame().config}</div>
<div className="sectionHeader">Video</div>
<div className="propertyValue">{groupName}</div>
<div className="sectionHeader">Group</div>
<div className="propertyValue">{activeGroup}: {this.props.groupNames[activeGroup]}</div>
<div className="sectionHeader">Score</div>
<div className="propertyValue">{this.getActiveGroupScore()}</div>
<div className="sectionHeader">Frame</div>
<div className="propertyValue">{this.state.activeFrame}</div>
</div>
</div>
}
<div className="rootContainer">
<div className="contentContainer">
<div className="canvasContainer" ref={(self: any) => this.canvasContainer = self}>
<canvas ref={(self: any) => this.displayCanvas = self} width="256" height="256" style={{ position: "absolute", left: 0, top: 0, zIndex: 0, imageRendering: "pixelated" }}></canvas>
<canvas ref={(self: any) => this.overlayCanvas = self} width="256" height="256" style={{ position: "absolute", left: 0, top: 0, zIndex: 1, imageRendering: "pixelated", cursor: "crosshair", opacity: this.state.layerAlpha }}></canvas>
</div>
</div>
{sidePanel}
</div>
</div>
return result;
}
drawSkip(frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle) {
let skipGrid = frame.json["skip"];
let skipMap = frame.json["skipMap"];
this.fillBlock(frame, ctx, src, dst, (blockSize, c, r, sc, sr) => {
let v = skipGrid[r][c];
if (v == skipMap.NO_SKIP) {
return false;
}
ctx.fillStyle = palette.skip.SKIP;
return true;
});
}
drawFilters(frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle) {
let dualFilterTypeGrid = frame.json["dualFilterType"];
if (!dualFilterTypeGrid) return;
let dualFilterTypeMapByValue = reverseMap(frame.json["dualFilterTypeMap"]);
this.fillBlock(frame, ctx, src, dst, (blockSize, c, r, sc, sr) => {
ctx.fillStyle = getColor(dualFilterTypeMapByValue[dualFilterTypeGrid[r][c]], palette.dualFilterType);
return true;
});
}
drawCDEF(frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle) {
let skipGrid = frame.json["skip"];
if (!skipGrid) return;
let rows = skipGrid.length;
let cols = skipGrid[0].length;
function allSkip(c: number, r: number) {
let s = 1 << (frame.miSuperSizeLog2 - frame.miSizeLog2);
for (let y = 0; y < s; y++) {
for (let x = 0; x < s; x++) {
if (r + y >= rows || c + x >= cols) {
continue;
}
if (!skipGrid[r + y][c + x]) {
return false;
}
}
}
return true;
}
let levelGrid = frame.json["cdef_level"];
let strengthGrid = frame.json["cdef_strength"];
if (!levelGrid) return;
if (!strengthGrid) return;
ctx.globalAlpha = 0.2;
this.fillBlock(frame, ctx, src, dst, (blockSize, c, r, sc, sr) => {
if (allSkip(c, r)) {
return;
}
let v = levelGrid[r][c] + strengthGrid[r][c];
if (!v) {
return false;
}
ctx.fillStyle = colorScale(v / (DERING_STRENGTHS + CLPF_STRENGTHS), HEAT_COLORS);
return true;
}, VisitMode.SuperBlock);
ctx.globalAlpha = 1;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "white";
ctx.font = String(8 * this.ratio) + "pt Courier New";
this.drawBlock(frame, ctx, src, dst, (blockSize, c, r, sc, sr, bounds, scale) => {
if (allSkip(c, r)) {
return;
}
let s = strengthGrid[r][c];
let l = levelGrid[r][c];
let o = bounds.getCenter();
ctx.fillText(l + "/" + s, o.x, o.y);
return true;
}, VisitMode.SuperBlock);
}
drawReferenceFrames(frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle) {
let referenceGrid = frame.json["referenceFrame"];
let referenceMapByValue = reverseMap(frame.json["referenceFrameMap"]);
const triangles = true;
this.drawBlock(frame, ctx, src, dst, (blockSize, c, r, sc, sr, bounds) => {
ctx.save();
if (referenceGrid[r][c][0] >= 0) {
ctx.fillStyle = getColor(referenceMapByValue[referenceGrid[r][c][0]], palette.referenceFrame);
if (triangles) {
ctx.beginPath();
ctx.moveTo(bounds.x, bounds.y);
ctx.lineTo(bounds.x + bounds.w, bounds.y);
ctx.lineTo(bounds.x, bounds.y + bounds.h);
ctx.fill();
} else {
ctx.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
}
}
if (referenceGrid[r][c][1] >= 0) {
ctx.fillStyle = getColor(referenceMapByValue[referenceGrid[r][c][1]], palette.referenceFrame);
if (triangles) {
ctx.beginPath();
ctx.moveTo(bounds.x + bounds.w, bounds.y);
ctx.lineTo(bounds.x + bounds.w, bounds.y + bounds.h);
ctx.lineTo(bounds.x, bounds.y + bounds.h);
ctx.fill();
} else {
ctx.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
}
}
ctx.restore();
return true;
});
}
drawMotionVectors(frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle) {
let motionVectorsGrid = frame.json["motionVectors"];
let scale = dst.w / src.w;
let scaledFrameSize = this.frameSize.clone().multiplyScalar(scale);
ctx.save();
ctx.globalAlpha = 1;
let aColor = "red";
let bColor = "blue";
ctx.fillStyle = aColor;
ctx.lineWidth = scale / 2;
ctx.translate(-src.x * scale, -src.y * scale);
this.visitBlocks(VisitMode.Block, frame, (blockSize, c, r, sc, sr, bounds) => {
bounds.multiplyScalar(scale);
let o = bounds.getCenter();
let m = motionVectorsGrid[r][c];
let a = new Vector(m[0], m[1])
let b = new Vector(m[2], m[3])
if (a.length() > 0) {
ctx.globalAlpha = Math.min(0.3, a.length() / 128);
ctx.fillStyle = aColor;
ctx.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
}
if (b.length() > 0) {
ctx.globalAlpha = Math.min(0.3, b.length() / 128);
ctx.fillStyle = bColor;
ctx.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
}
a.divideScalar(8 / scale);
let va = o.clone().add(a);
b.divideScalar(8 / scale);
let vb = o.clone().add(b);
// Draw small vectors with a ligher color.
ctx.globalAlpha = Math.max(0.2, Math.min(a.length() + b.length(), 1));
ctx.strokeStyle = aColor;
drawVector(ctx, o, va);
ctx.strokeStyle = bColor;
drawVector(ctx, o, vb);
// Draw Dot
ctx.beginPath();
ctx.arc(o.x, o.y, scale / 2, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
});
ctx.restore();
}
drawSegment(frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle) {
let segGrid = frame.json["seg_id"];
let segMapByValue = reverseMap(frame.json["seg_idMap"]);
this.fillBlock(frame, ctx, src, dst, (blockSize, c, r, sc, sr) => {
ctx.fillStyle = getColor(segGrid[r][c], palette.seg_id);
return true;
});
}
drawTransformType(frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle) {
let typeGrid = frame.json["transformType"];
let transformTypeMapByValue = reverseMap(frame.json["transformTypeMap"]);
this.fillBlock(frame, ctx, src, dst, (blockSize, c, r, sc, sr) => {
ctx.fillStyle = getColor(transformTypeMapByValue[typeGrid[r][c]], palette.transformType);
return true;
});
}
drawBits(frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle) {
let { blocks, total } = frame.accounting.countBits(this.state.showBitsFilter);
function getBits(blocks, c, r) {
if (!blocks[r]) {
return 0;
}
return blocks[r][c] | 0;
}
let maxBitsPerPixel = 0;
if (this.state.showBitsScale == "frame") {
this.visitBlocks(VisitMode.Block, frame, (blockSize, c, r, sc, sr, bounds) => {
let area = blockSizeArea(frame, blockSize);
let bits = getBits(blocks, c, r);
maxBitsPerPixel = Math.max(maxBitsPerPixel, bits / area);
});
} else {
let groups = this.state.showBitsScale === "video" ? [this.getActiveGroup()] : this.props.groups;
groups.forEach(frames => {
frames.forEach(frame => {
let { blocks } = frame.accounting.countBits(this.state.showBitsFilter);
this.visitBlocks(VisitMode.Block, frame, (blockSize, c, r, sc, sr, bounds) => {
let area = blockSizeArea(frame, blockSize);
let bits = getBits(blocks, c, r);
maxBitsPerPixel = Math.max(maxBitsPerPixel, bits / area);
});
});
});
}
this.fillBlock(frame, ctx, src, dst, (blockSize, c, r, sc, sr) => {
let area = blockSizeArea(frame, blockSize);
let bits = getBits(blocks, c, r);
let value = (bits / area) / maxBitsPerPixel;
let mode = this.state.showBitsMode;
if (mode == "linear") {
ctx.globalAlpha = value;
ctx.fillStyle = "#9400D3";
} else if (mode == "heat") {
ctx.globalAlpha = value;
ctx.fillStyle = colorScale(value, HEAT_COLORS);
} else if (mode == "heat-opaque") {
ctx.globalAlpha = 1;
ctx.fillStyle = colorScale(value, HEAT_COLORS);
}
return true;
});
}
drawMode(type: string, frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle) {
let skipGrid = frame.json["skip"];
let modeGrid = frame.json[type];
let modeMap = frame.json["modeMap"];
let uvModeMap = frame.json["uv_modeMap"];
let alphaIndex = frame.json["cfl_alpha_idx"];
let modeMapByValue = reverseMap(modeMap);
const V_PRED = modeMap.V_PRED;
const H_PRED = modeMap.H_PRED;
const D45_PRED = modeMap.D45_PRED;
const D67_PRED = modeMap.D67_PRED;
const D135_PRED = modeMap.D135_PRED;
const D113_PRED = modeMap.D113_PRED;
const D157_PRED = modeMap.D157_PRED;
const D203_PRED = modeMap.D203_PRED;
const DC_PRED = modeMap.DC_PRED;
const UV_CFL_PRED = uvModeMap.UV_CFL_PRED;
let scale = dst.w / src.w;
ctx.save();
ctx.lineWidth = 1;
ctx.strokeStyle = "white";
let lineOffset = getLineOffset(1);
ctx.translate(lineOffset, lineOffset);
ctx.translate(-src.x * scale, -src.y * scale);
let lineWidth = 1;
ctx.lineWidth = lineWidth;
ctx.globalAlpha = 1;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = String(6 * this.ratio) + "pt Courier New";
this.visitBlocks(VisitMode.Block, frame, (blockSize, c, r, sc, sr, bounds) => {
bounds.multiplyScalar(scale);
drawMode(modeGrid[r][c], bounds);
if (alphaIndex && type === "uv_mode" && modeGrid[r][c] === UV_CFL_PRED) {
if (bounds.w < 16 * this.ratio || bounds.h < 16 * this.ratio) {
return;
}
let o = bounds.getCenter();
let cfl_alpha_idx = frame.json["cfl_alpha_idx"][r][c];
let cfl_alpha_sign = frame.json["cfl_alpha_sign"][r][c];
let [cfl_alpha_u, cfl_alpha_v] = toCflAlphas(cfl_alpha_idx, cfl_alpha_sign);
ctx.fillStyle = "black";
ctx.fillText(`${cfl_alpha_u}`, o.x, o.y - 4 * this.ratio);
ctx.fillText(`${cfl_alpha_v}`, o.x, o.y + 4 * this.ratio);
}
});
function drawMode(m: number, bounds: Rectangle) {
let x = bounds.x;
let y = bounds.y;
let w = bounds.w;
let h = bounds.h;
let hw = w / 2;
let hh = h / 2;
ctx.fillStyle = getColor(modeMapByValue[m], palette.predictionMode);
ctx.fillRect(x, y, w, h);
switch (m) {
case V_PRED:
drawLine(ctx, x + hw + lineOffset, y, 0, h);
break;
case H_PRED:
drawLine(ctx, x, y + hh + lineOffset, w, 0);
break;
case D45_PRED:
drawLine(ctx, x, y + h, w, -h);
break;
case D67_PRED:
drawLine(ctx, x, y + h, hw, -h);
break;
case D135_PRED:
drawLine(ctx, x, y, w, h);
break;
case D113_PRED:
drawLine(ctx, x + hw, y, hw, h);
break;
case D157_PRED:
drawLine(ctx, x, y + hh, w, hh);
break;
case D203_PRED:
drawLine(ctx, x, y + hh, w, -hh);
break;
default:
break;
}
}
ctx.restore();
}
fillBlock(frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle, setFillStyle: (blockSize: number, c: number, r: number, sc: number, sr: number) => boolean, mode = VisitMode.Block) {
this.drawBlock(frame, ctx, src, dst, (blockSize, c, r, sc, sr, bounds, scale) => {
if (setFillStyle(blockSize, c, r, sc, sr)) {
ctx.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
}
}, mode);
}
drawBlock(frame: AnalyzerFrame, ctx: CanvasRenderingContext2D, src: Rectangle, dst: Rectangle, visitor: BlockVisitor, mode = VisitMode.Block) {
let scale = dst.w / src.w;
ctx.save();
ctx.translate(-src.x * scale, -src.y * scale);
this.visitBlocks(mode, frame, (blockSize, c, r, sc, sr, bounds) => {
bounds.multiplyScalar(scale);
visitor(blockSize, c, r, sc, sr, bounds, scale);
});
ctx.restore();
}
/**
* A variety of ways to visit the grid.
*/
visitBlocks(mode: VisitMode, frame: AnalyzerFrame, visitor: BlockVisitor) {
const blockSizeGrid = frame.json["blockSize"];
const miSizeLog2 = frame.miSizeLog2;
const miSuperSizeLog2 = frame.miSuperSizeLog2;
const rect = new Rectangle(0, 0, 0, 0);
const rows = blockSizeGrid.length;
const cols = blockSizeGrid[0].length;
if (mode === VisitMode.Tile) {
let tileCols = frame.json["tileCols"];
let tileRows = frame.json["tileRows"];
if (!tileCols || !tileRows) return;
for (let c = 0; c < cols; c += tileCols) {
for (let r = 0; r < rows; r += tileRows) {
let size = blockSizeGrid[r][c];
visitor(size, c, r, 0, 0, rect.set((c << miSizeLog2), (r << miSizeLog2), (1 << miSizeLog2) * tileCols, (1 << miSizeLog2) * tileRows), 1);
}
}
} else if (mode === VisitMode.SuperBlock) {
for (let c = 0; c < cols; c += 1 << (miSuperSizeLog2 - miSizeLog2)) {
for (let r = 0; r < rows; r += 1 << (miSuperSizeLog2 - miSizeLog2)) {
let size = blockSizeGrid[r][c];
visitor(size, c, r, 0, 0, rect.set((c << miSizeLog2), (r << miSizeLog2), (1 << miSuperSizeLog2), (1 << miSuperSizeLog2)), 1);
}
}
} else if (mode === VisitMode.Block || mode === VisitMode.TransformBlock) {
let allSizes;
let sizeGrid;
if (mode === VisitMode.Block) {
sizeGrid = blockSizeGrid;
allSizes = frame.blockSizeLog2Map;
} else if (mode === VisitMode.TransformBlock) {
sizeGrid = frame.json["transformSize"];
allSizes = frame.transformSizeLog2Map;
} else {
unreachable();
}
// Visit sizes >= MI_SIZE
for (let i = 0; i < allSizes.length; i++) {
const sizeLog2 = allSizes[i];
if (sizeLog2[0] < miSizeLog2 || sizeLog2[1] < miSizeLog2) {
continue;
}
let dc = 1 << (sizeLog2[0] - miSizeLog2);
let dr = 1 << (sizeLog2[1] - miSizeLog2);
for (let r = 0; r < rows; r += dr) {
let sizeGridRow = sizeGrid[r];
for (let c = 0; c < cols; c += dc) {
let size = sizeGridRow[c];
if (size == i) {
let w = dc << miSizeLog2;
let h = dr << miSizeLog2;
visitor(size, c, r, 0, 0, rect.set((c << miSizeLog2), (r << miSizeLog2), w, h), 1);
}
}
}
}
} else {
throw new Error("Can't handle mode: " + mode);
}
}
createSharingLink(): Promise<string> {
return new Promise((resolve, reject) => {
shortenUrl(window.location.href , (url) => {
resolve(url);
});
});
}
shareLink() {
this.createSharingLink().then(link => {
this.setState({showShareUrlDialog: true, shareUrl: link} as any);
});
}
fileIssue(label: string = "") {
this.createSharingLink().then(link => {
window.open("https://github.com/mbebenita/aomanalyzer/issues/new?labels=" + label + "&body=" + encodeURIComponent(link));
});
}
} | the_stack |
import BSON from 'bson';
import {OriginalType, ParquetField, ParquetType, PrimitiveType} from './declare';
export interface ParquetTypeKit {
primitiveType: PrimitiveType;
originalType?: OriginalType;
typeLength?: number;
toPrimitive: Function;
fromPrimitive?: Function;
}
export const PARQUET_LOGICAL_TYPES: Record<ParquetType, ParquetTypeKit> = {
BOOLEAN: {
primitiveType: 'BOOLEAN',
toPrimitive: toPrimitive_BOOLEAN,
fromPrimitive: fromPrimitive_BOOLEAN
},
INT32: {
primitiveType: 'INT32',
toPrimitive: toPrimitive_INT32
},
INT64: {
primitiveType: 'INT64',
toPrimitive: toPrimitive_INT64
},
INT96: {
primitiveType: 'INT96',
toPrimitive: toPrimitive_INT96
},
FLOAT: {
primitiveType: 'FLOAT',
toPrimitive: toPrimitive_FLOAT
},
DOUBLE: {
primitiveType: 'DOUBLE',
toPrimitive: toPrimitive_DOUBLE
},
BYTE_ARRAY: {
primitiveType: 'BYTE_ARRAY',
toPrimitive: toPrimitive_BYTE_ARRAY
},
FIXED_LEN_BYTE_ARRAY: {
primitiveType: 'FIXED_LEN_BYTE_ARRAY',
toPrimitive: toPrimitive_BYTE_ARRAY
},
UTF8: {
primitiveType: 'BYTE_ARRAY',
originalType: 'UTF8',
toPrimitive: toPrimitive_UTF8,
fromPrimitive: fromPrimitive_UTF8
},
TIME_MILLIS: {
primitiveType: 'INT32',
originalType: 'TIME_MILLIS',
toPrimitive: toPrimitive_TIME_MILLIS
},
TIME_MICROS: {
primitiveType: 'INT64',
originalType: 'TIME_MICROS',
toPrimitive: toPrimitive_TIME_MICROS
},
DATE: {
primitiveType: 'INT32',
originalType: 'DATE',
toPrimitive: toPrimitive_DATE,
fromPrimitive: fromPrimitive_DATE
},
TIMESTAMP_MILLIS: {
primitiveType: 'INT64',
originalType: 'TIMESTAMP_MILLIS',
toPrimitive: toPrimitive_TIMESTAMP_MILLIS,
fromPrimitive: fromPrimitive_TIMESTAMP_MILLIS
},
TIMESTAMP_MICROS: {
primitiveType: 'INT64',
originalType: 'TIMESTAMP_MICROS',
toPrimitive: toPrimitive_TIMESTAMP_MICROS,
fromPrimitive: fromPrimitive_TIMESTAMP_MICROS
},
UINT_8: {
primitiveType: 'INT32',
originalType: 'UINT_8',
toPrimitive: toPrimitive_UINT8
},
UINT_16: {
primitiveType: 'INT32',
originalType: 'UINT_16',
toPrimitive: toPrimitive_UINT16
},
UINT_32: {
primitiveType: 'INT32',
originalType: 'UINT_32',
toPrimitive: toPrimitive_UINT32
},
UINT_64: {
primitiveType: 'INT64',
originalType: 'UINT_64',
toPrimitive: toPrimitive_UINT64
},
INT_8: {
primitiveType: 'INT32',
originalType: 'INT_8',
toPrimitive: toPrimitive_INT8
},
INT_16: {
primitiveType: 'INT32',
originalType: 'INT_16',
toPrimitive: toPrimitive_INT16
},
INT_32: {
primitiveType: 'INT32',
originalType: 'INT_32',
toPrimitive: toPrimitive_INT32
},
INT_64: {
primitiveType: 'INT64',
originalType: 'INT_64',
toPrimitive: toPrimitive_INT64
},
JSON: {
primitiveType: 'BYTE_ARRAY',
originalType: 'JSON',
toPrimitive: toPrimitive_JSON,
fromPrimitive: fromPrimitive_JSON
},
BSON: {
primitiveType: 'BYTE_ARRAY',
originalType: 'BSON',
toPrimitive: toPrimitive_BSON,
fromPrimitive: fromPrimitive_BSON
},
INTERVAL: {
primitiveType: 'FIXED_LEN_BYTE_ARRAY',
originalType: 'INTERVAL',
typeLength: 12,
toPrimitive: toPrimitive_INTERVAL,
fromPrimitive: fromPrimitive_INTERVAL
},
DECIMAL_INT32: {
primitiveType: 'INT32',
originalType: 'DECIMAL_INT32',
toPrimitive: decimalToPrimitive_INT32,
fromPrimitive: decimalFromPrimitive_INT
},
DECIMAL_INT64: {
primitiveType: 'INT64',
originalType: 'DECIMAL_INT64',
toPrimitive: decimalToPrimitive_INT64,
fromPrimitive: decimalFromPrimitive_INT
},
DECIMAL_BYTE_ARRAY: {
primitiveType: 'BYTE_ARRAY',
originalType: 'DECIMAL_BYTE_ARRAY',
toPrimitive: decimalToPrimitive_BYTE_ARRAY,
fromPrimitive: decimalFromPrimitive_BYTE_ARRAY
},
DECIMAL_FIXED_LEN_BYTE_ARRAY: {
primitiveType: 'FIXED_LEN_BYTE_ARRAY',
originalType: 'DECIMAL_FIXED_LEN_BYTE_ARRAY',
toPrimitive: decimalToPrimitive_BYTE_ARRAY,
fromPrimitive: decimalFromPrimitive_BYTE_ARRAY
}
};
/**
* Convert a value from it's native representation to the internal/underlying
* primitive type
*/
export function toPrimitive(type: ParquetType, value: any, field?: ParquetField) {
if (!(type in PARQUET_LOGICAL_TYPES)) {
throw new Error(`invalid type: ${type}`);
}
return PARQUET_LOGICAL_TYPES[type].toPrimitive(value, field);
}
/**
* Convert a value from it's internal/underlying primitive representation to
* the native representation
*/
export function fromPrimitive(type: ParquetType, value: any, field?: ParquetField) {
if (!(type in PARQUET_LOGICAL_TYPES)) {
throw new Error(`invalid type: ${type}`);
}
if ('fromPrimitive' in PARQUET_LOGICAL_TYPES[type]) {
return PARQUET_LOGICAL_TYPES[type].fromPrimitive?.(value, field);
// tslint:disable-next-line:no-else-after-return
}
return value;
}
function toPrimitive_BOOLEAN(value: any) {
return Boolean(value);
}
function fromPrimitive_BOOLEAN(value: any) {
return Boolean(value);
}
function toPrimitive_FLOAT(value: any) {
const v = parseFloat(value);
if (isNaN(v)) {
throw new Error(`invalid value for FLOAT: ${value}`);
}
return v;
}
function toPrimitive_DOUBLE(value: any) {
const v = parseFloat(value);
if (isNaN(v)) {
throw new Error(`invalid value for DOUBLE: ${value}`);
}
return v;
}
function toPrimitive_INT8(value: any) {
const v = parseInt(value, 10);
if (v < -0x80 || v > 0x7f || isNaN(v)) {
throw new Error(`invalid value for INT8: ${value}`);
}
return v;
}
function toPrimitive_UINT8(value: any) {
const v = parseInt(value, 10);
if (v < 0 || v > 0xff || isNaN(v)) {
throw new Error(`invalid value for UINT8: ${value}`);
}
return v;
}
function toPrimitive_INT16(value: any) {
const v = parseInt(value, 10);
if (v < -0x8000 || v > 0x7fff || isNaN(v)) {
throw new Error(`invalid value for INT16: ${value}`);
}
return v;
}
function toPrimitive_UINT16(value: any) {
const v = parseInt(value, 10);
if (v < 0 || v > 0xffff || isNaN(v)) {
throw new Error(`invalid value for UINT16: ${value}`);
}
return v;
}
function toPrimitive_INT32(value: any) {
const v = parseInt(value, 10);
if (v < -0x80000000 || v > 0x7fffffff || isNaN(v)) {
throw new Error(`invalid value for INT32: ${value}`);
}
return v;
}
function decimalToPrimitive_INT32(value: number, field: ParquetField) {
const primitiveValue = value * 10 ** (field.scale || 0);
const v = Math.round(((primitiveValue * 10 ** -field.presision!) % 1) * 10 ** field.presision!);
if (v < -0x80000000 || v > 0x7fffffff || isNaN(v)) {
throw new Error(`invalid value for INT32: ${value}`);
}
return v;
}
function toPrimitive_UINT32(value: any) {
const v = parseInt(value, 10);
if (v < 0 || v > 0xffffffffffff || isNaN(v)) {
throw new Error(`invalid value for UINT32: ${value}`);
}
return v;
}
function toPrimitive_INT64(value: any) {
const v = parseInt(value, 10);
if (isNaN(v)) {
throw new Error(`invalid value for INT64: ${value}`);
}
return v;
}
function decimalToPrimitive_INT64(value: number, field: ParquetField) {
const primitiveValue = value * 10 ** (field.scale || 0);
const v = Math.round(((primitiveValue * 10 ** -field.presision!) % 1) * 10 ** field.presision!);
if (isNaN(v)) {
throw new Error(`invalid value for INT64: ${value}`);
}
return v;
}
function toPrimitive_UINT64(value: any) {
const v = parseInt(value, 10);
if (v < 0 || isNaN(v)) {
throw new Error(`invalid value for UINT64: ${value}`);
}
return v;
}
function toPrimitive_INT96(value: any) {
const v = parseInt(value, 10);
if (isNaN(v)) {
throw new Error(`invalid value for INT96: ${value}`);
}
return v;
}
function toPrimitive_BYTE_ARRAY(value: any) {
return Buffer.from(value);
}
function decimalToPrimitive_BYTE_ARRAY(value: any) {
// TBD
return Buffer.from(value);
}
function toPrimitive_UTF8(value: any) {
return Buffer.from(value, 'utf8');
}
function fromPrimitive_UTF8(value: any) {
return value.toString();
}
function toPrimitive_JSON(value: any) {
return Buffer.from(JSON.stringify(value));
}
function fromPrimitive_JSON(value: any) {
return JSON.parse(value);
}
function toPrimitive_BSON(value: any) {
return Buffer.from(BSON.serialize(value));
}
function fromPrimitive_BSON(value: any) {
return BSON.deserialize(value);
}
function toPrimitive_TIME_MILLIS(value: any) {
const v = parseInt(value, 10);
if (v < 0 || v > 0xffffffffffffffff || isNaN(v)) {
throw new Error(`invalid value for TIME_MILLIS: ${value}`);
}
return v;
}
function toPrimitive_TIME_MICROS(value: any) {
const v = parseInt(value, 10);
if (v < 0 || isNaN(v)) {
throw new Error(`invalid value for TIME_MICROS: ${value}`);
}
return v;
}
const kMillisPerDay = 86400000;
function toPrimitive_DATE(value: any) {
/* convert from date */
if (value instanceof Date) {
return value.getTime() / kMillisPerDay;
}
/* convert from integer */
{
const v = parseInt(value, 10);
if (v < 0 || isNaN(v)) {
throw new Error(`invalid value for DATE: ${value}`);
}
return v;
}
}
function fromPrimitive_DATE(value: any) {
return new Date(value * kMillisPerDay);
}
function toPrimitive_TIMESTAMP_MILLIS(value: any) {
/* convert from date */
if (value instanceof Date) {
return value.getTime();
}
/* convert from integer */
{
const v = parseInt(value, 10);
if (v < 0 || isNaN(v)) {
throw new Error(`invalid value for TIMESTAMP_MILLIS: ${value}`);
}
return v;
}
}
function fromPrimitive_TIMESTAMP_MILLIS(value: any) {
return new Date(value);
}
function toPrimitive_TIMESTAMP_MICROS(value: any) {
/* convert from date */
if (value instanceof Date) {
return value.getTime() * 1000;
}
/* convert from integer */
{
const v = parseInt(value, 10);
if (v < 0 || isNaN(v)) {
throw new Error(`invalid value for TIMESTAMP_MICROS: ${value}`);
}
return v;
}
}
function fromPrimitive_TIMESTAMP_MICROS(value: any) {
return new Date(value / 1000);
}
function toPrimitive_INTERVAL(value: any) {
if (!value.months || !value.days || !value.milliseconds) {
throw new Error(
'value for INTERVAL must be object { months: ..., days: ..., milliseconds: ... }'
);
}
const buf = Buffer.alloc(12);
buf.writeUInt32LE(value.months, 0);
buf.writeUInt32LE(value.days, 4);
buf.writeUInt32LE(value.milliseconds, 8);
return buf;
}
function fromPrimitive_INTERVAL(value: any) {
const buf = Buffer.from(value);
const months = buf.readUInt32LE(0);
const days = buf.readUInt32LE(4);
const millis = buf.readUInt32LE(8);
return {months, days, milliseconds: millis};
}
function decimalFromPrimitive_INT(value: any, field: ParquetField) {
const presisionInt = Math.round(((value * 10 ** -field.presision!) % 1) * 10 ** field.presision!);
return presisionInt * 10 ** -(field.scale || 0);
}
function decimalFromPrimitive_BYTE_ARRAY(value: any, field: ParquetField) {
let number = 0;
if (value.length <= 4) {
// Bytewise operators faster. Use them if it is possible
for (let i = 0; i < value.length; i++) {
// `value.length - i - 1` bytes have reverse order (big-endian)
const component = value[i] << (8 * (value.length - i - 1));
number += component;
}
} else {
for (let i = 0; i < value.length; i++) {
// `value.length - i - 1` bytes have reverse order (big-endian)
const component = value[i] * 2 ** (8 * (value.length - 1 - i));
number += component;
}
}
const presisionInt = Math.round(
((number * 10 ** -field.presision!) % 1) * 10 ** field.presision!
);
return presisionInt * 10 ** -(field.scale || 0);
} | the_stack |
declare const enum NLDistanceType {
Cosine = 0
}
declare class NLEmbedding extends NSObject {
static alloc(): NLEmbedding; // inherited from NSObject
static currentRevisionForLanguage(language: string): number;
static currentSentenceEmbeddingRevisionForLanguage(language: string): number;
static embeddingWithContentsOfURLError(url: NSURL): NLEmbedding;
static new(): NLEmbedding; // inherited from NSObject
static sentenceEmbeddingForLanguage(language: string): NLEmbedding;
static sentenceEmbeddingForLanguageRevision(language: string, revision: number): NLEmbedding;
static supportedRevisionsForLanguage(language: string): NSIndexSet;
static supportedSentenceEmbeddingRevisionsForLanguage(language: string): NSIndexSet;
static wordEmbeddingForLanguage(language: string): NLEmbedding;
static wordEmbeddingForLanguageRevision(language: string, revision: number): NLEmbedding;
static writeEmbeddingForDictionaryLanguageRevisionToURLError(dictionary: NSDictionary<string, NSArray<number>>, language: string, revision: number, url: NSURL): boolean;
readonly dimension: number;
readonly language: string;
readonly revision: number;
readonly vocabularySize: number;
containsString(string: string): boolean;
distanceBetweenStringAndStringDistanceType(firstString: string, secondString: string, distanceType: NLDistanceType): number;
enumerateNeighborsForStringMaximumCountDistanceTypeUsingBlock(string: string, maxCount: number, distanceType: NLDistanceType, block: (p1: string, p2: number, p3: interop.Pointer | interop.Reference<boolean>) => void): void;
enumerateNeighborsForStringMaximumCountMaximumDistanceDistanceTypeUsingBlock(string: string, maxCount: number, maxDistance: number, distanceType: NLDistanceType, block: (p1: string, p2: number, p3: interop.Pointer | interop.Reference<boolean>) => void): void;
enumerateNeighborsForVectorMaximumCountDistanceTypeUsingBlock(vector: NSArray<number> | number[], maxCount: number, distanceType: NLDistanceType, block: (p1: string, p2: number, p3: interop.Pointer | interop.Reference<boolean>) => void): void;
enumerateNeighborsForVectorMaximumCountMaximumDistanceDistanceTypeUsingBlock(vector: NSArray<number> | number[], maxCount: number, maxDistance: number, distanceType: NLDistanceType, block: (p1: string, p2: number, p3: interop.Pointer | interop.Reference<boolean>) => void): void;
getVectorForString(vector: interop.Pointer | interop.Reference<number>, string: string): boolean;
neighborsForStringMaximumCountDistanceType(string: string, maxCount: number, distanceType: NLDistanceType): NSArray<string>;
neighborsForStringMaximumCountMaximumDistanceDistanceType(string: string, maxCount: number, maxDistance: number, distanceType: NLDistanceType): NSArray<string>;
neighborsForVectorMaximumCountDistanceType(vector: NSArray<number> | number[], maxCount: number, distanceType: NLDistanceType): NSArray<string>;
neighborsForVectorMaximumCountMaximumDistanceDistanceType(vector: NSArray<number> | number[], maxCount: number, maxDistance: number, distanceType: NLDistanceType): NSArray<string>;
vectorForString(string: string): NSArray<number>;
}
declare class NLGazetteer extends NSObject {
static alloc(): NLGazetteer; // inherited from NSObject
static gazetteerWithContentsOfURLError(url: NSURL): NLGazetteer;
static new(): NLGazetteer; // inherited from NSObject
static writeGazetteerForDictionaryLanguageToURLError(dictionary: NSDictionary<string, NSArray<string>>, language: string, url: NSURL): boolean;
readonly data: NSData;
readonly language: string;
constructor(o: { contentsOfURL: NSURL; });
constructor(o: { data: NSData; });
constructor(o: { dictionary: NSDictionary<string, NSArray<string>>; language: string; });
initWithContentsOfURLError(url: NSURL): this;
initWithDataError(data: NSData): this;
initWithDictionaryLanguageError(dictionary: NSDictionary<string, NSArray<string>>, language: string): this;
labelForString(string: string): string;
}
declare var NLLanguageAmharic: string;
declare var NLLanguageArabic: string;
declare var NLLanguageArmenian: string;
declare var NLLanguageBengali: string;
declare var NLLanguageBulgarian: string;
declare var NLLanguageBurmese: string;
declare var NLLanguageCatalan: string;
declare var NLLanguageCherokee: string;
declare var NLLanguageCroatian: string;
declare var NLLanguageCzech: string;
declare var NLLanguageDanish: string;
declare var NLLanguageDutch: string;
declare var NLLanguageEnglish: string;
declare var NLLanguageFinnish: string;
declare var NLLanguageFrench: string;
declare var NLLanguageGeorgian: string;
declare var NLLanguageGerman: string;
declare var NLLanguageGreek: string;
declare var NLLanguageGujarati: string;
declare var NLLanguageHebrew: string;
declare var NLLanguageHindi: string;
declare var NLLanguageHungarian: string;
declare var NLLanguageIcelandic: string;
declare var NLLanguageIndonesian: string;
declare var NLLanguageItalian: string;
declare var NLLanguageJapanese: string;
declare var NLLanguageKannada: string;
declare var NLLanguageKhmer: string;
declare var NLLanguageKorean: string;
declare var NLLanguageLao: string;
declare var NLLanguageMalay: string;
declare var NLLanguageMalayalam: string;
declare var NLLanguageMarathi: string;
declare var NLLanguageMongolian: string;
declare var NLLanguageNorwegian: string;
declare var NLLanguageOriya: string;
declare var NLLanguagePersian: string;
declare var NLLanguagePolish: string;
declare var NLLanguagePortuguese: string;
declare var NLLanguagePunjabi: string;
declare class NLLanguageRecognizer extends NSObject {
static alloc(): NLLanguageRecognizer; // inherited from NSObject
static dominantLanguageForString(string: string): string;
static new(): NLLanguageRecognizer; // inherited from NSObject
readonly dominantLanguage: string;
languageConstraints: NSArray<string>;
languageHints: NSDictionary<string, number>;
languageHypothesesWithMaximum(maxHypotheses: number): NSDictionary<string, number>;
processString(string: string): void;
reset(): void;
}
declare var NLLanguageRomanian: string;
declare var NLLanguageRussian: string;
declare var NLLanguageSimplifiedChinese: string;
declare var NLLanguageSinhalese: string;
declare var NLLanguageSlovak: string;
declare var NLLanguageSpanish: string;
declare var NLLanguageSwedish: string;
declare var NLLanguageTamil: string;
declare var NLLanguageTelugu: string;
declare var NLLanguageThai: string;
declare var NLLanguageTibetan: string;
declare var NLLanguageTraditionalChinese: string;
declare var NLLanguageTurkish: string;
declare var NLLanguageUkrainian: string;
declare var NLLanguageUndetermined: string;
declare var NLLanguageUrdu: string;
declare var NLLanguageVietnamese: string;
declare class NLModel extends NSObject {
static alloc(): NLModel; // inherited from NSObject
static modelWithContentsOfURLError(url: NSURL): NLModel;
static modelWithMLModelError(mlModel: MLModel): NLModel;
static new(): NLModel; // inherited from NSObject
readonly configuration: NLModelConfiguration;
predictedLabelForString(string: string): string;
predictedLabelHypothesesForStringMaximumCount(string: string, maximumCount: number): NSDictionary<string, number>;
predictedLabelHypothesesForTokensMaximumCount(tokens: NSArray<string> | string[], maximumCount: number): NSArray<NSDictionary<string, number>>;
predictedLabelsForTokens(tokens: NSArray<string> | string[]): NSArray<string>;
}
declare class NLModelConfiguration extends NSObject implements NSCopying, NSSecureCoding {
static alloc(): NLModelConfiguration; // inherited from NSObject
static currentRevisionForType(type: NLModelType): number;
static new(): NLModelConfiguration; // inherited from NSObject
static supportedRevisionsForType(type: NLModelType): NSIndexSet;
readonly language: string;
readonly revision: number;
readonly type: NLModelType;
static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding
constructor(o: { coder: NSCoder; }); // inherited from NSCoding
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
encodeWithCoder(coder: NSCoder): void;
initWithCoder(coder: NSCoder): this;
}
declare const enum NLModelType {
Classifier = 0,
Sequence = 1
}
declare var NLTagAdjective: string;
declare var NLTagAdverb: string;
declare var NLTagClassifier: string;
declare var NLTagCloseParenthesis: string;
declare var NLTagCloseQuote: string;
declare var NLTagConjunction: string;
declare var NLTagDash: string;
declare var NLTagDeterminer: string;
declare var NLTagIdiom: string;
declare var NLTagInterjection: string;
declare var NLTagNoun: string;
declare var NLTagNumber: string;
declare var NLTagOpenParenthesis: string;
declare var NLTagOpenQuote: string;
declare var NLTagOrganizationName: string;
declare var NLTagOther: string;
declare var NLTagOtherPunctuation: string;
declare var NLTagOtherWhitespace: string;
declare var NLTagOtherWord: string;
declare var NLTagParagraphBreak: string;
declare var NLTagParticle: string;
declare var NLTagPersonalName: string;
declare var NLTagPlaceName: string;
declare var NLTagPreposition: string;
declare var NLTagPronoun: string;
declare var NLTagPunctuation: string;
declare var NLTagSchemeLanguage: string;
declare var NLTagSchemeLemma: string;
declare var NLTagSchemeLexicalClass: string;
declare var NLTagSchemeNameType: string;
declare var NLTagSchemeNameTypeOrLexicalClass: string;
declare var NLTagSchemeScript: string;
declare var NLTagSchemeSentimentScore: string;
declare var NLTagSchemeTokenType: string;
declare var NLTagSentenceTerminator: string;
declare var NLTagVerb: string;
declare var NLTagWhitespace: string;
declare var NLTagWord: string;
declare var NLTagWordJoiner: string;
declare class NLTagger extends NSObject {
static alloc(): NLTagger; // inherited from NSObject
static availableTagSchemesForUnitLanguage(unit: NLTokenUnit, language: string): NSArray<string>;
static new(): NLTagger; // inherited from NSObject
static requestAssetsForLanguageTagSchemeCompletionHandler(language: string, tagScheme: string, completionHandler: (p1: NLTaggerAssetsResult, p2: NSError) => void): void;
readonly dominantLanguage: string;
string: string;
readonly tagSchemes: NSArray<string>;
constructor(o: { tagSchemes: NSArray<string> | string[]; });
enumerateTagsInRangeUnitSchemeOptionsUsingBlock(range: NSRange, unit: NLTokenUnit, scheme: string, options: NLTaggerOptions, block: (p1: string, p2: NSRange, p3: interop.Pointer | interop.Reference<boolean>) => void): void;
gazetteersForTagScheme(tagScheme: string): NSArray<NLGazetteer>;
initWithTagSchemes(tagSchemes: NSArray<string> | string[]): this;
modelsForTagScheme(tagScheme: string): NSArray<NLModel>;
setGazetteersForTagScheme(gazetteers: NSArray<NLGazetteer> | NLGazetteer[], tagScheme: string): void;
setLanguageRange(language: string, range: NSRange): void;
setModelsForTagScheme(models: NSArray<NLModel> | NLModel[], tagScheme: string): void;
setOrthographyRange(orthography: NSOrthography, range: NSRange): void;
tagAtIndexUnitSchemeTokenRange(characterIndex: number, unit: NLTokenUnit, scheme: string, tokenRange: interop.Pointer | interop.Reference<NSRange>): string;
tagHypothesesAtIndexUnitSchemeMaximumCountTokenRange(characterIndex: number, unit: NLTokenUnit, scheme: string, maximumCount: number, tokenRange: interop.Pointer | interop.Reference<NSRange>): NSDictionary<string, number>;
tagsInRangeUnitSchemeOptionsTokenRanges(range: NSRange, unit: NLTokenUnit, scheme: string, options: NLTaggerOptions, tokenRanges: interop.Pointer | interop.Reference<NSArray<NSValue>>): NSArray<string>;
tokenRangeAtIndexUnit(characterIndex: number, unit: NLTokenUnit): NSRange;
tokenRangeForRangeUnit(range: NSRange, unit: NLTokenUnit): NSRange;
}
declare const enum NLTaggerAssetsResult {
Available = 0,
NotAvailable = 1,
Error = 2
}
declare const enum NLTaggerOptions {
OmitWords = 1,
OmitPunctuation = 2,
OmitWhitespace = 4,
OmitOther = 8,
JoinNames = 16,
JoinContractions = 32
}
declare const enum NLTokenUnit {
Word = 0,
Sentence = 1,
Paragraph = 2,
Document = 3
}
declare class NLTokenizer extends NSObject {
static alloc(): NLTokenizer; // inherited from NSObject
static new(): NLTokenizer; // inherited from NSObject
string: string;
readonly unit: NLTokenUnit;
constructor(o: { unit: NLTokenUnit; });
enumerateTokensInRangeUsingBlock(range: NSRange, block: (p1: NSRange, p2: NLTokenizerAttributes, p3: interop.Pointer | interop.Reference<boolean>) => void): void;
initWithUnit(unit: NLTokenUnit): this;
setLanguage(language: string): void;
tokenRangeAtIndex(characterIndex: number): NSRange;
tokenRangeForRange(range: NSRange): NSRange;
tokensForRange(range: NSRange): NSArray<NSValue>;
}
declare const enum NLTokenizerAttributes {
Numeric = 1,
Symbolic = 2,
Emoji = 4
} | the_stack |
import { exportAsMessages } from './helpers';
exportAsMessages('_locales/en/messages.json', {
// The extension name.
extensionName: 'uBlacklist',
// The extension description.
extensionDescription: 'Blocks sites you specify from appearing in Google search results',
// The language code.
lang: 'en',
// The text that means an error occurred.
// '$1' is expanded to the message.
error: 'Error: $1',
// The error message shown when unauthorized to access a cloud.
unauthorizedError: 'Unauthorized. Please turn sync off and on again.',
// The text of a cancel button.
cancelButton: 'Cancel',
// The text of an OK button.
okButton: 'OK',
// The text that means one site has been blocked.
content_singleSiteBlocked: 'uBlacklist has blocked 1 site',
// The text that means multiple sites have been blocked.
// '$1' is expanded to the count.
content_multipleSitesBlocked: 'uBlacklist has blocked $1 sites',
// The text of the link to show blocked sites.
content_showBlockedSitesLink: 'Show',
// The text of the link to hide blocked sites.
content_hideBlockedSitesLink: 'Hide',
// The text of a link to block a site.
content_blockSiteLink: 'Block this site',
// The text of a link to unblock a site.
content_unblockSiteLink: 'Unblock this site',
// The title of a popup to block a site.
popup_blockSiteTitle: 'Block this site',
// The title of a popup to unblock a site.
popup_unblockSiteTitle: 'Unblock this site',
// The title of the disclosure widget that contains the details.
popup_details: 'Details',
// The label for the textarea that shows the page URL.
popup_pageURLLabel: 'Page URL',
// The label for the input that shows a path depth of rules to be added.
popup_pathDepth: 'Depth',
// The label for the textarea that shows the page title.
popup_pageTitleLabel: 'Page title',
// The label for the textarea that shows rules to be added.
popup_addedRulesLabel: 'Rules to be added',
// The label for the textarea that shows rules to be removed.
popup_removedRulesLabel: 'Rules to be removed',
// The text of the button to block a site.
popup_blockSiteButton: 'Block',
// The text of the button to unblock a site.
popup_unblockSiteButton: 'Unblock',
// The text of the link to the options page.
popup_openOptionsLink: 'Options',
// The text to indicate that this extension is active.
popup_active: 'uBlacklist is active',
// The text to indicate that this extension is inactive.
popup_inactive: 'uBlacklist is inactive',
// The text of the button to activate this extension.
popup_activateButton: 'Activate',
// The title of the general section.
options_generalTitle: 'General',
// The label for the blacklist textarea.
options_blacklistLabel: 'Sites blocked from appearing in Google search results',
// The helper text for the blacklist textarea.
options_blacklistHelper:
'You can use [match patterns](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns) or [regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).',
// The helper text to show an example rule.
// '$1' is expanded to the example.
options_blacklistExample: 'Example: $1',
// The helper text to explain how to block sites by page title.
options_blockByTitle: 'To block sites by page title, prepend "title" to regular expressions.',
// The text indicating that the blacklist is update outside the options page.
options_blacklistUpdated: 'Updated',
// The text of the button to reload the blacklist.
options_reloadBlacklistButton: 'Reload',
// The text of the button to import a blacklist.
options_importBlacklistButton: 'Import',
// The text of the button to export a blacklist.
options_exportBlacklistButton: 'Export',
// The text of the button to save a blacklist.
options_saveBlacklistButton: 'Save',
// The title of the import-blacklist dialog.
options_importBlacklistDialog_title: 'Import',
// The label for the select to import from a file.
options_importBlacklistDialog_fromFile: 'Import from a file',
// The text of the button to import from a file.
options_importBlacklistDialog_selectFile: 'Select a file',
// The label for the select to import from Personal Blocklist.
options_importBlacklistDialog_fromPB: 'Import from Personal Blocklist',
// The label for the textarea to import from Personal Blocklist (for a11y only).
options_importBlacklistDialog_pbLabel: 'Domains',
// The text of the checkbox to append to the existing blacklist
options_importBlacklistDialog_append: 'Append to the existing list',
// The text of the import button on the import-blacklist dialog.
options_importBlacklistDialog_importButton: 'Import',
// The helper text for the textarea on the import-blacklist dialog.
options_importBlacklistDialog_helper: 'Paste the domains exported from Personal Blocklist.',
// Other search engines support.
options_otherSearchEngines: 'Other search engines',
// The details for other search engines support.
options_otherSearchEnginesDescription: 'You can use this extension on the below search engines.',
// The text of the button to enable this extension on a search engine.
options_registerSearchEngine: 'Enable',
// The text of the button to indicate that this extension is enabled on a search engine.
options_searchEngineRegistered: 'Enabled',
// The label for the switch whether to skip the 'Block this site' dialog
options_skipBlockDialogLabel: 'Skip the "Block this site" dialog',
// The label for the switch whether to hide the 'Block this site' links.
options_hideBlockLinksLabel: 'Hide the "Block this site" links',
// The label for the switch whether to hide the number of blocked sites and the 'Show' link.
options_hideControlLabel: 'Hide the number of blocked sites and the "Show" link',
// The label for the switch whether to block a whole site by default.
options_blockWholeSiteLabel: 'Add rules blocking whole sites by default',
// The example of blocking a whole site.
options_blockWholeSiteDescription:
'For example, to block the page "https://a.b.example.uk.com/", a rule "*://*.example.uk.com/*" will be added.',
// The title of the appearance section.
options_appearanceTitle: 'Appearance',
// The color of links.
options_linkColor: 'The color of links',
// The color of blocked search results.
options_blockColor: 'The color of blocked search results',
// The label of radio buttons to use the default color.
options_colorUseDefault: 'Default',
// The label of radio buttons to specify the color.
options_colorSpecify: 'Custom',
// The colors of highlighted search results.
options_highlightColors: 'The colors of highlighted search results',
// The description of the highlighting feature.
options_highlightDescription: 'To highlight search results with Color N, prepend "@N" to rules.',
// The name of the nth color.
options_highlightColorNth: 'Color $1',
// The label of the button to add a highlight color (for a11y only).
options_highlightColorAdd: 'Add',
// The label of the button to remove a highlight color (for a11y only).
options_highlightColorRemove: 'Remove',
// The dialog theme.
options_dialogTheme: 'The theme of the "Block this site" dialog on search results',
// The label of a radio button to use the default dialog theme.
options_dialogThemeDefault: 'Default',
// The label of a radio button to use the light theme.
options_dialogThemeLight: 'Light',
// The label of a radio button to use the dark theme.
options_dialogThemeDark: 'Dark',
// The title of the sync section.
options_syncTitle: 'Sync',
// The text to indicate that the sync feature has been updated (version 3 -> 4).
options_syncFeatureUpdated:
'The sync feature has been updated. To continue using sync, press the "Turn on sync" button.',
// The sync feature.
options_syncFeature: 'Sync with a cloud',
// The description of the sync feature.
options_syncFeatureDescription:
'You can synchronize blacklists across your devices through a cloud.',
// The text of the button to turn on sync.
options_turnOnSync: 'Turn on sync',
// The title of the dialog to turn on sync.
options_turnOnSyncDialog_title: 'Turn on sync',
// The text of the button to turn on sync.
options_turnOnSyncDialog_turnOnSyncButton: 'Turn on',
// The text to explain permission requests in the 'alternative' web auth flow.
// Currently it is used only in Safari.
// '$1' is expanded to 'iorate.github.io'.
options_turnOnSyncDialog_altFlowDescription:
'You may be asked for permission to access $1 before authentication, but your personal information will NOT be stored in that domain.',
// The label for the textarea to input the authorization code returned by the 'alternative' web auth flow.
// Currently it is used only in Safari (probably only on iOS and iPadOS).
options_turnOnSyncDialog_altFlowAuthCodeLabel: 'Authorization code',
// The text of the button to turn off sync.
options_turnOffSync: 'Turn off',
// The text that means the result of the last sync.
options_syncResult: 'Last sync',
// The text that means sync has been never performed.
options_syncNever: 'Never synced',
// The text that means sync is running right now.
options_syncRunning: 'Syncing...',
// The text of the button to reload the options page after settings are downloaded from a cloud.
options_syncReloadButton: 'Reload',
// The text of the button to sync now.
options_syncNowButton: 'Sync now',
// The label of the list to choose what to sync.
options_syncCategories: 'What to sync',
// The label of the switch to sync the blocklist.
options_syncBlocklist: 'Blocked sites',
// The label of the switch to sync the general settings.
options_syncGeneral: 'General settings',
// The label of the switch to sync the appearance.
options_syncAppearance: 'Appearance',
// The label of the switch to sync the subscriptions.
options_syncSubscriptions: 'Subscriptions',
// The label of the select to select a sync interval.
options_syncInterval: 'Sync interval',
// The title of the subscription section.
options_subscriptionTitle: 'Subscription',
// The subscription feature.
options_subscriptionFeature: 'Subscribe to blacklists',
// The description of the subscription feature.
options_subscriptionFeatureDescription:
'If you add a subscription, blacklists will be regularly downloaded from the specified URL.',
// The text of the button to add a subscription.
options_addSubscriptionButton: 'Add a subscription',
// The header text of the name row of the subscriptions table.
options_subscriptionNameHeader: 'Name',
// The header text of the URL row of the subscriptions table.
options_subscriptionURLHeader: 'URL',
// The header text of the update-result row of the subscriptions table.
options_subscriptionUpdateResultHeader: 'Last update',
// The label for the menu buttons of the subscriptions table (for a11y only).
options_subscriptionMenuButtonLabel: 'Menu',
// The text that means no subscriptions have been added.
options_noSubscriptionsAdded: 'No subscriptions added',
// The text that means update is running right now.
options_subscriptionUpdateRunning: 'Updating...',
// The text of a menu item to show a subscription.
options_showSubscriptionMenu: 'Show',
// The text of a menu item to update a subscription now.
options_updateSubscriptionNowMenu: 'Update now',
// The text of a menu item to remove a subscription.
options_removeSubscriptionMenu: 'Remove',
// The text of the button to update all subscriptions now.
options_updateAllSubscriptionsNowButton: 'Update now',
// The title of the add-subscription dialog.
options_addSubscriptionDialog_title: 'Add a subscription',
// The label for the name input on the add-subscription dialog.
options_addSubscriptionDialog_nameLabel: 'Name',
// The label for the URL input on the add-subscription dialog.
options_addSubscriptionDialog_urlLabel: 'URL',
// The text of the add button on the add-subscription dialog.
options_addSubscriptionDialog_addButton: 'Add',
// The label for the textarea on the show-subscription dialog (for a11y only).
options_showSubscriptionDialog_blacklistLabel: 'Rules',
// The label of the select to select an update interval.
options_updateInterval: 'Update interval',
// The label of the radio button to sync with Google Drive.
clouds_googleDriveSync: 'Sync with Google Drive',
// The text to describe the behavior of sync with Google Drive.
clouds_googleDriveSyncDescription:
'A file will be created within the application data folder hidden from the user.',
// The text indicating that sync with Google Drive is turned on.
clouds_googleDriveSyncTurnedOn: 'Synced with Google Drive',
// The text indicating syncing with Dropbox.
clouds_dropboxSync: 'Sync with Dropbox',
// The text to describe the behavior of sync with Dropbox.
clouds_dropboxSyncDescription: 'A file will be created within "/Apps/uBlacklist/".',
// The label of the radio button to sync with Dropbox.
clouds_dropboxSyncTurnedOn: 'Synced with Dropbox',
// The localized name of Google (not used).
searchEngines_googleName: 'Google',
// The localized name of Bing.
searchEngines_bingName: 'Bing',
// The localized name of DuckDuckGo.
searchEngines_duckduckgoName: 'DuckDuckGo',
// The localized name of Ecosia.
searchEngines_ecosiaName: 'Ecosia',
// The localized name of Startpage.
searchEngines_startpageName: 'Startpage.com',
}); | the_stack |
import {
app,
BrowserWindow,
dialog,
Menu,
MenuItem,
MenuItemConstructorOptions,
shell,
} from "electron";
import {
emuMuteSoundAction,
emuSetClockMultiplierAction,
emuSetSoundLevelAction,
} from "@state/emulator-panel-reducer";
import { AppState } from "@state/AppState";
import { __DARWIN__ } from "../utils/electron-utils";
import {
appConfiguration,
appSettings,
} from "../main-state/klive-configuration";
import {
ideToolFrameMaximizeAction,
ideToolFrameShowAction,
} from "@state/tool-frame-reducer";
import { MainToEmuForwarder } from "../communication/MainToEmuForwarder";
import { machineRegistry } from "@core/main/machine-registry";
import {
createKliveProject,
openProject,
openProjectFolder,
} from "../project/project-utils";
import { closeProjectAction } from "@state/project-reducer";
import { NewProjectResponse } from "@core/messaging/message-types";
import { AppWindow } from "./app-window";
import {
sendFromMainToEmu,
sendFromMainToIde,
} from "@core/messaging/message-sending";
import { executeKliveCommand } from "@abstractions/common-commands";
import { dispatch, getState, getStore } from "@core/service-registry";
import { ideWindow } from "./ide-window";
import { emuWindow } from "./emu-window";
import { Unsubscribe } from "redux";
/**
* Messenger instance to the emulator window
*/
export let emuForwarder: MainToEmuForwarder;
/**
* Last known machine type
*/
let lastMachineType = "";
/**
* Last known sound level
*/
let lastSoundLevel: number | null = null;
/**
* Was the sound muted?
*/
let lastMuted: boolean | null = null;
/**
* The state of the menu items
*/
let menuState: Record<string, boolean> = {};
/**
* Sets the forwarder to the emulator window
* @param forwarder
*/
export function setEmuForwarder(forwarder: MainToEmuForwarder): void {
emuForwarder = forwarder;
}
// --- Menu IDs
const NEW_PROJECT = "new_project";
const OPEN_FOLDER = "open_folder";
const CLOSE_FOLDER = "close_folder";
const TOGGLE_KEYBOARD = "toggle_keyboard";
const TOGGLE_TOOLBAR = "toggle_toolbar";
const TOGGLE_STATUSBAR = "toggle_statusbar";
const TOGGLE_FRAMES = "toggle_frames";
const TOGGLE_DEVTOOLS = "toggle_devtools";
const START_VM = "start_vm";
const PAUSE_VM = "pause_vm";
const STOP_VM = "stop_vm";
const RESTART_VM = "restart_vm";
const DEBUG_VM = "debug_vm";
const STEP_INTO_VM = "step_into_vm";
const STEP_OVER_VM = "step_over_vm";
const STEP_OUT_VM = "step_out_vm";
const SHOW_IDE = "show_ide";
const SHOW_IDE_TOOLS = "show_ide_tools";
/**
* Sets up the application menu
*/
export function setupMenu(): void {
// --- Merge startup configuration and settings
const viewOptions = appSettings?.viewOptions ?? {
showToolbar: true,
showStatusbar: true,
showFrameInfo: true,
};
const template: (MenuItemConstructorOptions | MenuItem)[] = [];
if (__DARWIN__) {
template.push({
label: app.name,
submenu: [
{ role: "about" },
{ type: "separator" },
{ role: "services" },
{ type: "separator" },
{ role: "hide" },
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
],
});
}
// --- Prepare the File menu
const fileMenu: MenuItemConstructorOptions = {
label: "File",
submenu: [
{
id: NEW_PROJECT,
label: "New project...",
click: async () => {
await openIdeWindow();
const project = (
(await sendFromMainToIde({
type: "NewProjectRequest",
})) as NewProjectResponse
).project;
if (project) {
const operation = await createKliveProject(
project.machineType,
project.projectPath,
project.projectName
);
if (operation.error) {
await dialog.showMessageBox(AppWindow.focusedWindow.window, {
title: "Error while creating a new Klive project",
message: operation.error,
type: "error",
});
} else {
if (project.open && operation.targetFolder) {
await openProject(operation.targetFolder);
}
}
}
},
},
{ type: "separator" },
{
id: OPEN_FOLDER,
label: "Open folder...",
click: async () => {
await openIdeWindow();
await openProjectFolder();
},
},
{
id: CLOSE_FOLDER,
label: "Close folder",
enabled: !!getState()?.project?.path,
click: () => {
dispatch(closeProjectAction());
},
},
{ type: "separator" },
__DARWIN__ ? { role: "close" } : { role: "quit" },
],
};
// --- Preapre the view menu
const viewSubMenu: MenuItemConstructorOptions[] = [
{ role: "resetZoom" },
{ role: "zoomIn" },
{ role: "zoomOut" },
{ type: "separator" },
{ role: "togglefullscreen" },
{
id: TOGGLE_DEVTOOLS,
label: "Toggle Developer Tools",
accelerator: "Ctrl+Shift+I",
visible: appConfiguration?.showDevTools ?? false,
enabled: appConfiguration?.showDevTools ?? false,
click: () => {
BrowserWindow.getFocusedWindow().webContents.toggleDevTools();
},
},
{ type: "separator" },
{
id: TOGGLE_KEYBOARD,
label: "Show keyboard",
type: "checkbox",
checked: false,
click: (mi) => {
executeKliveCommand(mi.checked ? "showKeyboard" : "hideKeyboard");
emuWindow.saveKliveProject();
},
},
{ type: "separator" },
];
let extraViewItems: MenuItemConstructorOptions[] =
emuWindow.machineContextProvider?.provideViewMenuItems() ?? [];
if (extraViewItems.length > 0) {
extraViewItems.push({ type: "separator" });
}
viewSubMenu.push(...extraViewItems);
viewSubMenu.push(
{
id: TOGGLE_TOOLBAR,
label: "Show toolbar",
type: "checkbox",
checked: viewOptions.showToolbar ?? true,
click: (mi) => {
executeKliveCommand(mi.checked ? "showToolbar" : "hideToolbar");
emuWindow.saveKliveProject();
},
},
{
id: TOGGLE_STATUSBAR,
label: "Show statusbar",
type: "checkbox",
checked: viewOptions.showStatusbar ?? true,
click: (mi) => {
executeKliveCommand(mi.checked ? "showStatusBar" : "hideStatusBar");
emuWindow.saveKliveProject();
},
},
{
id: TOGGLE_FRAMES,
label: "Show frame information",
type: "checkbox",
checked: viewOptions.showFrameInfo ?? true,
click: (mi) => {
executeKliveCommand(mi.checked ? "showFrameInfo" : "hideFrameInfo");
emuWindow.saveKliveProject();
},
}
);
// --- Add the file and view menu
template.push(fileMenu, {
label: "View",
submenu: viewSubMenu,
});
// --- Prepare the Run menu
const runMenu: MenuItemConstructorOptions = {
label: "Run",
submenu: [
{
id: START_VM,
label: "Start",
accelerator: "F5",
enabled: true,
click: async () => await sendFromMainToEmu({ type: "StartVm" }),
},
{
id: PAUSE_VM,
label: "Pause",
accelerator: "Shift+F5",
enabled: false,
click: async () => await sendFromMainToEmu({ type: "PauseVm" }),
},
{
id: STOP_VM,
label: "Stop",
accelerator: "F4",
enabled: false,
click: async () => await sendFromMainToEmu({ type: "StopVm" }),
},
{
id: RESTART_VM,
label: "Restart",
accelerator: "Shift+F4",
enabled: false,
click: async () => await sendFromMainToEmu({ type: "RestartVm" }),
},
{ type: "separator" },
{
id: DEBUG_VM,
label: "Start with debugging",
accelerator: "Ctrl+F5",
enabled: true,
click: async () => await sendFromMainToEmu({ type: "DebugVm" }),
},
{
id: STEP_INTO_VM,
label: "Step into",
accelerator: "F3",
enabled: false,
click: async () => await sendFromMainToEmu({ type: "StepIntoVm" }),
},
{
id: STEP_OVER_VM,
label: "Step over",
accelerator: "Shift+F3",
enabled: false,
click: async () => await sendFromMainToEmu({ type: "StepOverVm" }),
},
{
id: STEP_OUT_VM,
label: "Step out",
accelerator: "Ctrl+F3",
enabled: false,
click: async () => await sendFromMainToEmu({ type: "StepOutVm" }),
},
],
};
template.push(runMenu);
// --- Prepare the machine menu
const machineSubMenu: MenuItemConstructorOptions[] = [];
const machineType = getState()?.machineType?.split("_")[0];
for (var [_, value] of machineRegistry) {
machineSubMenu.push({
id: menuIdFromMachineId(value.id),
label: value.label,
type: "radio",
checked: value.id === machineType,
enabled: value.active ?? true,
click: async (mi) => {
try {
const machineType = mi.id.split("_")[1];
await emuWindow.requestMachineType(machineType);
emuWindow.saveAppSettings();
emuWindow.saveKliveProject();
} catch {
// --- Intentionally ignored
}
},
});
}
// --- Create menu items for sound
const soundMenuItems: MenuItemConstructorOptions[] = SOUND_MENU_ITEMS.map(
(item, index) => ({
id: item.id,
label: item.label,
type: "radio",
checked: index === 3,
click: () => {
setSoundLevel(item.level);
emuWindow.saveKliveProject();
},
})
);
machineSubMenu.push({ type: "separator" }, ...soundMenuItems);
if (emuWindow?.machineContextProvider) {
// --- Add clock multiplier submenu
const cpuClockSubmenu: MenuItemConstructorOptions = {
type: "submenu",
label: "CPU clock multiplier",
submenu: [],
};
const baseClockFrequency =
emuWindow.machineContextProvider?.getNormalCpuFrequency() ?? 1_000_000;
for (let i = 1; i <= 24; i++) {
(cpuClockSubmenu.submenu as MenuItemConstructorOptions[]).push({
id: `clockMultiplier_${i}`,
type: "radio",
label:
(i > 1 ? `${i}x` : `Normal`) +
` (${((i * baseClockFrequency) / 1_000_000).toFixed(4)}MHz)`,
click: () => {
dispatch(emuSetClockMultiplierAction(i));
emuWindow.saveKliveProject();
},
});
}
machineSubMenu.push({ type: "separator" });
machineSubMenu.push(cpuClockSubmenu);
// --- Add machine-specific submenus
let extraMachineItems: MenuItemConstructorOptions[] =
emuWindow.machineContextProvider?.provideMachineMenuItems() ?? [];
if (extraMachineItems.length > 0) {
machineSubMenu.push({ type: "separator" });
machineSubMenu.push(...extraMachineItems);
}
}
template.push({
label: "Machine",
submenu: machineSubMenu,
});
if (__DARWIN__) {
template.push({
label: "Window",
submenu: [
{ role: "minimize" },
{ role: "zoom" },
{ type: "separator" },
{ role: "front" },
{ type: "separator" },
{ role: "window" },
],
});
}
const ideMenu: MenuItemConstructorOptions = {
label: "IDE",
submenu: [
{
id: SHOW_IDE,
label: "Show IDE window",
type: "checkbox",
checked: false,
enabled: true,
click: async (mi) => {
executeKliveCommand(mi.checked ? "showIde" : "hideIde");
if (mi.checked) {
sendFromMainToIde({
type: "SyncMainState",
mainState: { ...getState() },
});
}
},
},
{ type: "separator" },
{
id: SHOW_IDE_TOOLS,
label: "Show Tools",
type: "checkbox",
checked: getState()?.toolFrame?.visible ?? false,
enabled: true,
click: async (mi) => {
const toolsMaximized = !!getState().toolFrame?.maximized;
const toolsVisible = !!getState()?.toolFrame?.visible;
if (toolsMaximized) {
dispatch(ideToolFrameMaximizeAction(false));
await new Promise((r) => setTimeout(r, 20));
}
dispatch(ideToolFrameShowAction(!toolsVisible));
if (toolsMaximized) {
await new Promise((r) => setTimeout(r, 20));
dispatch(ideToolFrameMaximizeAction(true));
}
},
},
],
};
template.push(ideMenu);
const helpSubmenu: MenuItemConstructorOptions[] = [
{
label: "Klive on Github",
click: async () => {
await shell.openExternal("https://github.com/Dotneteer/kliveide");
},
},
{
label: "Getting started with Klive",
click: async () => {
await shell.openExternal(
"https://dotneteer.github.io/kliveide/getting-started/install-kliveide.html"
);
},
},
];
// --- Add machine-specific help menu items
if (emuWindow?.machineContextProvider) {
let extraHelpItems: MenuItemConstructorOptions[] =
emuWindow.machineContextProvider?.provideHelpMenuItems() ?? [];
if (extraHelpItems.length > 0) {
helpSubmenu.push({ type: "separator" });
helpSubmenu.push(...extraHelpItems);
}
}
template.push({
role: "help",
submenu: helpSubmenu,
});
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
generateMenuIds();
}
/**
* Traverses all menu items and executed the specified action
* @param action Action to execute
*/
export function traverseMenu(action: (item: MenuItem) => void): void {
const menu = Menu.getApplicationMenu().items;
traverseMenu(menu, action);
function traverseMenu(
items: MenuItem[],
action: (item: MenuItem) => void
): void {
for (let item of items) {
action(item);
if (item.submenu) {
traverseMenu(item.submenu.items, action);
}
}
}
}
/**
* Saves the enabled states of menu items
*/
export function generateMenuIds(): void {
let counter = 0;
traverseMenu((item) => {
if (!item.id) {
item.id = `__generated__${counter++}`;
}
});
}
/**
* Saves the enabled states of menu items
*/
export function saveMenuEnabledState(): void {
menuState = {};
traverseMenu((item) => {
menuState[item.id] = item.enabled;
});
}
/**
* Saves the enabled states of menu items
*/
export function disableAppMenu(): void {
traverseMenu((item) => (item.enabled = false));
}
/**
* Saves the enabled states of menu items
*/
export function restoreEnabledState(): void {
traverseMenu((item) => {
item.enabled = menuState[item.id];
});
}
/**
* Sets the specified sound level
* @param level Sound level (between 0.0 and 1.0)
*/
export function setSoundLevel(level: number): void {
if (level === 0) {
dispatch(emuMuteSoundAction(true));
} else {
dispatch(emuMuteSoundAction(false));
dispatch(emuSetSoundLevelAction(level));
}
}
/**
* Sets the sound menu with the specified level
* @param level Sound level
*/
export function setSoundLevelMenu(muted: boolean, level: number): void {
for (const menuItem of SOUND_MENU_ITEMS) {
const item = Menu.getApplicationMenu().getMenuItemById(menuItem.id);
if (item) {
item.checked = false;
}
}
if (muted) {
const soundItem = Menu.getApplicationMenu().getMenuItemById(
SOUND_MENU_ITEMS[0].id
);
if (soundItem) {
soundItem.checked = true;
}
} else {
for (let i = 0; i < SOUND_MENU_ITEMS.length; i++) {
if (level < SOUND_MENU_ITEMS[i].level + 0.02) {
const soundItem = Menu.getApplicationMenu().getMenuItemById(
SOUND_MENU_ITEMS[i].id
);
if (soundItem) {
soundItem.checked = true;
}
break;
}
}
}
}
// ============================================================================
// Handle state changes affecting the application menu
const stateChangeHandler: () => void = () => processStateChange(getState());
let unsubscribe: Unsubscribe;
/**
* Sets up state change processing
*/
export function startStateChangeProcessing(): void {
unsubscribe = getStore().subscribe(stateChangeHandler);
}
/**
* Stop state change processing
*/
export function stopStateChangeProcessing(): void {
unsubscribe();
}
let lastShowIde = false;
let lastModalDisplayed = false;
/**
* Processes application state changes
* @param fullState Application state
*/
export function processStateChange(fullState: AppState): void {
const menu = Menu.getApplicationMenu();
const viewOptions = fullState.emuViewOptions;
const emuState = fullState.emulatorPanel;
// --- Modals?
if (lastModalDisplayed !== fullState.modalDisplayed) {
lastModalDisplayed = fullState.modalDisplayed;
if (fullState.modalDisplayed) {
saveMenuEnabledState();
disableAppMenu();
return;
}
restoreEnabledState();
}
// --- File menu state
const closeFolder = menu.getMenuItemById(CLOSE_FOLDER);
if (closeFolder) {
closeFolder.enabled = !!fullState?.project?.path;
}
// --- Visibility of the IDE window
if (lastShowIde !== fullState.showIde) {
lastShowIde = fullState.showIde;
if (fullState.showIde) {
ideWindow.show();
} else {
ideWindow.hide();
}
}
if (menu) {
// --- IDE window visibility
const showIDE = menu.getMenuItemById(SHOW_IDE);
if (showIDE) {
showIDE.checked = fullState.showIde;
}
// --- Tools panel visibility
const showTools = menu.getMenuItemById(SHOW_IDE_TOOLS);
if (showTools) {
showTools.checked = fullState.toolFrame?.visible ?? false;
}
// --- Keyboard panel status
const toggleKeyboard = menu.getMenuItemById(TOGGLE_KEYBOARD);
if (toggleKeyboard) {
toggleKeyboard.checked = !!viewOptions.showKeyboard;
}
// --- Clock multiplier status
if (emuState) {
const clockMultiplier = emuState.clockMultiplier ?? 1;
const cmItem = menu.getMenuItemById(`clockMultiplier_${clockMultiplier}`);
if (cmItem) {
cmItem.checked = false;
}
}
// --- VM control commands
const executionState = emuState.executionState;
const startVm = menu.getMenuItemById(START_VM);
if (startVm) {
startVm.enabled =
executionState === 0 || executionState === 3 || executionState === 5;
}
const pauseVm = menu.getMenuItemById(PAUSE_VM);
if (pauseVm) {
pauseVm.enabled = executionState === 1;
}
const stopVm = menu.getMenuItemById(STOP_VM);
if (stopVm) {
stopVm.enabled = executionState === 1 || executionState === 3;
}
const restartVm = menu.getMenuItemById(RESTART_VM);
if (restartVm) {
restartVm.enabled = executionState === 1 || executionState === 3;
}
const debugVm = menu.getMenuItemById(DEBUG_VM);
if (debugVm) {
debugVm.enabled =
executionState === 0 || executionState === 3 || executionState === 5;
}
const stepIntoVm = menu.getMenuItemById(STEP_INTO_VM);
if (stepIntoVm) {
stepIntoVm.enabled = executionState === 3;
}
const stepOverVm = menu.getMenuItemById(STEP_OVER_VM);
if (stepOverVm) {
stepOverVm.enabled = executionState === 3;
}
const stepOutVm = menu.getMenuItemById(STEP_OUT_VM);
if (stepOutVm) {
stepOutVm.enabled = executionState === 3;
}
}
if (lastMachineType !== fullState.machineType) {
// --- Current machine types has changed
lastMachineType = fullState.machineType;
setupMenu();
}
// --- Sound level has changed
if (lastSoundLevel !== emuState.soundLevel || lastMuted !== emuState.muted) {
lastSoundLevel = emuState.soundLevel;
lastMuted = emuState.muted;
setSoundLevelMenu(lastMuted, lastSoundLevel);
}
// --- Take care that custom machine menus are updated
emuWindow.machineContextProvider?.updateMenuStatus(fullState);
// // --- The engine has just saved a ZX Spectrum file
// if (emuState?.savedData && emuState.savedData.length > 0) {
// const data = emuState.savedData;
// const ideConfig = mainProcessStore.getState().ideConfiguration;
// if (!ideConfig) {
// return;
// }
// // --- Create filename
// const tapeFilePath = path.join(
// ideConfig.projectFolder,
// ideConfig.saveFolder
// );
// const nameBytes = data.slice(2, 12);
// let name = "";
// for (let i = 0; i < 10; i++) {
// name += String.fromCharCode(nameBytes[i]);
// }
// const tapeFileName = path.join(tapeFilePath, `${name.trimRight()}.tzx`);
// // --- We use this writer to save file info into
// const writer = new BinaryWriter();
// new TzxHeader().writeTo(writer);
// // --- The first 19 bytes is the header
// new TzxStandardSpeedDataBlock(data.slice(0, 19)).writeTo(writer);
// // --- Other bytes are the data block
// new TzxStandardSpeedDataBlock(data.slice(19)).writeTo(writer);
// // --- Now, save the file
// fs.writeFileSync(tapeFileName, writer.buffer);
// // --- Sign that the file has been saved
// mainProcessStore.dispatch(
// emulatorSetSavedDataAction(new Uint8Array(0))()
// );
// }
}
// ============================================================================
// Helper types and methods
/**
* Creates a menu ID from a machine ID
* @param machineId Machine ID
*/
function menuIdFromMachineId(machineId: string): string {
return `machine_${machineId}`;
}
/**
* Opens the IDE window
*/
async function openIdeWindow(): Promise<void> {
executeKliveCommand("showIde");
await new Promise((r) => setTimeout(r, 200));
await sendFromMainToIde({
type: "SyncMainState",
mainState: { ...getState() },
});
ideWindow.window.focus();
}
/**
* Represents a sound level menu item
*/
interface SoundMenuItem {
id: string;
label: string;
level: number;
}
/**
* The list of sound menu items
*/
const SOUND_MENU_ITEMS: SoundMenuItem[] = [
{ id: "mute_sound", label: "Mute sound", level: 0.0 },
{ id: "sound_level_low", label: "Sound: low", level: 0.13 },
{ id: "sound_level_medium", label: "Sound: Medium", level: 0.25 },
{ id: "sound_level_high", label: "Sound: High", level: 0.5 },
{ id: "sound_level_highest", label: "Sound: Highest", level: 1.0 },
]; | the_stack |
import { ResponseError } from "../exception/ResponseError"
import { QueryErrorMessage } from "../types/ResponseTypes"
import { TeamSpeakQuery } from "./TeamSpeakQuery"
import { Version } from "../types/ResponseTypes"
export class Command {
static SNAKE_CASE_IDENTIFIER = "_"
private requestParser: Command.RequestParser = Command.getParsers().request
private responseParser: Command.ResponseParser = Command.getParsers().response
private cmd: string = ""
private options: Command.options = {}
private multiOpts: Command.multiOpts = []
private flags: string[] = []
private response: TeamSpeakQuery.Response = []
private error: QueryErrorMessage|null = null
private stack: string = new Error().stack!
/** Initializes the Respone with default values */
reset(): Command {
this.response = []
this.error = null
return this
}
/** Sets the main command to send */
setCommand(cmd: string): Command {
this.cmd = cmd.trim()
return this
}
/**
* Sets the TeamSpeak Key Value Pairs
* @param opts sets the Object with the key value pairs which should get sent to the TeamSpeak Query
*/
setOptions(options: Command.options): Command {
this.options = options
return this
}
/**
* retrieves the current set options for this command
*/
getOptions(): Command.options {
return this.options
}
/**
* Sets the TeamSpeak Key Value Pairs
* @param opts sets the Object with the key value pairs which should get sent to the TeamSpeak Query
*/
setMultiOptions (options: Command.multiOpts): Command {
this.multiOpts = options
return this
}
/**
* adds a customparser
* @param parsers
*/
setParser(parsers: Command.ParserCallback) {
const { response, request } = parsers(Command.getParsers())
this.requestParser = request
this.responseParser = response
return this
}
/** checks wether there are options used with this command */
hasOptions(): boolean {
return Object.values(this.options).length > 0 || this.hasMultiOptions()
}
/** checks wether there are options used with this command */
hasMultiOptions() {
return this.multiOpts.length > 0
}
/**
* set TeamSpeak flags
* @param flags sets the flags which should get sent to the teamspeak query
*/
setFlags(flags: Command.flags): Command {
this.flags = <string[]>flags
.filter(flag => ["string", "number"].includes(typeof flag))
.map(flag => String(flag))
return this
}
/** checks wether there are flags used with this command */
hasFlags(): boolean {
return this.flags.length > 0
}
/**
* set the Line which has been received from the TeamSpeak Query
* @param line the line which has been received from the teamSpeak query
*/
setResponse(line: string): Command {
this.response = this.parse(line)
return this
}
/**
* Set the error line which has been received from the TeamSpeak Query
* @param error the error line which has been received from the TeamSpeak Query
*/
setError(raw: string): Command {
this.error = <QueryErrorMessage><unknown>Command.parse({ raw })[0]
return this
}
/** get the parsed error object which has been received from the TeamSpeak Query */
getError() {
if (!this.hasError()) return null
return new ResponseError(this.error!, this.stack)
}
/** checks if a error has been received */
hasError() {
return (
this.error !== null &&
typeof this.error === "object" &&
typeof this.error.id === "string" &&
this.error.id !== "0"
)
}
/** get the parsed response object which has been received from the TeamSpeak Query */
getResponse() {
return this.response
}
/** runs the parser of this instance */
parse(raw: string) {
return this.responseParser({ raw, cmd: Command })
}
/** runs the parser of this instance */
build() {
return this.requestParser(this)
}
/**
* retrieves the default parsers
*/
static getParsers(): Command.Parsers {
return {
response: Command.parse,
request: Command.build
}
}
/**
* parses a snapshot create request
* @param param0 the custom snapshot response parser
*/
static parseSnapshotCreate({ raw }: Pick<Command.ParserArgument, "raw">) {
const version = raw.match(/version=(\d+)/)
if (!version) throw new Error("unable to detect snapshot version")
switch (version[1]) {
case "2":
return (() => {
const [data, snapshot] = raw.split("|")
return <TeamSpeakQuery.Response>[{
...Command.parse({ raw: data })[0], snapshot
}]
})()
case "3":
return (() => {
const { salt, data } = Command.parse({ raw })[0]
return <TeamSpeakQuery.Response>[{
version: "3", salt, snapshot: data
}]
})()
default:
throw new Error(`unsupported snapshot version: ${version[1]}`)
}
}
/**
* the custom snapshot request parser
* @param data snapshot string
* @param cmd command object
*/
static buildSnapshotDeploy(data: string, cmd: Command, { version }: Version, snapshotVersion: string = "0") {
if ((snapshotVersion === "0" && Command.minVersion("3.12.0", version)) || snapshotVersion === "3") {
cmd.setOptions({ ...cmd.getOptions(), version: "3", data })
return Command.build(cmd)
} else if ((snapshotVersion === "0" && Command.minVersion("3.10.0", version)) || snapshotVersion === "2") {
cmd.setOptions({ ...cmd.getOptions(), version: "2" })
return [Command.build(cmd), data].join("|")
} else {
throw new Error(`unsupported teamspeak version (${version}) or snapshot version (${snapshotVersion})`)
}
}
/**
* checks if a version string has a minimum of x
* @param minimum minimum the version string should have
* @param version version string to compare
*/
static minVersion(minimum: string, version: string) {
const v = version.split(".").map(n => parseInt(n, 10))
return minimum
.split(".")
.map(n => parseInt(n, 10))
.every((n, index) => n <= v[index])
}
/**
* parses a query response
* @param data the query response received
*/
static parse({ raw }: Pick<Command.ParserArgument, "raw">): TeamSpeakQuery.Response {
return raw
.split("|")
.map(entry => {
const res: TeamSpeakQuery.ResponseEntry = {}
entry.split(" ").forEach(str => {
const { key, value } = Command.getKeyValue(str)
res[key] = Command.parseValue(key, value)
})
return res
})
.map((entry, _, original) => ({...original[0], ...entry }))
}
/**
* Checks if a error has been received
* @return The parsed String which is readable by the TeamSpeak Query
*/
static build(command: Command) {
let cmd = Command.escape(command.cmd)
if (command.hasFlags()) cmd += ` ${command.buildFlags()}`
if (command.hasOptions()) cmd += ` ${command.buildOptions()}`
return cmd
}
/**
* builds the query string for options
* @return the parsed String which is readable by the TeamSpeak Querytt
*/
buildOptions() {
const options = this.buildOption(this.options)
if (!this.hasMultiOptions()) return options
return `${options} ${this.multiOpts.map(this.buildOption.bind(this)).join("|")}`
}
/** builds the query string for options */
buildOption(options: Record<string, any>): string {
return Object
.keys(options)
.filter(key => ![undefined, null].includes(options[key]))
.filter(key => typeof options[key] !== "number" || !isNaN(options[key]))
.map(key => Command.escapeKeyValue(key, options[key]))
.join(" ")
}
/** builds the query string for flags */
buildFlags(): string {
return this.flags.map(f => Command.escape(f)).join(" ")
}
/**
* escapes a key value pair
* @param {string} key the key used
* @param {string|string[]} value the value or an array of values
* @return the parsed String which is readable by the TeamSpeak Query
*/
static escapeKeyValue(key: string, value: string|string[]|boolean): string {
key = Command.toSnakeCase(key)
if (typeof value === "boolean") value = value ? "1" : "0"
if (Array.isArray(value)) {
return value.map(v => `${Command.escape(key)}=${Command.escape(v)}`).join("|")
} else {
return `${Command.escape(key)}=${Command.escape(value)}`
}
}
/**
* retrieves the key value pair from a string
* @param str the key value pair to unescape eg foo=bar
*/
static getKeyValue(str: string): { key: string, value: string|undefined } {
const index = str.indexOf("=")
if (index === -1) return { key: Command.toCamelCase(str), value: undefined }
const value = str.substring(index+1)
return {
key: Command.toCamelCase(str.substring(0, index)),
value: value === "" ? undefined : value
}
}
/**
* Parses a value to the type which the key represents
* @param k the key which should get looked up
* @param v the value which should get parsed
*/
static parseValue(k: string, v: string|undefined) {
if (v === undefined) return undefined
if (Object.keys(Command.Identifier).includes(k)) {
return Command.Identifier[k](v)
} else {
return this.parseString(v)
}
}
/**
* parses a number
* @param value string to parse
*/
static parseBoolean(value: string) {
return Command.parseNumber(value) === 1
}
/**
* parses a string value
* @param value string to parse
*/
static parseString(value: string) {
return Command.unescape(value)
}
static parseRecursive(value: string) {
return Command.parse({ raw: Command.unescape(value) })
}
/**
* parses a string array
* @param value string to parse
*/
static parseStringArray(value: string) {
return value.split(",").map(v => Command.parseString(v))
}
/**
* parses a number
* @param value string to parse
*/
static parseNumber(value: string) {
return parseFloat(value)
}
/**
* parses a number array
* @param value string to parse
*/
static parseNumberArray(value: string) {
return value.split(",").map(v => Command.parseNumber(v))
}
/** unescapes a string */
static unescape(str: string): string {
return String(str)
.replace(/\\s/g, " ")
.replace(/\\p/g, "|")
.replace(/\\n/g, "\n")
.replace(/\\f/g, "\f")
.replace(/\\r/g, "\r")
.replace(/\\t/g, "\t")
.replace(/\\v/g, "\v")
.replace(/\\\//g, "/")
.replace(/\\\\/g, "\\")
}
/** escapes a string */
static escape(str: string): string {
return String(str)
.replace(/\\/g, "\\\\")
.replace(/\//g, "\\/")
.replace(/\|/g, "\\p")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")
.replace(/\v/g, "\\v")
.replace(/\f/g, "\\f")
.replace(/ /g, "\\s")
}
/** converts a string to camel case */
static toCamelCase(str: string) {
let toUpper = false
return str.split("").map(char => {
if (char === Command.SNAKE_CASE_IDENTIFIER) {
toUpper = true
return ""
} else if (toUpper) {
toUpper = false
return char.toUpperCase()
} else {
return char
}
}).join("")
}
/** converts a string to snake case */
static toSnakeCase(str: string) {
return str.split("").map(char => {
const lower = char.toLowerCase()
if (char !== lower) return `${Command.SNAKE_CASE_IDENTIFIER}${lower}`
return char
}).join("")
}
}
export namespace Command {
export interface ParserArgument {
cmd: typeof Command
raw: string
}
export interface Parsers {
response: ResponseParser
request: RequestParser
}
export type ParserCallback = (parser: Parsers) => Parsers
export type ResponseParser = (data: ParserArgument) => TeamSpeakQuery.Response
export type RequestParser = (cmd: Command) => string
export type options = Record<string, TeamSpeakQuery.ValueTypes>
export type multiOpts = Command.options[]
export type flags = (number|string|null)[]
export const Identifier = {
sid: Command.parseString,
serverId: Command.parseString,
virtualserverNickname: Command.parseString,
virtualserverUniqueIdentifier: Command.parseString,
virtualserverName: Command.parseString,
virtualserverWelcomemessage: Command.parseString,
virtualserverPlatform: Command.parseString,
virtualserverVersion: Command.parseString,
virtualserverMaxclients: Command.parseNumber,
virtualserverPassword: Command.parseString,
virtualserverClientsonline: Command.parseNumber,
virtualserverChannelsonline: Command.parseNumber,
virtualserverCreated: Command.parseNumber,
virtualserverUptime: Command.parseNumber,
virtualserverCodecEncryptionMode: Command.parseNumber,
virtualserverHostmessage: Command.parseString,
virtualserverHostmessageMode: Command.parseNumber,
virtualserverFilebase: Command.parseString,
virtualserverDefaultServerGroup: Command.parseString,
virtualserverDefaultChannelGroup: Command.parseString,
virtualserverFlagPassword: Command.parseBoolean,
virtualserverDefaultChannelAdminGroup: Command.parseString,
virtualserverMaxDownloadTotalBandwidth: Command.parseNumber,
virtualserverMaxUploadTotalBandwidth: Command.parseNumber,
virtualserverHostbannerUrl: Command.parseString,
virtualserverHostbannerGfxUrl: Command.parseString,
virtualserverHostbannerGfxInterval: Command.parseNumber,
virtualserverComplainAutobanCount: Command.parseNumber,
virtualserverComplainAutobanTime: Command.parseNumber,
virtualserverComplainRemoveTime: Command.parseNumber,
virtualserverMinClientsInChannelBeforeForcedSilence: Command.parseNumber,
virtualserverPrioritySpeakerDimmModificator: Command.parseNumber,
virtualserverId: Command.parseString,
virtualserverAntifloodPointsNeededPluginBlock: Command.parseNumber,
virtualserverAntifloodPointsTickReduce: Command.parseNumber,
virtualserverAntifloodPointsNeededCommandBlock: Command.parseNumber,
virtualserverAntifloodPointsNeededIpBlock: Command.parseNumber,
virtualserverClientConnections: Command.parseNumber,
virtualserverQueryClientConnections: Command.parseNumber,
virtualserverHostbuttonTooltip: Command.parseString,
virtualserverHostbuttonUrl: Command.parseString,
virtualserverHostbuttonGfxUrl: Command.parseString,
virtualserverQueryclientsonline: Command.parseNumber,
virtualserverDownloadQuota: Command.parseNumber,
virtualserverUploadQuota: Command.parseNumber,
virtualserverMonthBytesDownloaded: Command.parseNumber,
virtualserverMonthBytesUploaded: Command.parseNumber,
virtualserverTotalBytesDownloaded: Command.parseNumber,
virtualserverTotalBytesUploaded: Command.parseNumber,
virtualserverPort: Command.parseNumber,
virtualserverAutostart: Command.parseNumber,
virtualserverMachineId: Command.parseString,
virtualserverNeededIdentitySecurityLevel: Command.parseNumber,
virtualserverLogClient: Command.parseNumber,
virtualserverLogQuery: Command.parseNumber,
virtualserverLogChannel: Command.parseNumber,
virtualserverLogPermissions: Command.parseNumber,
virtualserverLogServer: Command.parseNumber,
virtualserverLogFiletransfer: Command.parseNumber,
virtualserverMinClientVersion: Command.parseNumber,
virtualserverNamePhonetic: Command.parseString,
virtualserverIconId: Command.parseString,
virtualserverReservedSlots: Command.parseNumber,
virtualserverTotalPacketlossSpeech: Command.parseNumber,
virtualserverTotalPacketlossKeepalive: Command.parseNumber,
virtualserverTotalPacketlossControl: Command.parseNumber,
virtualserverTotalPacketlossTotal: Command.parseNumber,
virtualserverTotalPing: Command.parseNumber,
virtualserverIp: Command.parseStringArray,
virtualserverWeblistEnabled: Command.parseNumber,
virtualserverAskForPrivilegekey: Command.parseNumber,
virtualserverHostbannerMode: Command.parseNumber,
virtualserverChannelTempDeleteDelayDefault: Command.parseNumber,
virtualserverMinAndroidVersion: Command.parseNumber,
virtualserverMinIosVersion: Command.parseNumber,
virtualserverStatus: Command.parseString,
connectionFiletransferBandwidthSent: Command.parseNumber,
connectionFiletransferBandwidthReceived: Command.parseNumber,
connectionFiletransferBytesSentTotal: Command.parseNumber,
connectionFiletransferBytesReceivedTotal: Command.parseNumber,
connectionPacketsSentSpeech: Command.parseNumber,
connectionBytesSentSpeech: Command.parseNumber,
connectionPacketsReceivedSpeech: Command.parseNumber,
connectionBytesReceivedSpeech: Command.parseNumber,
connectionPacketsSentKeepalive: Command.parseNumber,
connectionBytesSentKeepalive: Command.parseNumber,
connectionPacketsReceivedKeepalive: Command.parseNumber,
connectionBytesReceivedKeepalive: Command.parseNumber,
connectionPacketsSentControl: Command.parseNumber,
connectionBytesSentControl: Command.parseNumber,
connectionPacketsReceivedControl: Command.parseNumber,
connectionBytesReceivedControl: Command.parseNumber,
connectionPacketsSentTotal: Command.parseNumber,
connectionBytesSentTotal: Command.parseNumber,
connectionPacketsReceivedTotal: Command.parseNumber,
connectionBytesReceivedTotal: Command.parseNumber,
connectionBandwidthSentLastSecondTotal: Command.parseNumber,
connectionBandwidthSentLastMinuteTotal: Command.parseNumber,
connectionBandwidthReceivedLastSecondTotal: Command.parseNumber,
connectionBandwidthReceivedLastMinuteTotal: Command.parseNumber,
connectionPacketlossTotal: Command.parseNumber,
connectionPing: Command.parseNumber,
clid: Command.parseString,
clientId: Command.parseString,
cldbid: Command.parseString,
clientDatabaseId: Command.parseString,
clientChannelId: Command.parseString,
clientOriginServerId: Command.parseString,
clientNickname: Command.parseString,
clientType: Command.parseNumber,
clientAway: Command.parseBoolean,
clientAwayMessage: Command.parseString,
clientFlagTalking: Command.parseBoolean,
clientInputMuted: Command.parseBoolean,
clientOutputMuted: Command.parseBoolean,
clientInputHardware: Command.parseBoolean,
clientOutputHardware: Command.parseBoolean,
clientTalkPower: Command.parseNumber,
clientIsTalker: Command.parseBoolean,
clientIsPrioritySpeaker: Command.parseNumber,
clientIsRecording: Command.parseBoolean,
clientIsChannelCommander: Command.parseBoolean,
clientUniqueIdentifier: Command.parseString,
clientServergroups: Command.parseStringArray,
clientChannelGroupId: Command.parseString,
clientChannelGroupInheritedChannelId: Command.parseString,
clientVersion: Command.parseString,
clientPlatform: Command.parseString,
clientIdleTime: Command.parseNumber,
clientCreated: Command.parseNumber,
clientLastconnected: Command.parseNumber,
clientIconId: Command.parseString,
clientCountry: Command.parseString,
clientEstimatedLocation: Command.parseString,
clientOutputonlyMuted: Command.parseNumber,
clientDefaultChannel: Command.parseString,
clientMetaData: Command.parseString,
clientVersionSign: Command.parseString,
clientSecurityHash: Command.parseString,
clientLoginName: Command.parseString,
clientLoginPassword: Command.parseString,
clientTotalconnections: Command.parseNumber,
clientFlagAvatar: Command.parseString,
clientTalkRequest: Command.parseBoolean,
clientTalkRequestMsg: Command.parseString,
clientMonthBytesUploaded: Command.parseNumber,
clientMonthBytesDownloaded: Command.parseNumber,
clientTotalBytesUploaded: Command.parseNumber,
clientTotalBytesDownloaded: Command.parseNumber,
clientNicknamePhonetic: Command.parseString,
clientDefaultToken: Command.parseString,
clientBadges: Command.parseString,
clientBase64HashClientUID: Command.parseString,
connectionConnectedTime: Command.parseNumber,
connectionClientIp: Command.parseString,
clientMyteamspeakId: Command.parseString,
clientIntegrations: Command.parseString,
clientDescription: Command.parseString,
clientNeededServerqueryViewPower: Command.parseNumber,
clientMyteamspeakAvatar: Command.parseString,
clientSignedBadges: Command.parseString,
clientLastip: Command.parseString,
cid: Command.parseString,
pid: Command.parseString,
cpid: Command.parseString,
order: Command.parseNumber,
channelOrder: Command.parseNumber,
channelName: Command.parseString,
channelPassword: Command.parseString,
channelDescription: Command.parseString,
channelTopic: Command.parseString,
channelFlagDefault: Command.parseBoolean,
channelFlagPassword: Command.parseBoolean,
channelFlagPermanent: Command.parseBoolean,
channelFlagSemiPermanent: Command.parseBoolean,
channelFlagTemporary: Command.parseBoolean,
channelCodec: Command.parseNumber,
channelCodecQuality: Command.parseNumber,
channelNeededTalkPower: Command.parseNumber,
channelIconId: Command.parseString,
totalClientsFamily: Command.parseNumber,
channelMaxclients: Command.parseNumber,
channelMaxfamilyclients: Command.parseNumber,
totalClients: Command.parseNumber,
channelNeededSubscribePower: Command.parseNumber,
channelCodecLatencyFactor: Command.parseNumber,
channelCodecIsUnencrypted: Command.parseNumber,
channelSecuritySalt: Command.parseString,
channelDeleteDelay: Command.parseNumber,
channelFlagMaxclientsUnlimited: Command.parseBoolean,
channelFlagMaxfamilyclientsUnlimited: Command.parseBoolean,
channelFlagMaxfamilyclientsInherited: Command.parseBoolean,
channelFilepath: Command.parseString,
channelForcedSilence: Command.parseNumber,
channelNamePhonetic: Command.parseString,
channelFlagPrivate: Command.parseBoolean,
channelBannerGfxUrl: Command.parseString,
channelBannerMode: Command.parseNumber,
secondsEmpty: Command.parseNumber,
cgid: Command.parseString,
sgid: Command.parseString,
permid: Command.parseString,
permvalue: Command.parseNumber,
permnegated: Command.parseBoolean,
permskip: Command.parseBoolean,
permsid: Command.parseString,
t: Command.parseNumber,
id1: Command.parseString,
id2: Command.parseString,
p: Command.parseNumber,
v: Command.parseNumber,
n: Command.parseNumber,
s: Command.parseNumber,
reasonid: Command.parseString,
reasonmsg: Command.parseString,
ctid: Command.parseString,
cfid: Command.parseString,
targetmode: Command.parseNumber,
target: Command.parseNumber,
invokerid: Command.parseString,
invokername: Command.parseString,
invokeruid: Command.parseString,
hash: Command.parseString,
lastPos: Command.parseNumber,
fileSize: Command.parseNumber,
l: Command.parseString,
path: Command.parseString,
size: Command.parseNumber,
clientftfid: Command.parseString,
serverftfid: Command.parseString,
currentSpeed: Command.parseNumber,
averageSpeed: Command.parseNumber,
runtime: Command.parseNumber,
sizedone: Command.parseNumber,
sender: Command.parseNumber,
status: Command.parseNumber,
ftkey: Command.parseString,
port: Command.parseNumber,
proto: Command.parseNumber,
datetime: Command.parseNumber,
hostTimestampUtc: Command.parseNumber,
instanceUptime: Command.parseNumber,
virtualserversRunningTotal: Command.parseNumber,
virtualserversTotalChannelsOnline: Command.parseNumber,
virtualserversTotalClientsOnline: Command.parseNumber,
virtualserversTotalMaxclients: Command.parseNumber,
serverinstanceDatabaseVersion: Command.parseNumber,
serverinstanceFiletransferPort: Command.parseNumber,
serverinstanceServerqueryMaxConnectionsPerIp: Command.parseNumber,
serverinstanceMaxDownloadTotalBandwidth: Command.parseNumber,
serverinstanceMaxUploadTotalBandwidth: Command.parseNumber,
serverinstanceGuestServerqueryGroup: Command.parseNumber,
serverinstancePendingConnectionsPerIp: Command.parseNumber,
serverinstancePermissionsVersion: Command.parseNumber,
serverinstanceServerqueryFloodBanTime: Command.parseNumber,
serverinstanceServerqueryFloodCommands: Command.parseNumber,
serverinstanceServerqueryFloodTime: Command.parseNumber,
serverinstanceTemplateChanneladminGroup: Command.parseString,
serverinstanceTemplateChanneldefaultGroup: Command.parseString,
serverinstanceTemplateServeradminGroup: Command.parseNumber,
serverinstanceTemplateServerdefaultGroup: Command.parseString,
msgid: Command.parseString,
timestamp: Command.parseNumber,
cluid: Command.parseString,
subject: Command.parseString,
message: Command.parseString,
version: Command.parseString,
build: Command.parseNumber,
platform: Command.parseString,
name: Command.parseString,
token: Command.parseString,
tokencustomset: Command.parseRecursive,
value: Command.parseString,
banid: Command.parseString,
id: Command.parseString,
msg: Command.parseString,
extraMsg: Command.parseString,
failedPermid: Command.parseString,
ident: Command.parseString,
ip: Command.parseString,
nickname: Command.parseString,
uid: Command.parseString,
desc: Command.parseString,
pwClear: Command.parseString,
start: Command.parseNumber,
end: Command.parseNumber,
tcid: Command.parseString,
permname: Command.parseString,
permdesc: Command.parseString,
tokenType: Command.parseNumber,
tokenCustomset: Command.parseRecursive,
token1: Command.parseString,
token2: Command.parseString,
tokenId1: Command.parseString,
tokenId2: Command.parseString,
tokenCreated: Command.parseNumber,
tokenDescription: Command.parseString,
flagRead: Command.parseBoolean,
tcldbid: Command.parseString,
tname: Command.parseString,
fcldbid: Command.parseString,
fname: Command.parseString,
mytsid: Command.parseString,
lastnickname: Command.parseString,
created: Command.parseNumber,
duration: Command.parseNumber,
invokercldbid: Command.parseString,
enforcements: Command.parseNumber,
reason: Command.parseString,
type: Command.parseNumber,
iconid: Command.parseString,
savedb: Command.parseNumber,
namemode: Command.parseNumber,
nModifyp: Command.parseNumber,
nMemberAddp: Command.parseNumber,
nMemberRemovep: Command.parseNumber,
sortid: Command.parseString,
count: Command.parseNumber,
salt: Command.parseString,
snapshot: Command.parseString,
apikey: Command.parseString,
scope: Command.parseString,
timeLeft: Command.parseNumber,
createdAt: Command.parseNumber,
expiresAt: Command.parseNumber
}
} | the_stack |
import { EventEmitter } from 'events'
import { Agent } from 'http'
import _ from 'lodash'
import WebSocket from 'ws'
import {
DisconnectedError,
NotConnectedError,
ConnectionError,
XrplError,
} from '../errors'
import { BaseRequest } from '../models/methods/baseMethod'
import ConnectionManager from './ConnectionManager'
import ExponentialBackoff from './ExponentialBackoff'
import RequestManager from './RequestManager'
const SECONDS_PER_MINUTE = 60
const TIMEOUT = 20
const CONNECTION_TIMEOUT = 5
/**
* ConnectionOptions is the configuration for the Connection class.
*/
interface ConnectionOptions {
trace?: boolean | ((id: string, message: string) => void)
proxy?: string
proxyAuthorization?: string
authorization?: string
trustedCertificates?: string[]
key?: string
passphrase?: string
certificate?: string
// request timeout
timeout: number
connectionTimeout: number
}
/**
* ConnectionUserOptions is the user-provided configuration object. All configuration
* is optional, so any ConnectionOptions configuration that has a default value is
* still optional at the point that the user provides it.
*/
export type ConnectionUserOptions = Partial<ConnectionOptions>
/**
* Represents an intentionally triggered web-socket disconnect code.
* WebSocket spec allows 4xxx codes for app/library specific codes.
* See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
*/
export const INTENTIONAL_DISCONNECT_CODE = 4000
type WebsocketState = 0 | 1 | 2 | 3
function getAgent(url: string, config: ConnectionOptions): Agent | undefined {
if (config.proxy == null) {
return undefined
}
const parsedURL = new URL(url)
const parsedProxyURL = new URL(config.proxy)
const proxyOptions = _.omitBy(
{
secureEndpoint: parsedURL.protocol === 'wss:',
secureProxy: parsedProxyURL.protocol === 'https:',
auth: config.proxyAuthorization,
ca: config.trustedCertificates,
key: config.key,
passphrase: config.passphrase,
cert: config.certificate,
href: parsedProxyURL.href,
origin: parsedProxyURL.origin,
protocol: parsedProxyURL.protocol,
username: parsedProxyURL.username,
password: parsedProxyURL.password,
host: parsedProxyURL.host,
hostname: parsedProxyURL.hostname,
port: parsedProxyURL.port,
pathname: parsedProxyURL.pathname,
search: parsedProxyURL.search,
hash: parsedProxyURL.hash,
},
(value) => value == null,
)
let HttpsProxyAgent: new (opt: typeof proxyOptions) => Agent
try {
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-require-imports,
node/global-require, global-require, -- Necessary for the `require` */
HttpsProxyAgent = require('https-proxy-agent')
/* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-require-imports,
node/global-require, global-require, */
} catch (_error) {
throw new Error('"proxy" option is not supported in the browser')
}
return new HttpsProxyAgent(proxyOptions)
}
/**
* Create a new websocket given your URL and optional proxy/certificate
* configuration.
*
* @param url - The URL to connect to.
* @param config - THe configuration options for the WebSocket.
* @returns A Websocket that fits the given configuration parameters.
*/
function createWebSocket(
url: string,
config: ConnectionOptions,
): WebSocket | null {
const options: WebSocket.ClientOptions = {}
options.agent = getAgent(url, config)
if (config.authorization != null) {
const base64 = Buffer.from(config.authorization).toString('base64')
options.headers = { Authorization: `Basic ${base64}` }
}
const optionsOverrides = _.omitBy(
{
ca: config.trustedCertificates,
key: config.key,
passphrase: config.passphrase,
cert: config.certificate,
},
(value) => value == null,
)
const websocketOptions = { ...options, ...optionsOverrides }
const websocket = new WebSocket(url, websocketOptions)
/*
* we will have a listener for each outstanding request,
* so we have to raise the limit (the default is 10)
*/
if (typeof websocket.setMaxListeners === 'function') {
websocket.setMaxListeners(Infinity)
}
return websocket
}
/**
* Ws.send(), but promisified.
*
* @param ws - Websocket to send with.
* @param message - Message to send.
* @returns When the message has been sent.
*/
async function websocketSendAsync(
ws: WebSocket,
message: string,
): Promise<void> {
return new Promise<void>((resolve, reject) => {
ws.send(message, (error) => {
if (error) {
reject(new DisconnectedError(error.message, error))
} else {
resolve()
}
})
})
}
/**
* The main Connection class. Responsible for connecting to & managing
* an active WebSocket connection to a XRPL node.
*/
export class Connection extends EventEmitter {
private readonly url: string | undefined
private ws: WebSocket | null = null
private reconnectTimeoutID: null | NodeJS.Timeout = null
private heartbeatIntervalID: null | NodeJS.Timeout = null
private readonly retryConnectionBackoff = new ExponentialBackoff({
min: 100,
max: SECONDS_PER_MINUTE * 1000,
})
private readonly config: ConnectionOptions
private readonly requestManager = new RequestManager()
private readonly connectionManager = new ConnectionManager()
/**
* Creates a new Connection object.
*
* @param url - URL to connect to.
* @param options - Options for the Connection object.
*/
public constructor(url?: string, options: ConnectionUserOptions = {}) {
super()
this.setMaxListeners(Infinity)
this.url = url
this.config = {
timeout: TIMEOUT * 1000,
connectionTimeout: CONNECTION_TIMEOUT * 1000,
...options,
}
if (typeof options.trace === 'function') {
this.trace = options.trace
} else if (options.trace) {
// eslint-disable-next-line no-console -- Used for tracing only
this.trace = console.log
}
}
/**
* Returns whether the websocket is connected.
*
* @returns Whether the websocket connection is open.
*/
public isConnected(): boolean {
return this.state === WebSocket.OPEN
}
/**
* Connects the websocket to the provided URL.
*
* @returns When the websocket is connected.
* @throws ConnectionError if there is a connection error, RippleError if there is already a WebSocket in existence.
*/
public async connect(): Promise<void> {
if (this.isConnected()) {
return Promise.resolve()
}
if (this.state === WebSocket.CONNECTING) {
return this.connectionManager.awaitConnection()
}
if (!this.url) {
return Promise.reject(
new ConnectionError('Cannot connect because no server was specified'),
)
}
if (this.ws != null) {
return Promise.reject(
new XrplError('Websocket connection never cleaned up.', {
state: this.state,
}),
)
}
// Create the connection timeout, in case the connection hangs longer than expected.
const connectionTimeoutID = setTimeout(() => {
this.onConnectionFailed(
new ConnectionError(
`Error: connect() timed out after ${this.config.connectionTimeout} ms. If your internet connection is working, the ` +
`rippled server may be blocked or inaccessible. You can also try setting the 'connectionTimeout' option in the Client constructor.`,
),
)
}, this.config.connectionTimeout)
// Connection listeners: these stay attached only until a connection is done/open.
this.ws = createWebSocket(this.url, this.config)
if (this.ws == null) {
throw new XrplError('Connect: created null websocket')
}
this.ws.on('error', (error) => this.onConnectionFailed(error))
this.ws.on('error', () => clearTimeout(connectionTimeoutID))
this.ws.on('close', (reason) => this.onConnectionFailed(reason))
this.ws.on('close', () => clearTimeout(connectionTimeoutID))
this.ws.once('open', () => {
void this.onceOpen(connectionTimeoutID)
})
return this.connectionManager.awaitConnection()
}
/**
* Disconnect the websocket connection.
* We never expect this method to reject. Even on "bad" disconnects, the websocket
* should still successfully close with the relevant error code returned.
* See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent for the full list.
* If no open websocket connection exists, resolve with no code (`undefined`).
*
* @returns A promise containing either `undefined` or a disconnected code, that resolves when the connection is destroyed.
*/
public async disconnect(): Promise<number | undefined> {
if (this.reconnectTimeoutID !== null) {
clearTimeout(this.reconnectTimeoutID)
this.reconnectTimeoutID = null
}
if (this.state === WebSocket.CLOSED) {
return Promise.resolve(undefined)
}
if (this.ws == null) {
return Promise.resolve(undefined)
}
return new Promise((resolve) => {
if (this.ws == null) {
resolve(undefined)
}
if (this.ws != null) {
this.ws.once('close', (code) => resolve(code))
}
/*
* Connection already has a disconnect handler for the disconnect logic.
* Just close the websocket manually (with our "intentional" code) to
* trigger that.
*/
if (this.ws != null && this.state !== WebSocket.CLOSING) {
this.ws.close(INTENTIONAL_DISCONNECT_CODE)
}
})
}
/**
* Disconnect the websocket, then connect again.
*/
public async reconnect(): Promise<void> {
/*
* NOTE: We currently have a "reconnecting" event, but that only triggers
* through an unexpected connection retry logic.
* See: https://github.com/XRPLF/xrpl.js/pull/1101#issuecomment-565360423
*/
this.emit('reconnect')
await this.disconnect()
await this.connect()
}
/**
* Sends a request to the rippled server.
*
* @param request - The request to send to the server.
* @param timeout - How long the Connection instance should wait before assuming that there will not be a response.
* @returns The response from the rippled server.
* @throws NotConnectedError if the Connection isn't connected to a server.
*/
public async request<T extends BaseRequest>(
request: T,
timeout?: number,
): Promise<unknown> {
if (!this.shouldBeConnected || this.ws == null) {
throw new NotConnectedError()
}
const [id, message, responsePromise] = this.requestManager.createRequest(
request,
timeout ?? this.config.timeout,
)
this.trace('send', message)
websocketSendAsync(this.ws, message).catch((error) => {
this.requestManager.reject(id, error)
})
return responsePromise
}
/**
* Get the Websocket connection URL.
*
* @returns The Websocket connection URL.
*/
public getUrl(): string {
return this.url ?? ''
}
// eslint-disable-next-line @typescript-eslint/no-empty-function -- Does nothing on default
public readonly trace: (id: string, message: string) => void = () => {}
/**
* Handler for when messages are received from the server.
*
* @param message - The message received from the server.
*/
private onMessage(message): void {
this.trace('receive', message)
let data: Record<string, unknown>
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Must be a JSON dictionary
data = JSON.parse(message)
} catch (error) {
if (error instanceof Error) {
this.emit('error', 'badMessage', error.message, message)
}
return
}
if (data.type == null && data.error) {
// e.g. slowDown
this.emit('error', data.error, data.error_message, data)
return
}
if (data.type) {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Should be true
this.emit(data.type as string, data)
}
if (data.type === 'response') {
try {
this.requestManager.handleResponse(data)
} catch (error) {
// eslint-disable-next-line max-depth -- okay here
if (error instanceof Error) {
this.emit('error', 'badMessage', error.message, message)
} else {
this.emit('error', 'badMessage', error, error)
}
}
}
}
/**
* Gets the state of the websocket.
*
* @returns The Websocket's ready state.
*/
private get state(): WebsocketState {
return this.ws ? this.ws.readyState : WebSocket.CLOSED
}
/**
* Returns whether the server should be connected.
*
* @returns Whether the server should be connected.
*/
private get shouldBeConnected(): boolean {
return this.ws !== null
}
/**
* Handler for what to do once the connection to the server is open.
*
* @param connectionTimeoutID - Timeout in case the connection hangs longer than expected.
* @returns A promise that resolves to void when the connection is fully established.
* @throws Error if the websocket initialized is somehow null.
*/
private async onceOpen(connectionTimeoutID: NodeJS.Timeout): Promise<void> {
if (this.ws == null) {
throw new XrplError('onceOpen: ws is null')
}
// Once the connection completes successfully, remove all old listeners
this.ws.removeAllListeners()
clearTimeout(connectionTimeoutID)
// Add new, long-term connected listeners for messages and errors
this.ws.on('message', (message: string) => this.onMessage(message))
this.ws.on('error', (error) =>
this.emit('error', 'websocket', error.message, error),
)
// Handle a closed connection: reconnect if it was unexpected
this.ws.once('close', (code, reason) => {
if (this.ws == null) {
throw new XrplError('onceClose: ws is null')
}
this.clearHeartbeatInterval()
this.requestManager.rejectAll(
new DisconnectedError(
`websocket was closed, ${new TextDecoder('utf-8').decode(reason)}`,
),
)
this.ws.removeAllListeners()
this.ws = null
this.emit('disconnected', code)
// If this wasn't a manual disconnect, then lets reconnect ASAP.
if (code !== INTENTIONAL_DISCONNECT_CODE) {
this.intentionalDisconnect()
}
})
// Finalize the connection and resolve all awaiting connect() requests
try {
this.retryConnectionBackoff.reset()
this.startHeartbeatInterval()
this.connectionManager.resolveAllAwaiting()
this.emit('connected')
} catch (error) {
if (error instanceof Error) {
this.connectionManager.rejectAllAwaiting(error)
// Ignore this error, propagate the root cause.
// eslint-disable-next-line @typescript-eslint/no-empty-function -- Need empty catch
await this.disconnect().catch(() => {})
}
}
}
private intentionalDisconnect(): void {
const retryTimeout = this.retryConnectionBackoff.duration()
this.trace('reconnect', `Retrying connection in ${retryTimeout}ms.`)
this.emit('reconnecting', this.retryConnectionBackoff.attempts)
/*
* Start the reconnect timeout, but set it to `this.reconnectTimeoutID`
* so that we can cancel one in-progress on disconnect.
*/
this.reconnectTimeoutID = setTimeout(() => {
this.reconnect().catch((error: Error) => {
this.emit('error', 'reconnect', error.message, error)
})
}, retryTimeout)
}
/**
* Clears the heartbeat connection interval.
*/
private clearHeartbeatInterval(): void {
if (this.heartbeatIntervalID) {
clearInterval(this.heartbeatIntervalID)
}
}
/**
* Starts a heartbeat to check the connection with the server.
*/
private startHeartbeatInterval(): void {
this.clearHeartbeatInterval()
this.heartbeatIntervalID = setInterval(() => {
void this.heartbeat()
}, this.config.timeout)
}
/**
* A heartbeat is just a "ping" command, sent on an interval.
* If this succeeds, we're good. If it fails, disconnect so that the consumer can reconnect, if desired.
*
* @returns A Promise that resolves to void when the heartbeat returns successfully.
*/
private async heartbeat(): Promise<void> {
this.request({ command: 'ping' }).catch(async () => {
return this.reconnect().catch((error: Error) => {
this.emit('error', 'reconnect', error.message, error)
})
})
}
/**
* Process a failed connection.
*
* @param errorOrCode - (Optional) Error or code for connection failure.
*/
private onConnectionFailed(errorOrCode: Error | number | null): void {
if (this.ws) {
this.ws.removeAllListeners()
this.ws.on('error', () => {
/*
* Correctly listen for -- but ignore -- any future errors: If you
* don't have a listener on "error" node would log a warning on error.
*/
})
this.ws.close()
this.ws = null
}
if (typeof errorOrCode === 'number') {
this.connectionManager.rejectAllAwaiting(
new NotConnectedError(`Connection failed with code ${errorOrCode}.`, {
code: errorOrCode,
}),
)
} else if (errorOrCode?.message) {
this.connectionManager.rejectAllAwaiting(
new NotConnectedError(errorOrCode.message, errorOrCode),
)
} else {
this.connectionManager.rejectAllAwaiting(
new NotConnectedError('Connection failed.'),
)
}
}
} | the_stack |
import { DataProvider } from '../ojdataprovider';
import { baseComponent, baseComponentEventMap, baseComponentSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojDataGrid<K, D> extends baseComponent<ojDataGridSettableProperties<K, D>> {
bandingInterval: {
column: number;
row: number;
};
cell: {
className?: ((context: ojDataGrid.CellContext<K, D>) => string | void | null) | string | null;
renderer?: ((context: ojDataGrid.CellContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
style?: ((context: ojDataGrid.CellContext<K, D>) => string | void | null) | string | null;
};
currentCell: ojDataGrid.CurrentCell<K> | null;
data: DataProvider<K, D>;
dnd: {
reorder: {
row: 'enable' | 'disable';
};
};
editMode: 'none' | 'cellNavigation' | 'cellEdit';
gridlines: {
horizontal: 'visible' | 'hidden';
vertical: 'visible' | 'hidden';
};
header: {
column: {
className?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
label: {
className?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
renderer?: ((context: ojDataGrid.LabelContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
style?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
};
renderer?: ((context: ojDataGrid.HeaderContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
resizable: {
height: 'enable' | 'disable';
width?: ((context: ojDataGrid.HeaderContext<K, D>) => string) | string | null;
};
sortable?: ((context: ojDataGrid.HeaderContext<K, D>) => string) | string | null;
style?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
};
columnEnd: {
className?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
label: {
className?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
renderer?: ((context: ojDataGrid.LabelContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
style?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
};
renderer?: ((context: ojDataGrid.HeaderContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
resizable: {
height: 'enable' | 'disable';
width?: ((context: ojDataGrid.HeaderContext<K, D>) => string) | string | null;
};
style?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
};
row: {
className?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
label: {
className?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
renderer?: ((context: ojDataGrid.LabelContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
style?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
};
renderer?: ((context: ojDataGrid.HeaderContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
resizable: {
height?: ((context: ojDataGrid.HeaderContext<K, D>) => string) | string | null;
width: 'enable' | 'disable';
};
sortable?: ((context: ojDataGrid.HeaderContext<K, D>) => string) | string | null;
style?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
};
rowEnd: {
className?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
label: {
className?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
renderer?: ((context: ojDataGrid.LabelContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
style?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
};
renderer?: ((context: ojDataGrid.HeaderContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
resizable: {
height?: ((context: ojDataGrid.HeaderContext<K, D>) => string) | string | null;
width: 'enable' | 'disable';
};
style?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
};
};
scrollPolicy: 'auto' | 'loadMoreOnScroll' | 'scroll';
scrollPolicyOptions: {
maxColumnCount: number;
maxRowCount: number;
};
scrollPosition: {
x?: number;
y?: number;
rowIndex?: number;
columnIndex?: number;
rowKey?: K;
columnKey?: K;
offsetX?: number;
offsetY?: number;
};
selection: Array<ojDataGrid.Selection<K>>;
selectionMode: {
cell: 'none' | 'single' | 'multiple';
row: 'none' | 'single' | 'multiple';
};
translations: {
accessibleActionableMode?: string;
accessibleColumnContext?: string;
accessibleColumnEndHeaderContext?: string;
accessibleColumnHeaderContext?: string;
accessibleColumnSelected?: string;
accessibleColumnSpanContext?: string;
accessibleFirstColumn?: string;
accessibleFirstRow?: string;
accessibleLastColumn?: string;
accessibleLastRow?: string;
accessibleLevelContext?: string;
accessibleMultiCellSelected?: string;
accessibleNavigationMode?: string;
accessibleRangeSelectModeOff?: string;
accessibleRangeSelectModeOn?: string;
accessibleRowCollapsed?: string;
accessibleRowContext?: string;
accessibleRowEndHeaderContext?: string;
accessibleRowExpanded?: string;
accessibleRowHeaderContext?: string;
accessibleRowSelected?: string;
accessibleRowSpanContext?: string;
accessibleSelectionAffordanceBottom?: string;
accessibleSelectionAffordanceTop?: string;
accessibleSortAscending?: string;
accessibleSortDescending?: string;
accessibleStateSelected?: string;
accessibleSummaryEstimate?: string;
accessibleSummaryExact?: string;
accessibleSummaryExpanded?: string;
labelCut?: string;
labelDisableNonContiguous?: string;
labelEnableNonContiguous?: string;
labelPaste?: string;
labelResize?: string;
labelResizeDialogSubmit?: string;
labelResizeHeight?: string;
labelResizeWidth?: string;
labelSortCol?: string;
labelSortColAsc?: string;
labelSortColDsc?: string;
labelSortRow?: string;
labelSortRowAsc?: string;
labelSortRowDsc?: string;
msgFetchingData?: string;
msgNoData?: string;
};
onBandingIntervalChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["bandingInterval"]>) => any) | null;
onCellChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["cell"]>) => any) | null;
onCurrentCellChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["currentCell"]>) => any) | null;
onDataChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["data"]>) => any) | null;
onDndChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["dnd"]>) => any) | null;
onEditModeChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["editMode"]>) => any) | null;
onGridlinesChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["gridlines"]>) => any) | null;
onHeaderChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["header"]>) => any) | null;
onScrollPolicyChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["scrollPolicy"]>) => any) | null;
onScrollPolicyOptionsChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["scrollPolicyOptions"]>) => any) | null;
onScrollPositionChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["scrollPosition"]>) => any) | null;
onSelectionChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["selection"]>) => any) | null;
onSelectionModeChanged: ((event: JetElementCustomEvent<ojDataGrid<K, D>["selectionMode"]>) => any) | null;
onOjBeforeCurrentCell: ((event: ojDataGrid.ojBeforeCurrentCell<K>) => any) | null;
onOjBeforeEdit: ((event: ojDataGrid.ojBeforeEdit<K, D>) => any) | null;
onOjBeforeEditEnd: ((event: ojDataGrid.ojBeforeEditEnd<K, D>) => any) | null;
onOjResize: ((event: ojDataGrid.ojResize) => any) | null;
onOjScroll: ((event: ojDataGrid.ojScroll) => any) | null;
onOjSort: ((event: ojDataGrid.ojSort) => any) | null;
addEventListener<T extends keyof ojDataGridEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojDataGridEventMap<K, D>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojDataGridSettableProperties<K, D>>(property: T): ojDataGrid<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojDataGridSettableProperties<K, D>>(property: T, value: ojDataGridSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojDataGridSettableProperties<K, D>>): void;
setProperties(properties: ojDataGridSettablePropertiesLenient<K, D>): void;
getContextByNode(node: Element): ojDataGrid.CellContext<K, D> & {
subId: 'oj-datagrid-cell';
} | ojDataGrid.HeaderContext<K, D> & {
subId: 'oj-datagrid-header';
} | ojDataGrid.LabelContext<K, D> & {
subId: 'oj-datagrid-header-label';
};
refresh(): void;
}
export namespace ojDataGrid {
interface ojBeforeCurrentCell<K> extends CustomEvent<{
currentCell: CurrentCell<K>;
previousCurrentCell: CurrentCell<K>;
[propName: string]: any;
}> {
}
interface ojBeforeEdit<K, D> extends CustomEvent<{
cellContext: CellContext<K, D>;
[propName: string]: any;
}> {
}
interface ojBeforeEditEnd<K, D> extends CustomEvent<{
cellContext: CellContext<K, D>;
cancelEdit: boolean;
[propName: string]: any;
}> {
}
interface ojResize extends CustomEvent<{
header: string | number;
oldDimensions: {
width: number;
height: number;
};
newDimensions: {
width: number;
height: number;
};
[propName: string]: any;
}> {
}
interface ojScroll extends CustomEvent<{
scrollX: number;
scrollY: number;
[propName: string]: any;
}> {
}
interface ojSort extends CustomEvent<{
header: any;
direction: 'ascending' | 'descending';
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type CellContext<K, D> = {
componentElement: Element;
parentElement: Element;
cell: D;
data: D;
datasource: DataProvider<K, D> | null;
indexes: {
row: number;
column: number;
};
keys: {
row: K;
column: K;
};
extents: {
row: number;
column: number;
};
mode: 'edit' | 'navigation';
};
// tslint:disable-next-line interface-over-type-literal
type CurrentCell<K> = {
type: 'cell' | 'header' | 'label';
axis?: 'column' | 'columnEnd' | 'row' | 'rowEnd';
index?: number;
level?: number;
key?: any;
indexes?: {
row: number;
column: number;
};
keys?: {
row: K;
column: K;
};
};
// tslint:disable-next-line interface-over-type-literal
type HeaderContext<K, D> = {
componentElement: Element;
parentElement: Element;
data: D;
datasource: DataProvider<K, D> | null;
axis: 'column' | 'columnEnd' | 'row' | 'rowEnd';
index: number;
key: K;
level: number;
extent: number;
depth: number;
};
// tslint:disable-next-line interface-over-type-literal
type LabelContext<K, D> = {
componentElement: Element;
parentElement: Element;
datasource: DataProvider<K, D> | null;
axis: 'column' | 'columnEnd' | 'row' | 'rowEnd';
key: K;
level: number;
};
// tslint:disable-next-line interface-over-type-literal
type Selection<K> = {
startIndex?: {
row: number;
column?: number;
};
startKey?: {
row: K;
column?: K;
};
endIndex?: {
row: number;
column?: number;
};
endKey?: {
row: K;
column?: K;
};
};
}
export interface ojDataGridEventMap<K, D> extends baseComponentEventMap<ojDataGridSettableProperties<K, D>> {
'ojBeforeCurrentCell': ojDataGrid.ojBeforeCurrentCell<K>;
'ojBeforeEdit': ojDataGrid.ojBeforeEdit<K, D>;
'ojBeforeEditEnd': ojDataGrid.ojBeforeEditEnd<K, D>;
'ojResize': ojDataGrid.ojResize;
'ojScroll': ojDataGrid.ojScroll;
'ojSort': ojDataGrid.ojSort;
'bandingIntervalChanged': JetElementCustomEvent<ojDataGrid<K, D>["bandingInterval"]>;
'cellChanged': JetElementCustomEvent<ojDataGrid<K, D>["cell"]>;
'currentCellChanged': JetElementCustomEvent<ojDataGrid<K, D>["currentCell"]>;
'dataChanged': JetElementCustomEvent<ojDataGrid<K, D>["data"]>;
'dndChanged': JetElementCustomEvent<ojDataGrid<K, D>["dnd"]>;
'editModeChanged': JetElementCustomEvent<ojDataGrid<K, D>["editMode"]>;
'gridlinesChanged': JetElementCustomEvent<ojDataGrid<K, D>["gridlines"]>;
'headerChanged': JetElementCustomEvent<ojDataGrid<K, D>["header"]>;
'scrollPolicyChanged': JetElementCustomEvent<ojDataGrid<K, D>["scrollPolicy"]>;
'scrollPolicyOptionsChanged': JetElementCustomEvent<ojDataGrid<K, D>["scrollPolicyOptions"]>;
'scrollPositionChanged': JetElementCustomEvent<ojDataGrid<K, D>["scrollPosition"]>;
'selectionChanged': JetElementCustomEvent<ojDataGrid<K, D>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojDataGrid<K, D>["selectionMode"]>;
}
export interface ojDataGridSettableProperties<K, D> extends baseComponentSettableProperties {
bandingInterval: {
column: number;
row: number;
};
cell: {
className?: ((context: ojDataGrid.CellContext<K, D>) => string | void | null) | string | null;
renderer?: ((context: ojDataGrid.CellContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
style?: ((context: ojDataGrid.CellContext<K, D>) => string | void | null) | string | null;
};
currentCell: ojDataGrid.CurrentCell<K> | null;
data: DataProvider<K, D> | null;
dnd: {
reorder: {
row: 'enable' | 'disable';
};
};
editMode: 'none' | 'cellNavigation' | 'cellEdit';
gridlines: {
horizontal: 'visible' | 'hidden';
vertical: 'visible' | 'hidden';
};
header: {
column: {
className?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
label: {
className?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
renderer?: ((context: ojDataGrid.LabelContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
style?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
};
renderer?: ((context: ojDataGrid.HeaderContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
resizable: {
height: 'enable' | 'disable';
width?: ((context: ojDataGrid.HeaderContext<K, D>) => string) | string | null;
};
sortable?: ((context: ojDataGrid.HeaderContext<K, D>) => string) | string | null;
style?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
};
columnEnd: {
className?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
label: {
className?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
renderer?: ((context: ojDataGrid.LabelContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
style?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
};
renderer?: ((context: ojDataGrid.HeaderContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
resizable: {
height: 'enable' | 'disable';
width?: ((context: ojDataGrid.HeaderContext<K, D>) => string) | string | null;
};
style?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
};
row: {
className?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
label: {
className?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
renderer?: ((context: ojDataGrid.LabelContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
style?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
};
renderer?: ((context: ojDataGrid.HeaderContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
resizable: {
height?: ((context: ojDataGrid.HeaderContext<K, D>) => string) | string | null;
width: 'enable' | 'disable';
};
sortable?: ((context: ojDataGrid.HeaderContext<K, D>) => string) | string | null;
style?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
};
rowEnd: {
className?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
label: {
className?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
renderer?: ((context: ojDataGrid.LabelContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
style?: ((context: ojDataGrid.LabelContext<K, D>) => string | void | null) | string | null;
};
renderer?: ((context: ojDataGrid.HeaderContext<K, D>) => {
insert: HTMLElement | string;
} | void | null) | null;
resizable: {
height?: ((context: ojDataGrid.HeaderContext<K, D>) => string) | string | null;
width: 'enable' | 'disable';
};
style?: ((context: ojDataGrid.HeaderContext<K, D>) => string | void | null) | string | null;
};
};
scrollPolicy: 'auto' | 'loadMoreOnScroll' | 'scroll';
scrollPolicyOptions: {
maxColumnCount: number;
maxRowCount: number;
};
scrollPosition: {
x?: number;
y?: number;
rowIndex?: number;
columnIndex?: number;
rowKey?: K;
columnKey?: K;
offsetX?: number;
offsetY?: number;
};
selection: Array<ojDataGrid.Selection<K>>;
selectionMode: {
cell: 'none' | 'single' | 'multiple';
row: 'none' | 'single' | 'multiple';
};
translations: {
accessibleActionableMode?: string;
accessibleColumnContext?: string;
accessibleColumnEndHeaderContext?: string;
accessibleColumnHeaderContext?: string;
accessibleColumnSelected?: string;
accessibleColumnSpanContext?: string;
accessibleFirstColumn?: string;
accessibleFirstRow?: string;
accessibleLastColumn?: string;
accessibleLastRow?: string;
accessibleLevelContext?: string;
accessibleMultiCellSelected?: string;
accessibleNavigationMode?: string;
accessibleRangeSelectModeOff?: string;
accessibleRangeSelectModeOn?: string;
accessibleRowCollapsed?: string;
accessibleRowContext?: string;
accessibleRowEndHeaderContext?: string;
accessibleRowExpanded?: string;
accessibleRowHeaderContext?: string;
accessibleRowSelected?: string;
accessibleRowSpanContext?: string;
accessibleSelectionAffordanceBottom?: string;
accessibleSelectionAffordanceTop?: string;
accessibleSortAscending?: string;
accessibleSortDescending?: string;
accessibleStateSelected?: string;
accessibleSummaryEstimate?: string;
accessibleSummaryExact?: string;
accessibleSummaryExpanded?: string;
labelCut?: string;
labelDisableNonContiguous?: string;
labelEnableNonContiguous?: string;
labelPaste?: string;
labelResize?: string;
labelResizeDialogSubmit?: string;
labelResizeHeight?: string;
labelResizeWidth?: string;
labelSortCol?: string;
labelSortColAsc?: string;
labelSortColDsc?: string;
labelSortRow?: string;
labelSortRowAsc?: string;
labelSortRowDsc?: string;
msgFetchingData?: string;
msgNoData?: string;
};
}
export interface ojDataGridSettablePropertiesLenient<K, D> extends Partial<ojDataGridSettableProperties<K, D>> {
[key: string]: any;
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [apigateway](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonapigatewaymanagement.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Apigateway extends PolicyStatement {
public servicePrefix = 'apigateway';
/**
* Statement provider for service [apigateway](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonapigatewaymanagement.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to add certificates for mutual TLS authentication to a domain name. This is an additional authorization control for managing the DomainName resource due to the sensitive nature of mTLS
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/apigateway/api-reference/ADD_CERTIFICATE_TO_DOMAIN.html
*/
public toAddCertificateToDomain() {
return this.to('AddCertificateToDomain');
}
/**
* Grants permission to delete a particular resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/apigateway/api-reference/API_DELETE.html
*/
public toDELETE() {
return this.to('DELETE');
}
/**
* Grants permission to read a particular resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/apigateway/api-reference/API_GET.html
*/
public toGET() {
return this.to('GET');
}
/**
* Grants permission to update a particular resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/apigateway/api-reference/API_PATCH.html
*/
public toPATCH() {
return this.to('PATCH');
}
/**
* Grants permission to create a particular resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/apigateway/api-reference/API_POST.html
*/
public toPOST() {
return this.to('POST');
}
/**
* Grants permission to update a particular resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/apigateway/api-reference/API_PUT.html
*/
public toPUT() {
return this.to('PUT');
}
/**
* Grants permission to remove certificates for mutual TLS authentication from a domain name. This is an additional authorization control for managing the DomainName resource due to the sensitive nature of mTLS
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/apigateway/api-reference/REMOVE_CERTIFICATE_FROM_DOMAIN.html
*/
public toRemoveCertificateFromDomain() {
return this.to('RemoveCertificateFromDomain');
}
/**
* Grants permission set a WAF access control list (ACL). This is an additional authorization control for managing the Stage resource due to the sensitive nature of WebAcl's
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/apigateway/api-reference/WEBACL_SET.html
*/
public toSetWebACL() {
return this.to('SetWebACL');
}
/**
* Grants permission to manage the IAM resource policy for an API. This is an additional authorization control for managing an API due to the sensitive nature of the resource policy
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/apigateway/api-reference/UPDATE_REST_API_POLICY.html
*/
public toUpdateRestApiPolicy() {
return this.to('UpdateRestApiPolicy');
}
protected accessLevelList: AccessLevelList = {
"Permissions management": [
"AddCertificateToDomain",
"RemoveCertificateFromDomain",
"SetWebACL",
"UpdateRestApiPolicy"
],
"Write": [
"DELETE",
"PATCH",
"POST",
"PUT"
],
"Read": [
"GET"
]
};
/**
* Adds a resource of type Account to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onAccount(region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/account';
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type ApiKey to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param apiKeyId - Identifier for the apiKeyId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onApiKey(apiKeyId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apikeys/${ApiKeyId}';
arn = arn.replace('${ApiKeyId}', apiKeyId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type ApiKeys to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onApiKeys(region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/apikeys';
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Authorizer to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param authorizerId - Identifier for the authorizerId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifRequestAuthorizerType()
* - .ifRequestAuthorizerUri()
* - .ifResourceAuthorizerType()
* - .ifResourceAuthorizerUri()
* - .ifAwsResourceTag()
*/
public onAuthorizer(restApiId: string, authorizerId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/authorizers/${AuthorizerId}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${AuthorizerId}', authorizerId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Authorizers to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifRequestAuthorizerType()
* - .ifRequestAuthorizerUri()
* - .ifAwsResourceTag()
*/
public onAuthorizers(restApiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/authorizers';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type BasePathMapping to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param domainName - Identifier for the domainName.
* @param basePath - Identifier for the basePath.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onBasePathMapping(domainName: string, basePath: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}/basepathmappings/${BasePath}';
arn = arn.replace('${DomainName}', domainName);
arn = arn.replace('${BasePath}', basePath);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type BasePathMappings to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param domainName - Identifier for the domainName.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onBasePathMappings(domainName: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}/basepathmappings';
arn = arn.replace('${DomainName}', domainName);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type ClientCertificate to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param clientCertificateId - Identifier for the clientCertificateId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onClientCertificate(clientCertificateId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/clientcertificates/${ClientCertificateId}';
arn = arn.replace('${ClientCertificateId}', clientCertificateId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type ClientCertificates to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onClientCertificates(region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/clientcertificates';
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Deployment to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param deploymentId - Identifier for the deploymentId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onDeployment(restApiId: string, deploymentId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/deployments/${DeploymentId}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${DeploymentId}', deploymentId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Deployments to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifRequestStageName()
*/
public onDeployments(restApiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/deployments';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type DocumentationPart to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param documentationPartId - Identifier for the documentationPartId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onDocumentationPart(restApiId: string, documentationPartId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/documentation/parts/${DocumentationPartId}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${DocumentationPartId}', documentationPartId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type DocumentationParts to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onDocumentationParts(restApiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/documentation/parts';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type DocumentationVersion to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param documentationVersionId - Identifier for the documentationVersionId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onDocumentationVersion(restApiId: string, documentationVersionId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/documentation/versions/${DocumentationVersionId}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${DocumentationVersionId}', documentationVersionId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type DocumentationVersions to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onDocumentationVersions(restApiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/documentation/versions';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type DomainName to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param domainName - Identifier for the domainName.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifRequestEndpointType()
* - .ifRequestMtlsTrustStoreUri()
* - .ifRequestMtlsTrustStoreVersion()
* - .ifRequestSecurityPolicy()
* - .ifResourceEndpointType()
* - .ifResourceMtlsTrustStoreUri()
* - .ifResourceMtlsTrustStoreVersion()
* - .ifResourceSecurityPolicy()
* - .ifAwsResourceTag()
*/
public onDomainName(domainName: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}';
arn = arn.replace('${DomainName}', domainName);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type DomainNames to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifRequestEndpointType()
* - .ifRequestMtlsTrustStoreUri()
* - .ifRequestMtlsTrustStoreVersion()
* - .ifRequestSecurityPolicy()
* - .ifAwsResourceTag()
*/
public onDomainNames(region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/domainnames';
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type GatewayResponse to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param responseType - Identifier for the responseType.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onGatewayResponse(restApiId: string, responseType: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/gatewayresponses/${ResponseType}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${ResponseType}', responseType);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type GatewayResponses to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onGatewayResponses(restApiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/gatewayresponses';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Integration to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param resourceId - Identifier for the resourceId.
* @param httpMethodType - Identifier for the httpMethodType.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onIntegration(restApiId: string, resourceId: string, httpMethodType: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/resources/${ResourceId}/methods/${HttpMethodType}/integration';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${HttpMethodType}', httpMethodType);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type IntegrationResponse to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param resourceId - Identifier for the resourceId.
* @param httpMethodType - Identifier for the httpMethodType.
* @param statusCode - Identifier for the statusCode.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onIntegrationResponse(restApiId: string, resourceId: string, httpMethodType: string, statusCode: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/resources/${ResourceId}/methods/${HttpMethodType}/integration/responses/${StatusCode}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${HttpMethodType}', httpMethodType);
arn = arn.replace('${StatusCode}', statusCode);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Method to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param resourceId - Identifier for the resourceId.
* @param httpMethodType - Identifier for the httpMethodType.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifRequestApiKeyRequired()
* - .ifRequestRouteAuthorizationType()
* - .ifResourceApiKeyRequired()
* - .ifResourceRouteAuthorizationType()
* - .ifAwsResourceTag()
*/
public onMethod(restApiId: string, resourceId: string, httpMethodType: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/resources/${ResourceId}/methods/${HttpMethodType}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${HttpMethodType}', httpMethodType);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type MethodResponse to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param resourceId - Identifier for the resourceId.
* @param httpMethodType - Identifier for the httpMethodType.
* @param statusCode - Identifier for the statusCode.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onMethodResponse(restApiId: string, resourceId: string, httpMethodType: string, statusCode: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/resources/${ResourceId}/methods/${HttpMethodType}/responses/${StatusCode}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${HttpMethodType}', httpMethodType);
arn = arn.replace('${StatusCode}', statusCode);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Model to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param modelName - Identifier for the modelName.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onModel(restApiId: string, modelName: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/models/${ModelName}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${ModelName}', modelName);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Models to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onModels(restApiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/models';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type RequestValidator to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param requestValidatorId - Identifier for the requestValidatorId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onRequestValidator(restApiId: string, requestValidatorId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/requestvalidators/${RequestValidatorId}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${RequestValidatorId}', requestValidatorId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type RequestValidators to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onRequestValidators(restApiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/requestvalidators';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Resource to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param resourceId - Identifier for the resourceId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onResource(restApiId: string, resourceId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/resources/${ResourceId}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Resources to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onResources(restApiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/resources';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type RestApi to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifRequestApiKeyRequired()
* - .ifRequestApiName()
* - .ifRequestAuthorizerType()
* - .ifRequestAuthorizerUri()
* - .ifRequestDisableExecuteApiEndpoint()
* - .ifRequestEndpointType()
* - .ifRequestRouteAuthorizationType()
* - .ifResourceApiKeyRequired()
* - .ifResourceApiName()
* - .ifResourceAuthorizerType()
* - .ifResourceAuthorizerUri()
* - .ifResourceDisableExecuteApiEndpoint()
* - .ifResourceEndpointType()
* - .ifResourceRouteAuthorizationType()
* - .ifAwsResourceTag()
*/
public onRestApi(restApiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type RestApis to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifRequestApiKeyRequired()
* - .ifRequestApiName()
* - .ifRequestAuthorizerType()
* - .ifRequestAuthorizerUri()
* - .ifRequestDisableExecuteApiEndpoint()
* - .ifRequestEndpointType()
* - .ifRequestRouteAuthorizationType()
* - .ifAwsResourceTag()
*/
public onRestApis(region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis';
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Sdk to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param stageName - Identifier for the stageName.
* @param sdkType - Identifier for the sdkType.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onSdk(restApiId: string, stageName: string, sdkType: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/stages/${StageName}/sdks/${SdkType}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${StageName}', stageName);
arn = arn.replace('${SdkType}', sdkType);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Stage to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param stageName - Identifier for the stageName.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifRequestAccessLoggingDestination()
* - .ifRequestAccessLoggingFormat()
* - .ifResourceAccessLoggingDestination()
* - .ifResourceAccessLoggingFormat()
* - .ifAwsResourceTag()
*/
public onStage(restApiId: string, stageName: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/stages/${StageName}';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${StageName}', stageName);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Stages to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param restApiId - Identifier for the restApiId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifRequestAccessLoggingDestination()
* - .ifRequestAccessLoggingFormat()
* - .ifAwsResourceTag()
*/
public onStages(restApiId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/stages';
arn = arn.replace('${RestApiId}', restApiId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Template to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param modelName - Identifier for the modelName.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onTemplate(modelName: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/restapis/models/${ModelName}/template';
arn = arn.replace('${ModelName}', modelName);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type UsagePlan to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param usagePlanId - Identifier for the usagePlanId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onUsagePlan(usagePlanId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/usageplans/${UsagePlanId}';
arn = arn.replace('${UsagePlanId}', usagePlanId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type UsagePlans to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onUsagePlans(region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/usageplans';
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type UsagePlanKey to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param usagePlanId - Identifier for the usagePlanId.
* @param id - Identifier for the id.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onUsagePlanKey(usagePlanId: string, id: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/usageplans/${UsagePlanId}/keys/${Id}';
arn = arn.replace('${UsagePlanId}', usagePlanId);
arn = arn.replace('${Id}', id);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type UsagePlanKeys to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param usagePlanId - Identifier for the usagePlanId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onUsagePlanKeys(usagePlanId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/usageplans/${UsagePlanId}/keys';
arn = arn.replace('${UsagePlanId}', usagePlanId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type VpcLink to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param vpcLinkId - Identifier for the vpcLinkId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onVpcLink(vpcLinkId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/vpclinks/${VpcLinkId}';
arn = arn.replace('${VpcLinkId}', vpcLinkId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type VpcLinks to the statement
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onVpcLinks(region?: string, partition?: string) {
var arn = 'arn:${Partition}:apigateway:${Region}::/vpclinks';
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Filters access by access log destination. Available during the CreateStage and UpdateStage operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Stage
* - Stages
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestAccessLoggingDestination(value: string | string[], operator?: Operator | string) {
return this.if(`Request/AccessLoggingDestination`, value, operator || 'StringLike');
}
/**
* Filters access by access log format. Available during the CreateStage and UpdateStage operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Stage
* - Stages
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestAccessLoggingFormat(value: string | string[], operator?: Operator | string) {
return this.if(`Request/AccessLoggingFormat`, value, operator || 'StringLike');
}
/**
* Filters access based on whether an API key is required or not. Available during the CreateMethod and PutMethod operations. Also available as a collection during import and reimport
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Method
* - RestApi
* - RestApis
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifRequestApiKeyRequired(value?: boolean) {
return this.if(`Request/ApiKeyRequired`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access by API name. Available during the CreateRestApi and UpdateRestApi operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - RestApi
* - RestApis
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestApiName(value: string | string[], operator?: Operator | string) {
return this.if(`Request/ApiName`, value, operator || 'StringLike');
}
/**
* Filters access by type of authorizer in the request, for example TOKEN, REQUEST, JWT. Available during CreateAuthorizer and UpdateAuthorizer. Also available during import and reimport as an ArrayOfString
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Authorizer
* - Authorizers
* - RestApi
* - RestApis
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestAuthorizerType(value: string | string[], operator?: Operator | string) {
return this.if(`Request/AuthorizerType`, value, operator || 'StringLike');
}
/**
* Filters access by URI of a Lambda authorizer function. Available during CreateAuthorizer and UpdateAuthorizer. Also available during import and reimport as an ArrayOfString
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Authorizer
* - Authorizers
* - RestApi
* - RestApis
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestAuthorizerUri(value: string | string[], operator?: Operator | string) {
return this.if(`Request/AuthorizerUri`, value, operator || 'StringLike');
}
/**
* Filters access by status of the default execute-api endpoint. Available during the CreateRestApi and DeleteRestApi operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - RestApi
* - RestApis
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifRequestDisableExecuteApiEndpoint(value?: boolean) {
return this.if(`Request/DisableExecuteApiEndpoint`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access by endpoint type. Available during the CreateDomainName, UpdateDomainName, CreateRestApi, and UpdateRestApi operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - DomainName
* - DomainNames
* - RestApi
* - RestApis
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestEndpointType(value: string | string[], operator?: Operator | string) {
return this.if(`Request/EndpointType`, value, operator || 'StringLike');
}
/**
* Filters access by URI of the truststore used for mutual TLS authentication. Available during the CreateDomainName and UpdateDomainName operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - DomainName
* - DomainNames
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestMtlsTrustStoreUri(value: string | string[], operator?: Operator | string) {
return this.if(`Request/MtlsTrustStoreUri`, value, operator || 'StringLike');
}
/**
* Filters access by version of the truststore used for mutual TLS authentication. Available during the CreateDomainName and UpdateDomainName operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - DomainName
* - DomainNames
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestMtlsTrustStoreVersion(value: string | string[], operator?: Operator | string) {
return this.if(`Request/MtlsTrustStoreVersion`, value, operator || 'StringLike');
}
/**
* Filters access by authorization type, for example NONE, AWS_IAM, CUSTOM, JWT, COGNITO_USER_POOLS. Available during the CreateMethod and PutMethod operations Also available as a collection during import
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Method
* - RestApi
* - RestApis
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestRouteAuthorizationType(value: string | string[], operator?: Operator | string) {
return this.if(`Request/RouteAuthorizationType`, value, operator || 'StringLike');
}
/**
* Filters access by TLS version. Available during the CreateDomain and UpdateDomain operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - DomainName
* - DomainNames
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestSecurityPolicy(value: string | string[], operator?: Operator | string) {
return this.if(`Request/SecurityPolicy`, value, operator || 'StringLike');
}
/**
* Filters access by stage name of the deployment that you attempt to create. Available during the CreateDeployment operation
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Deployments
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestStageName(value: string | string[], operator?: Operator | string) {
return this.if(`Request/StageName`, value, operator || 'StringLike');
}
/**
* Filters access by access log destination of the current Stage resource. Available during the UpdateStage and DeleteStage operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Stage
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceAccessLoggingDestination(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/AccessLoggingDestination`, value, operator || 'StringLike');
}
/**
* Filters access by access log format of the current Stage resource. Available during the UpdateStage and DeleteStage operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Stage
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceAccessLoggingFormat(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/AccessLoggingFormat`, value, operator || 'StringLike');
}
/**
* Filters access based on whether an API key is required or not for the existing Method resource. Available during the PutMethod and DeleteMethod operations. Also available as a collection during reimport
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Method
* - RestApi
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifResourceApiKeyRequired(value?: boolean) {
return this.if(`Resource/ApiKeyRequired`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access by API name of the existing RestApi resource. Available during UpdateRestApi and DeleteRestApi operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - RestApi
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceApiName(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/ApiName`, value, operator || 'StringLike');
}
/**
* Filters access by the current type of authorizer, for example TOKEN, REQUEST, JWT. Available during UpdateAuthorizer and DeleteAuthorizer operations. Also available during reimport as an ArrayOfString
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Authorizer
* - RestApi
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceAuthorizerType(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/AuthorizerType`, value, operator || 'StringLike');
}
/**
* Filters access by URI of a Lambda authorizer function. Available during UpdateAuthorizer and DeleteAuthorizer operations. Also available during reimport as an ArrayOfString
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Authorizer
* - RestApi
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceAuthorizerUri(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/AuthorizerUri`, value, operator || 'StringLike');
}
/**
* Filters access by status of the default execute-api endpoint of the current RestApi resource. Available during UpdateRestApi and DeleteRestApi operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - RestApi
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifResourceDisableExecuteApiEndpoint(value?: boolean) {
return this.if(`Resource/DisableExecuteApiEndpoint`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access by endpoint type. Available during the UpdateDomainName, DeleteDomainName, UpdateRestApi, and DeleteRestApi operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - DomainName
* - RestApi
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceEndpointType(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/EndpointType`, value, operator || 'StringLike');
}
/**
* Filters access by URI of the truststore used for mutual TLS authentication. Available during UpdateDomainName and DeleteDomainName operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - DomainName
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceMtlsTrustStoreUri(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/MtlsTrustStoreUri`, value, operator || 'StringLike');
}
/**
* Filters access by version of the truststore used for mutual TLS authentication. Available during UpdateDomainName and DeleteDomainName operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - DomainName
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceMtlsTrustStoreVersion(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/MtlsTrustStoreVersion`, value, operator || 'StringLike');
}
/**
* Filters access by authorization type of the existing Method resource, for example NONE, AWS_IAM, CUSTOM, JWT, COGNITO_USER_POOLS. Available during the PutMethod and DeleteMethod operations. Also available as a collection during reimport
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - Method
* - RestApi
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceRouteAuthorizationType(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/RouteAuthorizationType`, value, operator || 'StringLike');
}
/**
* Filters access by TLS version. Available during UpdateDomain and DeleteDomain operations
*
* https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_service-with-iam.html
*
* Applies to resource types:
* - DomainName
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceSecurityPolicy(value: string | string[], operator?: Operator | string) {
return this.if(`Resource/SecurityPolicy`, value, operator || 'StringLike');
}
} | the_stack |
import numeric = require("numeric");
const vector = [2, 5];
const matrix = [vector, vector];
const threeDimensionalMatrix = [[[2, 3], [2, 3], [3, 5]]];
const sparseMatrix: [number[], number[], number[]] = [vector, vector, vector];
numeric.bench(() => null, 150); // $ExpectType number
numeric.prettyPrint(vector); // $ExpectType string
numeric.parseDate("08-08-17"); // $ExpectType number
numeric.parseDate(["08-05-87", "08-05-75"]); // $ExpectType number[]
numeric.parseFloat("55.24"); // $ExpectType number
numeric.parseFloat(["25.15", "44.25", "as"]); // $ExpectType number[]
numeric.parseCSV("car, bike"); // $ExpectType string[][]
numeric.toCSV([[25, 52, 62, 66], ["car", "bad", "bike", {}]]); // $ExpectType string
numeric.imageURL([[25, 50], [52, 52]]); // $ExpectType string
numeric.getURL('sdf'); // $ExpectType any
numeric.dim(matrix); // $ExpectType number[] || Vector
numeric.same(25, [25]); // $ExpectType boolean
numeric.rep([2, 5], true);
numeric.dotMMsmall(matrix, matrix); // $ExpectType number[][] || Matrix
numeric.dotMMbig(matrix, matrix); // $ExpectType number[][] || Matrix
numeric.dotMV(matrix, vector); // $ExpectType number[] || Vector
numeric.dotVM(vector, matrix); // $ExpectType number[] || Vector
numeric.dotVV(vector, vector); // $ExpectType number
numeric.dot(vector, matrix); // $ExpectType number | number[] | number[][] || number | Vector | Matrix
numeric.diag([25, 52]); // $ExpectType number[][] || Matrix
numeric.getDiag(matrix); // $ExpectType number[] || Vector
numeric.identity(24); // $ExpectType number[][] || Matrix
numeric.abs(matrix); // $ExpectType number[][] || Matrix
numeric.absV(vector); // $ExpectType number[] || Vector
numeric.abseqV(vector); // $ExpectType number[] || Vector
numeric.abseq(matrix); // $ExpectType number[][] || Matrix
numeric.acos(matrix); // $ExpectType number[][] || Matrix
numeric.acosV(vector); // $ExpectType number[] || Vector
numeric.acoseqV(vector); // $ExpectType number[] || Vector
numeric.acoseq(matrix); // $ExpectType number[][] || Matrix
numeric.asin(matrix); // $ExpectType number[][] || Matrix
numeric.asinV(vector); // $ExpectType number[] || Vector
numeric.asineqV(vector); // $ExpectType number[] || Vector
numeric.asineq(matrix); // $ExpectType number[][] || Matrix
numeric.atan(matrix); // $ExpectType number[][] || Matrix
numeric.atanV(vector); // $ExpectType number[] || Vector
numeric.ataneqV(vector); // $ExpectType number[] || Vector
numeric.ataneq(matrix); // $ExpectType number[][] || Matrix
numeric.ceil(matrix); // $ExpectType number[][] || Matrix
numeric.ceilV(vector); // $ExpectType number[] || Vector
numeric.ceileqV(vector); // $ExpectType number[] || Vector
numeric.ceileq(matrix); // $ExpectType number[][] || Matrix
numeric.cos(matrix); // $ExpectType number[][] || Matrix
numeric.cosV(vector); // $ExpectType number[] || Vector
numeric.coseqV(vector); // $ExpectType number[] || Vector
numeric.coseq(matrix); // $ExpectType number[][] || Matrix
numeric.exp(matrix); // $ExpectType number[][] || Matrix
numeric.expV(vector); // $ExpectType number[] || Vector
numeric.expeqV(vector); // $ExpectType number[] || Vector
numeric.expeq(matrix); // $ExpectType number[][] || Matrix
numeric.floor(matrix); // $ExpectType number[][] || Matrix
numeric.floorV(vector); // $ExpectType number[] || Vector
numeric.flooreqV(vector); // $ExpectType number[] || Vector
numeric.flooreq(matrix); // $ExpectType number[][] || Matrix
numeric.log(matrix); // $ExpectType number[][] || Matrix
numeric.logV(vector); // $ExpectType number[] || Vector
numeric.logeqV(vector); // $ExpectType number[] || Vector
numeric.logeq(matrix); // $ExpectType number[][] || Matrix
numeric.round(matrix); // $ExpectType number[][] || Matrix
numeric.roundV(vector); // $ExpectType number[] || Vector
numeric.roundeqV(vector); // $ExpectType number[] || Vector
numeric.roundeq(matrix); // $ExpectType number[][] || Matrix
numeric.sin(matrix); // $ExpectType number[][] || Matrix
numeric.sinV(vector); // $ExpectType number[] || Vector
numeric.sineqV(vector); // $ExpectType number[] || Vector
numeric.sineq(matrix); // $ExpectType number[][] || Matrix
numeric.sqrt(matrix); // $ExpectType number[][] || Matrix
numeric.sqrtV(vector); // $ExpectType number[] || Vector
numeric.sqrteqV(vector); // $ExpectType number[] || Vector
numeric.sqrteq(matrix); // $ExpectType number[][] || Matrix
numeric.tan(matrix); // $ExpectType number[][] || Matrix
numeric.tanV(vector); // $ExpectType number[] || Vector
numeric.taneqV(vector); // $ExpectType number[] || Vector
numeric.taneq(matrix); // $ExpectType number[][] || Matrix
numeric.isNaN(vector); // $ExpectType boolean[] || VectorBoolean
numeric.isNaN(threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric.isNaNV(vector); // $ExpectType boolean[] || VectorBoolean
numeric.isNaNeqV(vector); // $ExpectType boolean[] || VectorBoolean
numeric.isNaNeq(vector); // $ExpectType boolean[] || VectorBoolean
numeric.isNaNeq(threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric.isFinite(vector); // $ExpectType boolean[] || VectorBoolean
numeric.isFinite(threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric.isFiniteV(vector); // $ExpectType boolean[] || VectorBoolean
numeric.isFiniteeqV(vector); // $ExpectType boolean[] || VectorBoolean
numeric.isFiniteeq(vector); // $ExpectType boolean[] || VectorBoolean
numeric.isFiniteeq(threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric.neg(matrix); // $ExpectType number[][] || Matrix
numeric.negV(vector); // $ExpectType number[] || Vector
numeric.negeqV(vector); // $ExpectType number[] || Vector
numeric.negeq(matrix); // $ExpectType number[][] || Matrix
numeric.bnot(matrix); // $ExpectType number[][] || Matrix
numeric.bnotV(vector); // $ExpectType number[] || Vector
numeric.bnoteqV(vector); // $ExpectType number[] || Vector
numeric.bnoteq(matrix); // $ExpectType number[][] || Matrix
numeric.not(2); // $ExpectType boolean
numeric.not(vector); // $ExpectType boolean[] || VectorBoolean
numeric.not(threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric.notV(vector); // $ExpectType boolean[] || VectorBoolean
numeric.noteq(2); // $ExpectType boolean
numeric.noteq(vector); // $ExpectType boolean[] || VectorBoolean
numeric.noteq(threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric.noteqV(vector); // $ExpectType boolean[] || VectorBoolean
numeric.clone(vector); // $ExpectType number[] || Vector
numeric.cloneV(vector); // $ExpectType NonNullPrimitive[]
numeric.cloneeq(vector); // $ExpectType NonNullPrimitive[]
numeric.cloneeqV(vector); // $ExpectType NonNullPrimitive[]
numeric.add(2, 5, 6); // $ExpectType number
numeric.add(2, 3, vector); // $ExpectType number[] || Vector
numeric.add(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric["+"](2, 5, 6); // $ExpectType number
numeric["+"](2, 3, vector); // $ExpectType number[] || Vector
numeric["+"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.addVV(vector, vector); // $ExpectType number[] || Vector
numeric.addSV(2, vector); // $ExpectType number[] || Vector
numeric.addVS(vector, 2); // $ExpectType number[] || Vector
numeric.addeq(vector, 3); // $ExpectType number[] || Vector
numeric.addeqV(vector, vector); // $ExpectType number[] || Vector
numeric.addeqS(vector, 3); // $ExpectType number[] || Vector
numeric.sub(2, 5, 6); // $ExpectType number
numeric.sub(2, 3, vector); // $ExpectType number[] || Vector
numeric.sub(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric["-"](2, 5, 6); // $ExpectType number
numeric["-"](2, 3, vector); // $ExpectType number[] || Vector
numeric["-"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.subVV(vector, vector); // $ExpectType number[] || Vector
numeric.subSV(2, vector); // $ExpectType number[] || Vector
numeric.subVS(vector, 2); // $ExpectType number[] || Vector
numeric.subeq(vector, 3); // $ExpectType number[] || Vector
numeric.subeqV(vector, vector); // $ExpectType number[] || Vector
numeric.subeqS(vector, 3); // $ExpectType number[] || Vector
numeric.mul(2, 5, 6); // $ExpectType number
numeric.mul(2, 3, vector); // $ExpectType number[] || Vector
numeric.mul(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric["*"](2, 5, 6); // $ExpectType number
numeric["*"](2, 3, vector); // $ExpectType number[] || Vector
numeric["*"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.mulVV(vector, vector); // $ExpectType number[] || Vector
numeric.mulSV(2, vector); // $ExpectType number[] || Vector
numeric.mulVS(vector, 2); // $ExpectType number[] || Vector
numeric.muleq(vector, 3); // $ExpectType number[] || Vector
numeric.muleqV(vector, vector); // $ExpectType number[] || Vector
numeric.muleqS(vector, 3); // $ExpectType number[] || Vector
numeric.div(2, 5, 6); // $ExpectType number
numeric.div(2, 3, vector); // $ExpectType number[] || Vector
numeric.div(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric["/"](2, 5, 6); // $ExpectType number
numeric["/"](2, 3, vector); // $ExpectType number[] || Vector
numeric["/"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.divVV(vector, vector); // $ExpectType number[] || Vector
numeric.divSV(2, vector); // $ExpectType number[] || Vector
numeric.divVS(vector, 2); // $ExpectType number[] || Vector
numeric.diveq(vector, 3); // $ExpectType number[] || Vector
numeric.diveqV(vector, vector); // $ExpectType number[] || Vector
numeric.diveqS(vector, 3); // $ExpectType number[] || Vector
numeric.mod(2, 5, 6); // $ExpectType number
numeric.mod(2, 3, vector); // $ExpectType number[] || Vector
numeric.mod(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric["%"](2, 5, 6); // $ExpectType number
numeric["%"](2, 3, vector); // $ExpectType number[] || Vector
numeric["%"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.modVV(vector, vector); // $ExpectType number[] || Vector
numeric.modSV(2, vector); // $ExpectType number[] || Vector
numeric.modVS(vector, 2); // $ExpectType number[] || Vector
numeric.modeq(vector, 3); // $ExpectType number[] || Vector
numeric.modeqV(vector, vector); // $ExpectType number[] || Vector
numeric.modeqS(vector, 3); // $ExpectType number[] || Vector
numeric.and(2, 5, 6); // $ExpectType number
numeric.and(2, 3, vector); // $ExpectType number[] || Vector
numeric.and(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric["&&"](2, 5, 6); // $ExpectType number
numeric["&&"](2, 3, vector); // $ExpectType number[] || Vector
numeric["&&"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.andVV(vector, vector); // $ExpectType number[] || Vector
numeric.andSV(2, vector); // $ExpectType number[] || Vector
numeric.andVS(vector, 2); // $ExpectType number[] || Vector
numeric.andeq(vector, 3); // $ExpectType number[] || Vector
numeric.andeqV(vector, vector); // $ExpectType number[] || Vector
numeric.andeqS(vector, 3); // $ExpectType number[] || Vector
numeric.or(2, 5, 6); // $ExpectType number
numeric.or(2, 3, vector); // $ExpectType number[] || Vector
numeric.or(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric["||"](2, 5, 6); // $ExpectType number
numeric["||"](2, 3, vector); // $ExpectType number[] || Vector
numeric["||"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.orVV(vector, vector); // $ExpectType number[] || Vector
numeric.orSV(2, vector); // $ExpectType number[] || Vector
numeric.orVS(vector, 2); // $ExpectType number[] || Vector
numeric.oreq(vector, 3); // $ExpectType number[] || Vector
numeric.oreqV(vector, vector); // $ExpectType number[] || Vector
numeric.oreqS(vector, 3); // $ExpectType number[] || Vector
numeric.eq(2, 5); // $ExpectType boolean
numeric.eq(2, vector); // $ExpectType boolean[] || VectorBoolean
numeric.eq(threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric["==="](2, 5); // $ExpectType boolean
numeric["==="](2, vector); // $ExpectType boolean[] || VectorBoolean
numeric["==="](threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric.eqVV(vector, vector); // $ExpectType boolean[] || VectorBoolean
numeric.eqSV(2, vector); // $ExpectType boolean[] || VectorBoolean
numeric.eqVS(vector, 2); // $ExpectType boolean[] || VectorBoolean
numeric.eqeq(vector, 3); // $ExpectType boolean[] || VectorBoolean
numeric.eqeqV(vector, vector); // $ExpectType boolean[] || VectorBoolean
numeric.eqeqS(vector, 3); // $ExpectType boolean[] || VectorBoolean
numeric.neq(2, 5); // $ExpectType boolean
numeric.neq(2, vector); // $ExpectType boolean[] || VectorBoolean
numeric.neq(threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric["==="](2, 5); // $ExpectType boolean
numeric["==="](2, vector); // $ExpectType boolean[] || VectorBoolean
numeric["==="](threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric.neqVV(vector, vector); // $ExpectType boolean[] || VectorBoolean
numeric.neqSV(2, vector); // $ExpectType boolean[] || VectorBoolean
numeric.neqVS(vector, 2); // $ExpectType boolean[] || VectorBoolean
numeric.neqeq(vector, 3); // $ExpectType boolean[] || VectorBoolean
numeric.neqeqV(vector, vector); // $ExpectType boolean[] || VectorBoolean
numeric.neqeqS(vector, 3); // $ExpectType boolean[] || VectorBoolean
numeric.lt(2, 5); // $ExpectType boolean
numeric.lt(2, vector); // $ExpectType boolean[] || VectorBoolean
numeric.lt(threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric["==="](2, 5); // $ExpectType boolean
numeric["==="](2, vector); // $ExpectType boolean[] || VectorBoolean
numeric["==="](threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric.ltVV(vector, vector); // $ExpectType boolean[] || VectorBoolean
numeric.ltSV(2, vector); // $ExpectType boolean[] || VectorBoolean
numeric.ltVS(vector, 2); // $ExpectType boolean[] || VectorBoolean
numeric.lteq(vector, 3); // $ExpectType boolean[] || VectorBoolean
numeric.lteqV(vector, vector); // $ExpectType boolean[] || VectorBoolean
numeric.lteqS(vector, 3); // $ExpectType boolean[] || VectorBoolean
numeric.gt(2, 5); // $ExpectType boolean
numeric.gt(2, vector); // $ExpectType boolean[] || VectorBoolean
numeric.gt(threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric["==="](2, 5); // $ExpectType boolean
numeric["==="](2, vector); // $ExpectType boolean[] || VectorBoolean
numeric["==="](threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric.gtVV(vector, vector); // $ExpectType boolean[] || VectorBoolean
numeric.gtSV(2, vector); // $ExpectType boolean[] || VectorBoolean
numeric.gtVS(vector, 2); // $ExpectType boolean[] || VectorBoolean
numeric.gteq(vector, 3); // $ExpectType boolean[] || VectorBoolean
numeric.gteqV(vector, vector); // $ExpectType boolean[] || VectorBoolean
numeric.gteqS(vector, 3); // $ExpectType boolean[] || VectorBoolean
numeric.leq(2, 5); // $ExpectType boolean
numeric.leq(2, vector); // $ExpectType boolean[] || VectorBoolean
numeric.leq(threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric["==="](2, 5); // $ExpectType boolean
numeric["==="](2, vector); // $ExpectType boolean[] || VectorBoolean
numeric["==="](threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric.leqVV(vector, vector); // $ExpectType boolean[] || VectorBoolean
numeric.leqSV(2, vector); // $ExpectType boolean[] || VectorBoolean
numeric.leqVS(vector, 2); // $ExpectType boolean[] || VectorBoolean
numeric.leqeq(vector, 3); // $ExpectType boolean[] || VectorBoolean
numeric.leqeqV(vector, vector); // $ExpectType boolean[] || VectorBoolean
numeric.leqeqS(vector, 3); // $ExpectType boolean[] || VectorBoolean
numeric.geq(2, 5); // $ExpectType boolean
numeric.geq(2, vector); // $ExpectType boolean[] || VectorBoolean
numeric.geq(threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric["==="](2, 5); // $ExpectType boolean
numeric["==="](2, vector); // $ExpectType boolean[] || VectorBoolean
numeric["==="](threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray<boolean>
numeric.geqVV(vector, vector); // $ExpectType boolean[] || VectorBoolean
numeric.geqSV(2, vector); // $ExpectType boolean[] || VectorBoolean
numeric.geqVS(vector, 2); // $ExpectType boolean[] || VectorBoolean
numeric.geqeq(vector, 3); // $ExpectType boolean[] || VectorBoolean
numeric.geqeqV(vector, vector); // $ExpectType boolean[] || VectorBoolean
numeric.geqeqS(vector, 3); // $ExpectType boolean[] || VectorBoolean
numeric.band(2, 5, 6); // $ExpectType number
numeric.band(2, 3, vector); // $ExpectType number[] || Vector
numeric.band(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric["&"](2, 5, 6); // $ExpectType number
numeric["&"](2, 3, vector); // $ExpectType number[] || Vector
numeric["&"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.bandVV(vector, vector); // $ExpectType number[] || Vector
numeric.bandSV(2, vector); // $ExpectType number[] || Vector
numeric.bandVS(vector, 2); // $ExpectType number[] || Vector
numeric.bandeq(vector, 3); // $ExpectType number[] || Vector
numeric.bandeqV(vector, vector); // $ExpectType number[] || Vector
numeric.bandeqS(vector, 3); // $ExpectType number[] || Vector
numeric.bor(2, 5, 6); // $ExpectType number
numeric.bor(2, 3, vector); // $ExpectType number[] || Vector
numeric.bor(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric["|"](2, 5, 6); // $ExpectType number
numeric["|"](2, 3, vector); // $ExpectType number[] || Vector
numeric["|"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.borVV(vector, vector); // $ExpectType number[] || Vector
numeric.borSV(2, vector); // $ExpectType number[] || Vector
numeric.borVS(vector, 2); // $ExpectType number[] || Vector
numeric.boreq(vector, 3); // $ExpectType number[] || Vector
numeric.boreqV(vector, vector); // $ExpectType number[] || Vector
numeric.boreqS(vector, 3); // $ExpectType number[] || Vector
numeric.bxor(2, 5, 6); // $ExpectType number
numeric.bxor(2, 3, vector); // $ExpectType number[] || Vector
numeric.bxor(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric["^"](2, 5, 6); // $ExpectType number
numeric["^"](2, 3, vector); // $ExpectType number[] || Vector
numeric["^"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.bxorVV(vector, vector); // $ExpectType number[] || Vector
numeric.bxorSV(2, vector); // $ExpectType number[] || Vector
numeric.bxorVS(vector, 2); // $ExpectType number[] || Vector
numeric.bxoreq(vector, 3); // $ExpectType number[] || Vector
numeric.bxoreqV(vector, vector); // $ExpectType number[] || Vector
numeric.bxoreqS(vector, 3); // $ExpectType number[] || Vector
numeric.lshift(2, 5, 6); // $ExpectType number
numeric.lshift(2, 3, vector); // $ExpectType number[] || Vector
numeric.lshift(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric["<<"](2, 5, 6); // $ExpectType number
numeric["<<"](2, 3, vector); // $ExpectType number[] || Vector
numeric["<<"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.lshiftVV(vector, vector); // $ExpectType number[] || Vector
numeric.lshiftSV(2, vector); // $ExpectType number[] || Vector
numeric.lshiftVS(vector, 2); // $ExpectType number[] || Vector
numeric.lshifteq(vector, 3); // $ExpectType number[] || Vector
numeric.lshifteqV(vector, vector); // $ExpectType number[] || Vector
numeric.lshifteqS(vector, 3); // $ExpectType number[] || Vector
numeric.rshift(2, 5, 6); // $ExpectType number
numeric.rshift(2, 3, vector); // $ExpectType number[] || Vector
numeric.rshift(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric[">>"](2, 5, 6); // $ExpectType number
numeric[">>"](2, 3, vector); // $ExpectType number[] || Vector
numeric[">>"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.rshiftVV(vector, vector); // $ExpectType number[] || Vector
numeric.rshiftSV(2, vector); // $ExpectType number[] || Vector
numeric.rshiftVS(vector, 2); // $ExpectType number[] || Vector
numeric.rshifteq(vector, 3); // $ExpectType number[] || Vector
numeric.rshifteqV(vector, vector); // $ExpectType number[] || Vector
numeric.rshifteqS(vector, 3); // $ExpectType number[] || Vector
numeric.rrshift(2, 5, 6); // $ExpectType number
numeric.rrshift(2, 3, vector); // $ExpectType number[] || Vector
numeric.rrshift(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric[">>>"](2, 5, 6); // $ExpectType number
numeric[">>>"](2, 3, vector); // $ExpectType number[] || Vector
numeric[">>>"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][]
numeric.rrshiftVV(vector, vector); // $ExpectType number[] || Vector
numeric.rrshiftSV(2, vector); // $ExpectType number[] || Vector
numeric.rrshiftVS(vector, 2); // $ExpectType number[] || Vector
numeric.rrshifteq(vector, 3); // $ExpectType number[] || Vector
numeric.rrshifteqV(vector, vector); // $ExpectType number[] || Vector
numeric.rrshifteqS(vector, 3); // $ExpectType number[] || Vector
numeric.atan2(2, 5, 6); // $ExpectType number
numeric.atan2(2, 3, vector); // $ExpectType number[] || Vector
numeric.atan2(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric.atan2VV(vector, vector); // $ExpectType number[] || Vector
numeric.atan2SV(2, vector); // $ExpectType number[] || Vector
numeric.atan2VS(vector, 2); // $ExpectType number[] || Vector
numeric.atan2eq(vector, 3); // $ExpectType number[] || Vector
numeric.atan2eqV(vector, vector); // $ExpectType number[] || Vector
numeric.atan2eqS(vector, 3); // $ExpectType number[] || Vector
numeric.pow(2, 5, 6); // $ExpectType number
numeric.pow(2, 3, vector); // $ExpectType number[] || Vector
numeric.pow(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric.powVV(vector, vector); // $ExpectType number[] || Vector
numeric.powSV(2, vector); // $ExpectType number[] || Vector
numeric.powVS(vector, 2); // $ExpectType number[] || Vector
numeric.poweq(vector, 3); // $ExpectType number[] || Vector
numeric.poweqV(vector, vector); // $ExpectType number[] || Vector
numeric.poweqS(vector, 3); // $ExpectType number[] || Vector
numeric.max(2, 5, 6); // $ExpectType number
numeric.max(2, 3, vector); // $ExpectType number[] || Vector
numeric.max(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric.maxVV(vector, vector); // $ExpectType number[] || Vector
numeric.maxSV(2, vector); // $ExpectType number[] || Vector
numeric.maxVS(vector, 2); // $ExpectType number[] || Vector
numeric.maxeq(vector, 3); // $ExpectType number[] || Vector
numeric.maxeqV(vector, vector); // $ExpectType number[] || Vector
numeric.maxeqS(vector, 3); // $ExpectType number[] || Vector
numeric.min(2, 5, 6); // $ExpectType number
numeric.min(2, 3, vector); // $ExpectType number[] || Vector
numeric.min(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][]
numeric.minVV(vector, vector); // $ExpectType number[] || Vector
numeric.minSV(2, vector); // $ExpectType number[] || Vector
numeric.minVS(vector, 2); // $ExpectType number[] || Vector
numeric.mineq(vector, 3); // $ExpectType number[] || Vector
numeric.mineqV(vector, vector); // $ExpectType number[] || Vector
numeric.mineqS(vector, 3); // $ExpectType number[] || Vector
numeric.any(23); // $ExpectType boolean
numeric.anyV(vector); // $ExpectType boolean
numeric.all(23); // $ExpectType boolean
numeric.allV(vector); // $ExpectType boolean
numeric.sum(threeDimensionalMatrix); // $ExpectType number
numeric.sumV(vector); // $ExceptType number
numeric.prod(threeDimensionalMatrix); // $ExpectType number
numeric.prodV(vector); // $ExceptType number
numeric.norm2Squared(threeDimensionalMatrix); // $ExpectType number
numeric.norm2SquaredV(vector); // $ExceptType number
numeric.norminf(threeDimensionalMatrix); // $ExpectType number
numeric.norminfV(vector); // $ExceptType number
numeric.norm1(threeDimensionalMatrix); // $ExpectType number
numeric.norm1V(vector); // $ExceptType number
numeric.sup(threeDimensionalMatrix); // $ExpectType number
numeric.supV(vector); // $ExceptType number
numeric.inf(threeDimensionalMatrix); // $ExpectType number
numeric.infV(vector); // $ExceptType number
numeric.trunc(vector, 3); // $ExpectType number[] || Vector
numeric.truncVV(vector, vector); // $ExpectType number[] || Vector
numeric.truncVS(vector, 4); // $ExpectType number[] || Vector
numeric.truncSV(3, vector); // $ExpectType number[] || Vector
numeric.inv(matrix); // $ExpectType number[][] || Matrix
numeric.det(matrix); // $ExpectType number
numeric.transpose(matrix); // $ExpectType number[][] || Matrix
numeric.negtranspose(matrix); // $ExpectType number[][] || Matrix
numeric.random(vector); // $ExpectType NonScalar
numeric.norm2(threeDimensionalMatrix); // $ExpectType number
numeric.linspace(1, 3, 5); // $ExpectType number[] || Vector
numeric.getBlock(threeDimensionalMatrix, vector, vector); // $ExpectType number[][][]
const block: number[][][] = numeric.setBlock(
threeDimensionalMatrix,
vector,
vector,
threeDimensionalMatrix
);
numeric.blockMatrix(matrix); // $ExpectType number[][] || Matrix
numeric.tensor(3, 5); // $ExpectType number
numeric.tensor(vector, vector); // $ExpectType number[][] || Matrix
const tensor = numeric.t(vector, vector);
tensor
.add(tensor)
.sub(tensor)
.mul(tensor)
.reciprocal()
.div(tensor)
.dot(tensor)
.transpose()
.transjugate()
.exp()
.conj()
.neg()
.sin()
.cos()
.abs()
.log()
.norm2()
.inv()
.get(vector)
.set(vector, tensor)
.getRow(2)
.setRow(2, tensor)
.getRows(10, 10)
.setRows(10, 10, tensor)
.getBlock(vector, vector)
.setBlock(vector, vector, tensor)
.rep(vector, tensor)
.diag(tensor)
.identity(3)
.getDiag()
.fft()
.ifft()
.eig();
numeric.house(vector); // $ExpectType number[] || Vector
numeric.toUpperHessenberg(matrix); // $ExpectType { H: number[][]; Q: number[][]; } || { H: Matrix; Q: Matrix; }
numeric.QRFrancis(matrix, 25); // $ExpectType { Q: number[][]; B: number[][]; } || { Q: Matrix; B: Matrix; }
numeric.eig(matrix); // $ExpectType { lambda: Tensor; E: Tensor; }
numeric.ccsSparse(matrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsFull(sparseMatrix); // $ExpectType number[][] || Matrix
numeric.ccsTSolve(sparseMatrix, vector, vector, vector, vector); // $ExpectType number[] || Vector
numeric.ccsDot(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
const lup = numeric.ccsLUP(sparseMatrix, 4);
numeric.ccsDim(sparseMatrix); // $ExpectType number[] || Vector
numeric.ccsGetBlock(sparseMatrix, vector, 3); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsLUPSolve(lup, sparseMatrix); // $ExpectType number[] || Vector
numeric.ccsScatter(sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsGather(sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsadd(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsadd(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsaddMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccssub(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccssub(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccssubMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsmul(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsmul(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsmulMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsdiv(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsdiv(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsdivMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsmod(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsmod(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsmodMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsand(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsand(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsandMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsor(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsor(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsorMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccseq(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccseq(2, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccseqMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsneq(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsneq(2, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsneqMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccslt(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccslt(2, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsltMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsgt(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsgt(2, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsgtMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsleq(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsleq(2, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsleqMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsgeq(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsgeq(2, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsgeqMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] || CCSComparisonResult
numeric.ccsband(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsband(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsbandMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsbor(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsbor(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsborMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsbxor(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsbxor(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsbxorMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccslshift(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccslshift(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccslshiftMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsrshift(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsrshift(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsrshiftMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsrrshift(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsrrshift(2, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
numeric.ccsrrshiftMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] || SparseMatrix
const lu = numeric.cLU(matrix);
numeric.cLUSolve(lu, vector); // $ExpectType number[] || Vector
numeric.cgrid(2, "L"); // $ExpectType number[][] || Matrix
numeric.cdelsq(matrix); // $ExpectType number[][] || Matrix
numeric.cdotmv(matrix, vector); // $ExpectType number[] || Vector
const spline = numeric.spline(vector, matrix, "periodic", 3);
spline.diff().roots(); // $ExpectType number[] || Vector
spline.at(vector); // $ExpectType number | number[] || number | Vector
numeric.uncmin((x: number[]) => 23, vector, 2, null, 3, () => undefined, {
Hinv: matrix
});
numeric.gradient((x: number[]) => 44, vector); // $ExpectType number[] || Vector
const dopri = numeric.dopri(
1,
1,
1,
(x = 23, y = 44) => 44,
2,
3,
(x = 23, y = 44) => 44
);
dopri.at(vector); // $ExpectType number[] | number[][] || Vector | Matrix
numeric.echelonize(matrix); // $ExpectType { I: number[][]; A: number[][]; P: number[]; } || { I: Matrix; A: Matrix; P: Vector; }
const temp1: { solution: number | number[]; message: string; iterations: number; } =
numeric.solveLP(vector, matrix, vector, matrix, matrix, 3, 4);
const temp2: { solution: number[]; value: number[]; unconstrained_solution: number[]; iterations: number[]; iact: number[]; message: string; } =
numeric.solveQP(matrix, vector, matrix, vector, 3, 44);
numeric.svd(matrix); // $ExpectType { U: number[][]; S: number[]; V: number[][]; } || { U: Matrix; S: Vector; V: Matrix; } | the_stack |
import { Blake2b } from "@iota/crypto.js";
import { deserializeMessage, INDEXATION_PAYLOAD_TYPE, MILESTONE_PAYLOAD_TYPE, SIG_LOCKED_SINGLE_OUTPUT_TYPE, TRANSACTION_PAYLOAD_TYPE } from "@iota/iota.js";
import { asTransactionObject } from "@iota/transaction-converter";
import { Converter, ReadStream } from "@iota/util.js";
import { io, Socket } from "socket.io-client";
import { ServiceFactory } from "../factories/serviceFactory";
import { TrytesHelper } from "../helpers/trytesHelper";
import { IFeedItemMetadata } from "../models/api/IFeedItemMetadata";
import { IFeedSubscribeRequest } from "../models/api/IFeedSubscribeRequest";
import { IFeedSubscribeResponse } from "../models/api/IFeedSubscribeResponse";
import { IFeedSubscriptionMessage } from "../models/api/IFeedSubscriptionMessage";
import { IFeedUnsubscribeRequest } from "../models/api/IFeedUnsubscribeRequest";
import { INetwork } from "../models/db/INetwork";
import { IFeedItem } from "../models/IFeedItem";
import { NetworkService } from "./networkService";
/**
* Class to handle api communications.
*/
export class FeedClient {
/**
* Minimun number of each item to keep.
*/
private static readonly MIN_ITEMS_PER_TYPE: number = 50;
/**
* The endpoint for performing communications.
*/
private readonly _endpoint: string;
/**
* Network configuration.
*/
private readonly _networkId: string;
/**
* Network configuration.
*/
private readonly _networkConfig?: INetwork;
/**
* The web socket to communicate on.
*/
private readonly _socket: Socket;
/**
* The latest items.
*/
private _items: IFeedItem[];
/**
* Existing ids.
*/
private _existingIds: string[];
/**
* The subscription id.
*/
private _subscriptionId?: string;
/**
* The subscribers.
*/
private readonly _subscribers: {
[id: string]: (newItems: IFeedItem[], metaData: { [id: string]: IFeedItemMetadata }) => void;
};
/**
* Create a new instance of TransactionsClient.
* @param endpoint The endpoint for the api.
* @param networkId The network configurations.
*/
constructor(endpoint: string, networkId: string) {
this._endpoint = endpoint;
this._networkId = networkId;
const networkService = ServiceFactory.get<NetworkService>("network");
this._networkConfig = networkService.get(this._networkId);
// Use websocket by default
// eslint-disable-next-line new-cap
this._socket = io(this._endpoint, { upgrade: true, transports: ["websocket"] });
// If reconnect fails then also try polling mode.
this._socket.on("reconnect_attempt", () => {
this._socket.io.opts.transports = ["polling", "websocket"];
});
this._items = [];
this._existingIds = [];
this._subscribers = {};
}
/**
* Perform a request to subscribe to transactions events.
* @param callback Callback called with transactions data.
* @returns The subscription id.
*/
public subscribe(callback: (newItems: IFeedItem[], metaData: { [id: string]: IFeedItemMetadata }) => void): string {
const subscriptionId = TrytesHelper.generateHash(27);
this._subscribers[subscriptionId] = callback;
try {
if (!this._subscriptionId) {
const subscribeRequest: IFeedSubscribeRequest = {
network: this._networkId
};
this._socket.emit("subscribe", subscribeRequest);
this._socket.on("subscribe", (subscribeResponse: IFeedSubscribeResponse) => {
if (!subscribeResponse.error) {
this._subscriptionId = subscribeResponse.subscriptionId;
}
});
this._socket.on("transactions", async (subscriptionMessage: IFeedSubscriptionMessage) => {
if (subscriptionMessage.subscriptionId === this._subscriptionId) {
if (subscriptionMessage.itemsMetadata) {
for (const metadataId in subscriptionMessage.itemsMetadata) {
const existing = this._items.find(c => c.id === metadataId);
if (existing) {
existing.metaData = {
...existing.metaData,
...subscriptionMessage.itemsMetadata[metadataId]
};
}
}
}
const filteredNewItems = subscriptionMessage.items
.map(item => this.convertItem(item))
.filter(nh => !this._existingIds.includes(nh.id));
if (filteredNewItems.length > 0) {
this._items = filteredNewItems.slice().concat(this._items);
let removeItems: IFeedItem[] = [];
if (this._networkConfig?.protocolVersion === "og") {
const zero = this._items.filter(t => t.payloadType === "Transaction" && t.value === 0);
const zeroToRemoveCount = zero.length - FeedClient.MIN_ITEMS_PER_TYPE;
if (zeroToRemoveCount > 0) {
removeItems = removeItems.concat(zero.slice(-zeroToRemoveCount));
}
const nonZero = this._items.filter(t => t.payloadType === "Transaction" &&
t.value !== 0 && t.value !== undefined);
const nonZeroToRemoveCount = nonZero.length - FeedClient.MIN_ITEMS_PER_TYPE;
if (nonZeroToRemoveCount > 0) {
removeItems = removeItems.concat(nonZero.slice(-nonZeroToRemoveCount));
}
} else {
const transactionPayload = this._items.filter(t => t.payloadType === "Transaction");
const transactionPayloadToRemoveCount =
transactionPayload.length - FeedClient.MIN_ITEMS_PER_TYPE;
if (transactionPayloadToRemoveCount > 0) {
removeItems =
removeItems.concat(transactionPayload.slice(-transactionPayloadToRemoveCount));
}
const indexPayload = this._items.filter(t => t.payloadType === "Index");
const indexPayloadToRemoveCount = indexPayload.length - FeedClient.MIN_ITEMS_PER_TYPE;
if (indexPayloadToRemoveCount > 0) {
removeItems = removeItems.concat(indexPayload.slice(-indexPayloadToRemoveCount));
}
const msPayload = this._items.filter(t => t.payloadType === "MS");
const msPayloadToRemoveCount = msPayload.length - FeedClient.MIN_ITEMS_PER_TYPE;
if (msPayloadToRemoveCount > 0) {
removeItems = removeItems.concat(msPayload.slice(-msPayloadToRemoveCount));
}
const nonePayload = this._items.filter(t => t.payloadType === "None");
const nonePayloadToRemoveCount = nonePayload.length - FeedClient.MIN_ITEMS_PER_TYPE;
if (nonePayloadToRemoveCount > 0) {
removeItems = removeItems.concat(nonePayload.slice(-nonePayloadToRemoveCount));
}
}
this._items = this._items.filter(t => !removeItems.includes(t));
this._existingIds = this._items.map(t => t.id);
}
for (const sub in this._subscribers) {
this._subscribers[sub](filteredNewItems, subscriptionMessage.itemsMetadata);
}
}
});
}
} catch { }
return subscriptionId;
}
/**
* Perform a request to unsubscribe to transactions events.
* @param subscriptionId The subscription id.
*/
public unsubscribe(subscriptionId: string): void {
try {
delete this._subscribers[subscriptionId];
if (this._subscriptionId && Object.keys(this._subscribers).length === 0) {
const unsubscribeRequest: IFeedUnsubscribeRequest = {
network: this._networkId,
subscriptionId: this._subscriptionId
};
this._socket.emit("unsubscribe", unsubscribeRequest);
this._socket.on("unsubscribe", () => { });
}
} catch {
} finally {
this._subscriptionId = undefined;
}
}
/**
* Get the items.
* @returns The item details.
*/
public getItems(): IFeedItem[] {
return this._items.slice();
}
/**
* Convert the feed item into real data.
* @param item The item source.
* @returns The feed item.
*/
private convertItem(item: string): IFeedItem {
if (this._networkConfig?.protocolVersion === "chrysalis") {
const bytes = Converter.hexToBytes(item);
const messageId = Converter.bytesToHex(Blake2b.sum256(bytes));
let value;
let payloadType: "Transaction" | "Index" | "MS" | "None" = "None";
const properties: { [key: string]: unknown } = {};
let message;
try {
message = deserializeMessage(new ReadStream(bytes));
if (message.payload?.type === TRANSACTION_PAYLOAD_TYPE) {
payloadType = "Transaction";
value = 0;
for (const output of message.payload.essence.outputs) {
if (output.type === SIG_LOCKED_SINGLE_OUTPUT_TYPE) {
value += output.amount;
}
}
if (message.payload.essence.payload) {
properties.Index = message.payload.essence.payload.index;
}
} else if (message.payload?.type === MILESTONE_PAYLOAD_TYPE) {
payloadType = "MS";
properties.MS = message.payload.index;
} else if (message.payload?.type === INDEXATION_PAYLOAD_TYPE) {
payloadType = "Index";
properties.Index = message.payload.index;
}
} catch (err) {
console.error(err);
}
return {
id: messageId,
value,
parents: message?.parentMessageIds ?? [],
properties,
payloadType
};
}
const tx = asTransactionObject(item);
return {
id: tx.hash,
value: tx.value,
parents: [
tx.trunkTransaction,
tx.branchTransaction
],
properties: {
"Tag": tx.tag,
"Address": tx.address,
"Bundle": tx.bundle
},
payloadType: "Transaction"
};
}
} | the_stack |
import chalk from 'chalk';
import * as Commander from 'commander';
import * as Path from 'path';
import * as readline from 'readline';
import stripAnsi from 'strip-ansi';
import * as Util from 'util';
import { URI } from 'vscode-uri';
import * as app from './app';
import * as Link from './link';
import { mergeAsyncIterables } from './util/async';
jest.mock('readline');
const mockCreateInterface = jest.mocked(readline.createInterface);
const projectRoot = Path.join(__dirname, '..');
const projectRootUri = URI.file(projectRoot);
function argv(...args: string[]): string[] {
return [...process.argv.slice(0, 2), ...args];
}
function getCommander() {
return new Commander.Command();
}
function pathRoot(...parts: string[]): string {
return Path.join(projectRoot, ...parts);
}
function pathSamples(...parts: string[]): string {
return pathRoot('samples', ...parts);
}
// [message, args, resolve, error, log, info]
type ErrorCheck = undefined | jest.Constructable | string | RegExp;
interface TestCase {
msg: string;
testArgs: string[];
errorCheck: ErrorCheck;
eError: boolean;
eLog: boolean;
eInfo: boolean;
}
class RecordStdStream {
private static columnWidth = 80;
private write = process.stdout.write.bind(process.stdout);
private streamWrite: StdoutWrite | undefined;
private columns: number = process.stdout.columns;
readonly text: string[] = [];
startCapture() {
this.stopCapture();
this.streamWrite = process[this.stream].write;
this.columns = process[this.stream].columns;
process[this.stream].write = this.capture.bind(this);
process[this.stream].columns = RecordStdStream.columnWidth;
}
stopCapture() {
if (this.streamWrite) {
process[this.stream].write = this.streamWrite;
process[this.stream].columns = this.columns;
}
this.streamWrite = undefined;
}
private capture(buffer: Uint8Array | string, cb?: Callback): boolean;
private capture(str: Uint8Array | string, encoding?: BufferEncoding, cb?: Callback): boolean;
private capture(str: Uint8Array | string, encodingOrCb?: BufferEncoding | Callback, cb?: Callback): boolean {
const encoding = typeof encodingOrCb === 'string' ? encodingOrCb : undefined;
cb = cb || (typeof encodingOrCb === 'function' ? encodingOrCb : undefined);
if (typeof str === 'string') {
const t = this.text.pop() || '';
const lines = str.split(/\r?\n/g);
lines[0] = t + lines[0];
this.text.push(...lines);
}
return encoding ? this.write(str, encoding, cb) : this.write(str, cb);
}
clear() {
this.text.length = 0;
}
constructor(readonly stream: 'stdout' | 'stderr' = 'stdout') {}
}
const colorLevel = chalk.level;
describe('Validate cli', () => {
const logger = makeLogger();
const error = jest.spyOn(console, 'error').mockName('console.error').mockImplementation(logger.error);
const log = jest.spyOn(console, 'log').mockName('console.log').mockImplementation(logger.log);
const info = jest.spyOn(console, 'info').mockName('console.info').mockImplementation(logger.info);
const listGlobalImports = jest.spyOn(Link, 'listGlobalImports').mockName('istGlobalImports');
const addPathsToGlobalImports = jest.spyOn(Link, 'addPathsToGlobalImports').mockName('addPathsToGlobalImports');
const removePathsFromGlobalImports = jest
.spyOn(Link, 'removePathsFromGlobalImports')
.mockName('removePathsFromGlobalImports');
const captureStdout = new RecordStdStream();
const captureStderr = new RecordStdStream('stderr');
beforeEach(() => {
log.mockClear();
error.mockClear();
mockCreateInterface.mockClear();
logger.clear();
captureStdout.startCapture();
captureStderr.startCapture();
chalk.level = 3;
});
afterEach(() => {
info.mockClear();
log.mockClear();
error.mockClear();
listGlobalImports.mockClear();
addPathsToGlobalImports.mockClear();
removePathsFromGlobalImports.mockClear();
captureStdout.stopCapture();
captureStdout.clear();
captureStderr.stopCapture();
captureStderr.clear();
chalk.level = colorLevel;
});
const failFastConfig = pathSamples('fail-fast/fail-fast-cspell.json');
const failFastRoot = pathSamples('fail-fast');
test.each`
msg | testArgs | errorCheck | eError | eLog | eInfo
${'with errors and excludes'} | ${['-r', 'samples', '*', '-e', 'Dutch.txt', '-c', 'samples/.cspell.json']} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'no-args'} | ${[]} | ${'outputHelp'} | ${false} | ${false} | ${false}
${'--help'} | ${['--help']} | ${'outputHelp'} | ${false} | ${false} | ${false}
${'current_file'} | ${[__filename]} | ${undefined} | ${true} | ${false} | ${false}
${'with spelling errors Dutch.txt'} | ${[pathSamples('Dutch.txt')]} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'with spelling errors Dutch.txt words only'} | ${[pathSamples('Dutch.txt'), '--wordsOnly']} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'with spelling errors Dutch.txt --legacy'} | ${[pathSamples('Dutch.txt'), '--legacy']} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'with spelling errors --silent Dutch.txt'} | ${['--silent', pathSamples('Dutch.txt')]} | ${app.CheckFailed} | ${false} | ${false} | ${false}
${'current_file languageId'} | ${[__filename, '--languageId=typescript']} | ${undefined} | ${true} | ${false} | ${false}
${'check help'} | ${['check', '--help']} | ${'outputHelp'} | ${false} | ${false} | ${false}
${'check LICENSE'} | ${['check', pathRoot('LICENSE')]} | ${undefined} | ${false} | ${true} | ${false}
${'check missing'} | ${['check', pathRoot('missing-file.txt')]} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'check with spelling errors'} | ${['check', pathSamples('Dutch.txt')]} | ${app.CheckFailed} | ${false} | ${true} | ${false}
${'LICENSE'} | ${[pathRoot('LICENSE')]} | ${undefined} | ${true} | ${false} | ${false}
${'samples/Dutch.txt'} | ${[pathSamples('Dutch.txt')]} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'with forbidden words'} | ${[pathSamples('src/sample-with-forbidden-words.md')]} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'current_file --verbose'} | ${['--verbose', __filename]} | ${undefined} | ${true} | ${false} | ${true}
${'bad config'} | ${['-c', __filename, __filename]} | ${app.CheckFailed} | ${true} | ${false} | ${false}
${'not found error by default'} | ${['*.not']} | ${app.CheckFailed} | ${true} | ${false} | ${false}
${'must find with error'} | ${['*.not', '--must-find-files']} | ${app.CheckFailed} | ${true} | ${false} | ${false}
${'must find force no error'} | ${['*.not', '--no-must-find-files']} | ${undefined} | ${true} | ${false} | ${false}
${'cspell-bad.json'} | ${['-c', pathSamples('cspell-bad.json'), __filename]} | ${undefined} | ${true} | ${false} | ${false}
${'cspell-import-missing.json'} | ${['-c', pathSamples('linked/cspell-import-missing.json'), __filename]} | ${app.CheckFailed} | ${true} | ${false} | ${false}
${'--fail-fast no option'} | ${['-r', failFastRoot, '*.txt']} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'--fail-fast with option'} | ${['-r', failFastRoot, '--fail-fast', '*.txt']} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'--fail-fast with config'} | ${['-r', failFastRoot, '-c', failFastConfig, '*.txt']} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'--no-fail-fast with config'} | ${['-r', failFastRoot, '--no-fail-fast', '-c', failFastConfig, '*.txt']} | ${app.CheckFailed} | ${true} | ${true} | ${false}
`('app $msg Expect Error: $errorCheck', async ({ testArgs, errorCheck, eError, eLog, eInfo }: TestCase) => {
chalk.level = 1;
const commander = getCommander();
const args = argv(...testArgs);
const result = app.run(commander, args);
if (!errorCheck) {
// eslint-disable-next-line jest/no-conditional-expect
await expect(result).resolves.toBeUndefined();
} else {
// eslint-disable-next-line jest/no-conditional-expect
await expect(result).rejects.toThrowError(errorCheck);
}
// eslint-disable-next-line jest/no-conditional-expect
eError ? expect(error).toHaveBeenCalled() : expect(error).not.toHaveBeenCalled();
// eslint-disable-next-line jest/no-conditional-expect
eLog ? expect(log).toHaveBeenCalled() : expect(log).not.toHaveBeenCalled();
// eslint-disable-next-line jest/no-conditional-expect
eInfo ? expect(info).toHaveBeenCalled() : expect(info).not.toHaveBeenCalled();
expect(captureStdout.text).toMatchSnapshot();
expect(logger.normalizedHistory()).toMatchSnapshot();
expect(normalizeOutput(captureStderr.text)).toMatchSnapshot();
});
test.each`
msg | testArgs | errorCheck | eError | eLog | eInfo
${'trace hello'} | ${['trace', 'hello']} | ${undefined} | ${false} | ${true} | ${false}
${'trace café'} | ${['trace', 'café'.normalize('NFD')]} | ${undefined} | ${false} | ${true} | ${false}
${'trace hello'} | ${['trace', '--locale=en-gb', 'hello']} | ${undefined} | ${false} | ${true} | ${false}
${'trace help'} | ${['trace', '-h']} | ${'outputHelp'} | ${false} | ${false} | ${false}
${'trace not-in-any-dictionary'} | ${['trace', 'not-in-any-dictionary']} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'trace missing dictionary'} | ${['trace', 'hello', '-c', 'samples/cspell-missing-dict.json']} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'with spelling errors --debug Dutch.txt'} | ${['--relative', '--debug', pathSamples('Dutch.txt')]} | ${app.CheckFailed} | ${true} | ${true} | ${true}
`('app $msg Expect Error: $errorCheck', async ({ testArgs, errorCheck, eError, eLog, eInfo }: TestCase) => {
chalk.level = 0;
const commander = getCommander();
const args = argv(...testArgs);
const result = app.run(commander, args);
if (!errorCheck) {
// eslint-disable-next-line jest/no-conditional-expect
await expect(result).resolves.toBeUndefined();
} else {
// eslint-disable-next-line jest/no-conditional-expect
await expect(result).rejects.toThrowError(errorCheck);
}
// eslint-disable-next-line jest/no-conditional-expect
eError ? expect(error).toHaveBeenCalled() : expect(error).not.toHaveBeenCalled();
// eslint-disable-next-line jest/no-conditional-expect
eLog ? expect(log).toHaveBeenCalled() : expect(log).not.toHaveBeenCalled();
// eslint-disable-next-line jest/no-conditional-expect
eInfo ? expect(info).toHaveBeenCalled() : expect(info).not.toHaveBeenCalled();
expect(captureStdout.text).toMatchSnapshot();
expect(normalizeLogCalls(log.mock.calls)).toMatchSnapshot();
});
test.each`
msg | testArgs
${'trace hello'} | ${['trace', 'hello']}
${'trace café'} | ${['trace', 'café'.normalize('NFD')]}
${'trace hello'} | ${['trace', '--locale=en-gb', 'hello']}
${'suggest'} | ${['suggest', 'café'.normalize('NFD'), '--num-suggestions=1', '--no-include-ties']}
`('app success $msg run with $testArgs', async ({ testArgs }: TestCase) => {
chalk.level = 0;
const commander = getCommander();
const args = argv(...testArgs);
await app.run(commander, args);
expect(captureStdout.text).toMatchSnapshot();
expect(normalizeLogCalls(log.mock.calls)).toMatchSnapshot();
});
test.each`
msg | testArgs | errorCheck | eError | eLog | eInfo
${'link'} | ${['link']} | ${undefined} | ${false} | ${true} | ${false}
${'link ls'} | ${['link', 'ls']} | ${undefined} | ${false} | ${true} | ${false}
${'link list'} | ${['link', 'list']} | ${undefined} | ${false} | ${true} | ${false}
${'link add'} | ${['link', 'add', 'cspell-dict-cpp/cspell-ext.json']} | ${undefined} | ${false} | ${true} | ${false}
${'link remove'} | ${['link', 'remove', 'cspell-dict-cpp/cspell-ext.json']} | ${undefined} | ${false} | ${true} | ${false}
`('app $msg', async ({ testArgs, errorCheck, eError, eLog, eInfo }: TestCase) => {
listGlobalImports.mockImplementation(_listGlobalImports());
addPathsToGlobalImports.mockImplementation(_addPathsToGlobalImports());
removePathsFromGlobalImports.mockImplementation(_removePathsFromGlobalImports());
const commander = getCommander();
const args = argv(...testArgs);
const result = app.run(commander, args);
if (!errorCheck) {
// eslint-disable-next-line jest/no-conditional-expect
await expect(result).resolves.toBeUndefined();
} else {
// eslint-disable-next-line jest/no-conditional-expect
await expect(result).rejects.toThrowError(errorCheck);
}
// eslint-disable-next-line jest/no-conditional-expect
eError ? expect(error).toHaveBeenCalled() : expect(error).not.toHaveBeenCalled();
// eslint-disable-next-line jest/no-conditional-expect
eLog ? expect(log).toHaveBeenCalled() : expect(log).not.toHaveBeenCalled();
// eslint-disable-next-line jest/no-conditional-expect
eInfo ? expect(info).toHaveBeenCalled() : expect(info).not.toHaveBeenCalled();
expect(normalizeOutput(captureStdout.text)).toMatchSnapshot();
});
test.each`
testArgs | stdin | errorCheck
${['sug']} | ${undefined} | ${'outputHelp'}
${['sug', 'mexico', '-d=en-us']} | ${undefined} | ${undefined}
${['sug', 'mexico', '-d=en_us']} | ${undefined} | ${undefined}
${['sug', 'mexico', '-d=en-gb']} | ${undefined} | ${undefined}
${['sug', 'mexico', '-d=en_us', '-v']} | ${undefined} | ${undefined}
${['sug', '--stdin', '-d=en_us', '-v']} | ${['mexico']} | ${undefined}
${['sug', 'mexico', '-d=en_us', '-v', '--num-suggestions=0']} | ${undefined} | ${undefined}
${['sug', 'dutch', '-d=en_us', '-d=en-gb', '-v', '--num-suggestions=2']} | ${undefined} | ${undefined}
${['sug', 'dutch', '--dictionaries=en_us', '--dictionary=en-gb', '-v', '--num-suggestions=2']} | ${undefined} | ${undefined}
${['sug', 'dutch', '--dictionaries=en_us', '-v', '--num-suggestions=2']} | ${undefined} | ${undefined}
${['sug', 'dutch', '--dictionaries=en_us', '-v', '--num-suggestions=2']} | ${undefined} | ${undefined}
`('app suggest $testArgs', async ({ testArgs, errorCheck, stdin }) => {
chalk.level = 0;
const values = stdin || [];
mockCreateInterface.mockReturnValue({
[Symbol.asyncIterator]: () => mergeAsyncIterables(values),
} as ReturnType<typeof readline.createInterface>);
listGlobalImports.mockImplementation(_listGlobalImports());
addPathsToGlobalImports.mockImplementation(_addPathsToGlobalImports());
removePathsFromGlobalImports.mockImplementation(_removePathsFromGlobalImports());
const commander = getCommander();
const args = argv(...testArgs);
const result = app.run(commander, args);
if (!errorCheck) {
// eslint-disable-next-line jest/no-conditional-expect
await expect(result).resolves.toBeUndefined();
} else {
// eslint-disable-next-line jest/no-conditional-expect
await expect(result).rejects.toThrowError(errorCheck);
}
expect(captureStdout.text).toMatchSnapshot();
expect(log.mock.calls.join('\n')).toMatchSnapshot();
expect(error.mock.calls.join('\n')).toMatchSnapshot();
expect(mockCreateInterface).toHaveBeenCalledTimes(stdin ? 1 : 0);
});
});
function _listGlobalImports(): typeof Link['listGlobalImports'] {
return () => {
return {
list: [],
globalSettings: {},
};
};
}
function _addPathsToGlobalImports(): typeof Link['addPathsToGlobalImports'] {
return (_paths: string[]) => {
return {
success: true,
resolvedSettings: [],
error: undefined,
};
};
}
function _removePathsFromGlobalImports(): typeof Link['removePathsFromGlobalImports'] {
return (paths: string[]) => {
return {
success: true,
error: undefined,
removed: paths,
};
};
}
type StdoutWrite = typeof process.stdout.write;
type Callback = (err?: Error) => void;
function normalizeLogCalls(calls: string[][]): string {
return normalizeOutput(calls.map((call) => Util.format(...call)));
}
function normalizeOutput(lines: string[]): string {
return lines.join('\n').replace(/\\/g, '/');
}
function makeLogger() {
const history: string[] = [];
function record(prefix: string, ...rest: unknown[]) {
const s = Util.format(...rest);
s.split('\n').forEach((line) => history.push(prefix + '\t' + line));
}
function normalizedHistory() {
let t = history.join('\n');
t = stripAnsi(t);
t = t.replace(/\r/gm, '');
t = t.replace(RegExp(escapeRegExp(projectRootUri.toString()), 'gi'), '.');
t = t.replace(RegExp(escapeRegExp(projectRoot), 'gi'), '.');
t = t.replace(/\\/g, '/');
t = t.replace(/(?<=^info\s+Date:).*$/gm, ' Sat, 03 Apr 2021 11:25:33 GMT');
t = t.replace(/\b[\d.]+ms\b/g, '0.00ms');
t = t.replace(/\b[\d.]+S\b/g, '0.00S');
return t;
}
return {
clear: () => {
history.length = 0;
return;
},
log: (...params: unknown[]) => record('log', ...params),
error: (...params: unknown[]) => record('error', ...params),
info: (...params: unknown[]) => record('info', ...params),
history,
normalizedHistory,
};
}
function escapeRegExp(s: string): string {
return s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
} | the_stack |
import * as certificatemanager from '@aws-cdk/aws-certificatemanager';
import * as lambda from '@aws-cdk/aws-lambda';
import * as s3 from '@aws-cdk/aws-s3';
import * as cdk from '@aws-cdk/core';
import { Construct } from 'constructs';
import { CfnDistribution } from './cloudfront.generated';
import { HttpVersion, IDistribution, LambdaEdgeEventType, OriginProtocolPolicy, PriceClass, ViewerProtocolPolicy, SSLMethod, SecurityPolicyProtocol } from './distribution';
import { GeoRestriction } from './geo-restriction';
import { IOriginAccessIdentity } from './origin_access_identity';
/**
* (experimental) HTTP status code to failover to second origin.
*
* @experimental
*/
export declare enum FailoverStatusCode {
/**
* (experimental) Forbidden (403).
*
* @experimental
*/
FORBIDDEN = 403,
/**
* (experimental) Not found (404).
*
* @experimental
*/
NOT_FOUND = 404,
/**
* (experimental) Internal Server Error (500).
*
* @experimental
*/
INTERNAL_SERVER_ERROR = 500,
/**
* (experimental) Bad Gateway (502).
*
* @experimental
*/
BAD_GATEWAY = 502,
/**
* (experimental) Service Unavailable (503).
*
* @experimental
*/
SERVICE_UNAVAILABLE = 503,
/**
* (experimental) Gateway Timeout (504).
*
* @experimental
*/
GATEWAY_TIMEOUT = 504
}
/**
* (experimental) Configuration for custom domain names.
*
* CloudFront can use a custom domain that you provide instead of a
* "cloudfront.net" domain. To use this feature you must provide the list of
* additional domains, and the ACM Certificate that CloudFront should use for
* these additional domains.
*
* @experimental
*/
export interface AliasConfiguration {
/**
* (experimental) ARN of an AWS Certificate Manager (ACM) certificate.
*
* @experimental
*/
readonly acmCertRef: string;
/**
* (experimental) Domain names on the certificate.
*
* Both main domain name and Subject Alternative Names.
*
* @experimental
*/
readonly names: string[];
/**
* (experimental) How CloudFront should serve HTTPS requests.
*
* See the notes on SSLMethod if you wish to use other SSL termination types.
*
* @default SSLMethod.SNI
* @see https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ViewerCertificate.html
* @experimental
*/
readonly sslMethod?: SSLMethod;
/**
* (experimental) The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections.
*
* CloudFront serves your objects only to browsers or devices that support at
* least the SSL version that you specify.
*
* @default - SSLv3 if sslMethod VIP, TLSv1 if sslMethod SNI
* @experimental
*/
readonly securityPolicy?: SecurityPolicyProtocol;
}
/**
* (experimental) Logging configuration for incoming requests.
*
* @experimental
*/
export interface LoggingConfiguration {
/**
* (experimental) Bucket to log requests to.
*
* @default - A logging bucket is automatically created.
* @experimental
*/
readonly bucket?: s3.IBucket;
/**
* (experimental) Whether to include the cookies in the logs.
*
* @default false
* @experimental
*/
readonly includeCookies?: boolean;
/**
* (experimental) Where in the bucket to store logs.
*
* @default - No prefix.
* @experimental
*/
readonly prefix?: string;
}
/**
* (experimental) A source configuration is a wrapper for CloudFront origins and behaviors.
*
* An origin is what CloudFront will "be in front of" - that is, CloudFront will pull it's assets from an origin.
*
* If you're using s3 as a source - pass the `s3Origin` property, otherwise, pass the `customOriginSource` property.
*
* One or the other must be passed, and it is invalid to pass both in the same SourceConfiguration.
*
* @experimental
*/
export interface SourceConfiguration {
/**
* (experimental) The number of times that CloudFront attempts to connect to the origin.
*
* You can specify 1, 2, or 3 as the number of attempts.
*
* @default 3
* @experimental
*/
readonly connectionAttempts?: number;
/**
* (experimental) The number of seconds that CloudFront waits when trying to establish a connection to the origin.
*
* You can specify a number of seconds between 1 and 10 (inclusive).
*
* @default cdk.Duration.seconds(10)
* @experimental
*/
readonly connectionTimeout?: cdk.Duration;
/**
* (experimental) An s3 origin source - if you're using s3 for your assets.
*
* @experimental
*/
readonly s3OriginSource?: S3OriginConfig;
/**
* (experimental) A custom origin source - for all non-s3 sources.
*
* @experimental
*/
readonly customOriginSource?: CustomOriginConfig;
/**
* (experimental) An s3 origin source for failover in case the s3OriginSource returns invalid status code.
*
* @default - no failover configuration
* @experimental
*/
readonly failoverS3OriginSource?: S3OriginConfig;
/**
* (experimental) A custom origin source for failover in case the s3OriginSource returns invalid status code.
*
* @default - no failover configuration
* @experimental
*/
readonly failoverCustomOriginSource?: CustomOriginConfig;
/**
* (experimental) HTTP status code to failover to second origin.
*
* @default [500, 502, 503, 504]
* @experimental
*/
readonly failoverCriteriaStatusCodes?: FailoverStatusCode[];
/**
* (experimental) The behaviors associated with this source.
*
* At least one (default) behavior must be included.
*
* @experimental
*/
readonly behaviors: Behavior[];
/**
* (deprecated) The relative path to the origin root to use for sources.
*
* @default /
* @deprecated Use originPath on s3OriginSource or customOriginSource
*/
readonly originPath?: string;
/**
* (deprecated) Any additional headers to pass to the origin.
*
* @default - No additional headers are passed.
* @deprecated Use originHeaders on s3OriginSource or customOriginSource
*/
readonly originHeaders?: {
[key: string]: string;
};
}
/**
* (experimental) A custom origin configuration.
*
* @experimental
*/
export interface CustomOriginConfig {
/**
* (experimental) The domain name of the custom origin.
*
* Should not include the path - that should be in the parent SourceConfiguration
*
* @experimental
*/
readonly domainName: string;
/**
* (experimental) The origin HTTP port.
*
* @default 80
* @experimental
*/
readonly httpPort?: number;
/**
* (experimental) The origin HTTPS port.
*
* @default 443
* @experimental
*/
readonly httpsPort?: number;
/**
* (experimental) The keep alive timeout when making calls in seconds.
*
* @default Duration.seconds(5)
* @experimental
*/
readonly originKeepaliveTimeout?: cdk.Duration;
/**
* (experimental) The protocol (http or https) policy to use when interacting with the origin.
*
* @default OriginProtocolPolicy.HttpsOnly
* @experimental
*/
readonly originProtocolPolicy?: OriginProtocolPolicy;
/**
* (experimental) The read timeout when calling the origin in seconds.
*
* @default Duration.seconds(30)
* @experimental
*/
readonly originReadTimeout?: cdk.Duration;
/**
* (experimental) The SSL versions to use when interacting with the origin.
*
* @default OriginSslPolicy.TLS_V1_2
* @experimental
*/
readonly allowedOriginSSLVersions?: OriginSslPolicy[];
/**
* (experimental) The relative path to the origin root to use for sources.
*
* @default /
* @experimental
*/
readonly originPath?: string;
/**
* (experimental) Any additional headers to pass to the origin.
*
* @default - No additional headers are passed.
* @experimental
*/
readonly originHeaders?: {
[key: string]: string;
};
}
/**
* @experimental
*/
export declare enum OriginSslPolicy {
/**
* @experimental
*/
SSL_V3 = "SSLv3",
/**
* @experimental
*/
TLS_V1 = "TLSv1",
/**
* @experimental
*/
TLS_V1_1 = "TLSv1.1",
/**
* @experimental
*/
TLS_V1_2 = "TLSv1.2"
}
/**
* (experimental) S3 origin configuration for CloudFront.
*
* @experimental
*/
export interface S3OriginConfig {
/**
* (experimental) The source bucket to serve content from.
*
* @experimental
*/
readonly s3BucketSource: s3.IBucket;
/**
* (experimental) The optional Origin Access Identity of the origin identity cloudfront will use when calling your s3 bucket.
*
* @default No Origin Access Identity which requires the S3 bucket to be public accessible
* @experimental
*/
readonly originAccessIdentity?: IOriginAccessIdentity;
/**
* (experimental) The relative path to the origin root to use for sources.
*
* @default /
* @experimental
*/
readonly originPath?: string;
/**
* (experimental) Any additional headers to pass to the origin.
*
* @default - No additional headers are passed.
* @experimental
*/
readonly originHeaders?: {
[key: string]: string;
};
}
/**
* (experimental) An enum for the supported methods to a CloudFront distribution.
*
* @experimental
*/
export declare enum CloudFrontAllowedMethods {
/**
* @experimental
*/
GET_HEAD = "GH",
/**
* @experimental
*/
GET_HEAD_OPTIONS = "GHO",
/**
* @experimental
*/
ALL = "ALL"
}
/**
* (experimental) Enums for the methods CloudFront can cache.
*
* @experimental
*/
export declare enum CloudFrontAllowedCachedMethods {
/**
* @experimental
*/
GET_HEAD = "GH",
/**
* @experimental
*/
GET_HEAD_OPTIONS = "GHO"
}
/**
* (experimental) A CloudFront behavior wrapper.
*
* @experimental
*/
export interface Behavior {
/**
* (experimental) If CloudFront should automatically compress some content types.
*
* @default true
* @experimental
*/
readonly compress?: boolean;
/**
* (experimental) If this behavior is the default behavior for the distribution.
*
* You must specify exactly one default distribution per CloudFront distribution.
* The default behavior is allowed to omit the "path" property.
*
* @experimental
*/
readonly isDefaultBehavior?: boolean;
/**
* (experimental) Trusted signers is how CloudFront allows you to serve private content.
*
* The signers are the account IDs that are allowed to sign cookies/presigned URLs for this distribution.
*
* If you pass a non empty value, all requests for this behavior must be signed (no public access will be allowed)
*
* @experimental
*/
readonly trustedSigners?: string[];
/**
* (experimental) The default amount of time CloudFront will cache an object.
*
* This value applies only when your custom origin does not add HTTP headers,
* such as Cache-Control max-age, Cache-Control s-maxage, and Expires to objects.
*
* @default 86400 (1 day)
* @experimental
*/
readonly defaultTtl?: cdk.Duration;
/**
* (experimental) The method this CloudFront distribution responds do.
*
* @default GET_HEAD
* @experimental
*/
readonly allowedMethods?: CloudFrontAllowedMethods;
/**
* (experimental) The path this behavior responds to.
*
* Required for all non-default behaviors. (The default behavior implicitly has "*" as the path pattern. )
*
* @experimental
*/
readonly pathPattern?: string;
/**
* (experimental) Which methods are cached by CloudFront by default.
*
* @default GET_HEAD
* @experimental
*/
readonly cachedMethods?: CloudFrontAllowedCachedMethods;
/**
* (experimental) The values CloudFront will forward to the origin when making a request.
*
* @default none (no cookies - no headers)
* @experimental
*/
readonly forwardedValues?: CfnDistribution.ForwardedValuesProperty;
/**
* (experimental) The minimum amount of time that you want objects to stay in the cache before CloudFront queries your origin.
*
* @experimental
*/
readonly minTtl?: cdk.Duration;
/**
* (experimental) The max amount of time you want objects to stay in the cache before CloudFront queries your origin.
*
* @default Duration.seconds(31536000) (one year)
* @experimental
*/
readonly maxTtl?: cdk.Duration;
/**
* (experimental) Declares associated lambda@edge functions for this distribution behaviour.
*
* @default No lambda function associated
* @experimental
*/
readonly lambdaFunctionAssociations?: LambdaFunctionAssociation[];
}
/**
* @experimental
*/
export interface LambdaFunctionAssociation {
/**
* (experimental) The lambda event type defines at which event the lambda is called during the request lifecycle.
*
* @experimental
*/
readonly eventType: LambdaEdgeEventType;
/**
* (experimental) A version of the lambda to associate.
*
* @experimental
*/
readonly lambdaFunction: lambda.IVersion;
/**
* (experimental) Allows a Lambda function to have read access to the body content.
*
* Only valid for "request" event types (`ORIGIN_REQUEST` or `VIEWER_REQUEST`).
* See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-include-body-access.html
*
* @default false
* @experimental
*/
readonly includeBody?: boolean;
}
/**
* @experimental
*/
export interface ViewerCertificateOptions {
/**
* (experimental) How CloudFront should serve HTTPS requests.
*
* See the notes on SSLMethod if you wish to use other SSL termination types.
*
* @default SSLMethod.SNI
* @see https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ViewerCertificate.html
* @experimental
*/
readonly sslMethod?: SSLMethod;
/**
* (experimental) The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections.
*
* CloudFront serves your objects only to browsers or devices that support at
* least the SSL version that you specify.
*
* @default - SSLv3 if sslMethod VIP, TLSv1 if sslMethod SNI
* @experimental
*/
readonly securityPolicy?: SecurityPolicyProtocol;
/**
* (experimental) Domain names on the certificate (both main domain name and Subject Alternative names).
*
* @experimental
*/
readonly aliases?: string[];
}
/**
* (experimental) Viewer certificate configuration class.
*
* @experimental
*/
export declare class ViewerCertificate {
readonly props: CfnDistribution.ViewerCertificateProperty;
readonly aliases: string[];
/**
* (experimental) Generate an AWS Certificate Manager (ACM) viewer certificate configuration.
*
* @param certificate AWS Certificate Manager (ACM) certificate.
* @param options certificate configuration options.
* @experimental
*/
static fromAcmCertificate(certificate: certificatemanager.ICertificate, options?: ViewerCertificateOptions): ViewerCertificate;
/**
* (experimental) Generate an IAM viewer certificate configuration.
*
* @param iamCertificateId Identifier of the IAM certificate.
* @param options certificate configuration options.
* @experimental
*/
static fromIamCertificate(iamCertificateId: string, options?: ViewerCertificateOptions): ViewerCertificate;
/**
* (experimental) Generate a viewer certifcate configuration using the CloudFront default certificate (e.g. d111111abcdef8.cloudfront.net) and a {@link SecurityPolicyProtocol.TLS_V1} security policy.
*
* @param aliases Alternative CNAME aliases You also must create a CNAME record with your DNS service to route queries.
* @experimental
*/
static fromCloudFrontDefaultCertificate(...aliases: string[]): ViewerCertificate;
private constructor();
}
/**
* @experimental
*/
export interface CloudFrontWebDistributionProps {
/**
* (deprecated) AliasConfiguration is used to configured CloudFront to respond to requests on custom domain names.
*
* @default - None.
* @deprecated see {@link CloudFrontWebDistributionProps#viewerCertificate} with {@link ViewerCertificate#acmCertificate}
*/
readonly aliasConfiguration?: AliasConfiguration;
/**
* (experimental) A comment for this distribution in the CloudFront console.
*
* @default - No comment is added to distribution.
* @experimental
*/
readonly comment?: string;
/**
* (experimental) The default object to serve.
*
* @default - "index.html" is served.
* @experimental
*/
readonly defaultRootObject?: string;
/**
* (experimental) If your distribution should have IPv6 enabled.
*
* @default true
* @experimental
*/
readonly enableIpV6?: boolean;
/**
* (experimental) The max supported HTTP Versions.
*
* @default HttpVersion.HTTP2
* @experimental
*/
readonly httpVersion?: HttpVersion;
/**
* (experimental) The price class for the distribution (this impacts how many locations CloudFront uses for your distribution, and billing).
*
* @default PriceClass.PRICE_CLASS_100 the cheapest option for CloudFront is picked by default.
* @experimental
*/
readonly priceClass?: PriceClass;
/**
* (experimental) The default viewer policy for incoming clients.
*
* @default RedirectToHTTPs
* @experimental
*/
readonly viewerProtocolPolicy?: ViewerProtocolPolicy;
/**
* (experimental) The origin configurations for this distribution.
*
* Behaviors are a part of the origin.
*
* @experimental
*/
readonly originConfigs: SourceConfiguration[];
/**
* (experimental) Optional - if we should enable logging.
*
* You can pass an empty object ({}) to have us auto create a bucket for logging.
* Omission of this property indicates no logging is to be enabled.
*
* @default - no logging is enabled by default.
* @experimental
*/
readonly loggingConfig?: LoggingConfiguration;
/**
* (experimental) How CloudFront should handle requests that are not successful (eg PageNotFound).
*
* By default, CloudFront does not replace HTTP status codes in the 4xx and 5xx range
* with custom error messages. CloudFront does not cache HTTP status codes.
*
* @default - No custom error configuration.
* @experimental
*/
readonly errorConfigurations?: CfnDistribution.CustomErrorResponseProperty[];
/**
* (experimental) Unique identifier that specifies the AWS WAF web ACL to associate with this CloudFront distribution.
*
* To specify a web ACL created using the latest version of AWS WAF, use the ACL ARN, for example
* `arn:aws:wafv2:us-east-1:123456789012:global/webacl/ExampleWebACL/473e64fd-f30b-4765-81a0-62ad96dd167a`.
*
* To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example `473e64fd-f30b-4765-81a0-62ad96dd167a`.
*
* @default - No AWS Web Application Firewall web access control list (web ACL).
* @see https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html#API_CreateDistribution_RequestParameters.
* @experimental
*/
readonly webACLId?: string;
/**
* (experimental) Specifies whether you want viewers to use HTTP or HTTPS to request your objects, whether you're using an alternate domain name with HTTPS, and if so, if you're using AWS Certificate Manager (ACM) or a third-party certificate authority.
*
* @default ViewerCertificate.fromCloudFrontDefaultCertificate()
* @see https://aws.amazon.com/premiumsupport/knowledge-center/custom-ssl-certificate-cloudfront/
* @experimental
*/
readonly viewerCertificate?: ViewerCertificate;
/**
* (experimental) Controls the countries in which your content is distributed.
*
* @default No geo restriction
* @experimental
*/
readonly geoRestriction?: GeoRestriction;
}
/**
* (experimental) Attributes used to import a Distribution.
*
* @experimental
*/
export interface CloudFrontWebDistributionAttributes {
/**
* (experimental) The generated domain name of the Distribution, such as d111111abcdef8.cloudfront.net.
*
* @experimental
* @attribute true
*/
readonly domainName: string;
/**
* (experimental) The distribution ID for this distribution.
*
* @experimental
* @attribute true
*/
readonly distributionId: string;
}
/**
* (experimental) Amazon CloudFront is a global content delivery network (CDN) service that securely delivers data, videos, applications, and APIs to your viewers with low latency and high transfer speeds.
*
* CloudFront fronts user provided content and caches it at edge locations across the world.
*
* Here's how you can use this construct:
*
* ```ts
* import { CloudFrontWebDistribution } from '@aws-cdk/aws-cloudfront'
*
* const sourceBucket = new Bucket(this, 'Bucket');
*
* const distribution = new CloudFrontWebDistribution(this, 'MyDistribution', {
* originConfigs: [
* {
* s3OriginSource: {
* s3BucketSource: sourceBucket
* },
* behaviors : [ {isDefaultBehavior: true}]
* }
* ]
* });
* ```
*
* This will create a CloudFront distribution that uses your S3Bucket as it's origin.
*
* You can customize the distribution using additional properties from the CloudFrontWebDistributionProps interface.
*
* @experimental
* @resource AWS::CloudFront::Distribution
*/
export declare class CloudFrontWebDistribution extends cdk.Resource implements IDistribution {
/**
* (experimental) Creates a construct that represents an external (imported) distribution.
*
* @experimental
*/
static fromDistributionAttributes(scope: Construct, id: string, attrs: CloudFrontWebDistributionAttributes): IDistribution;
/**
* (experimental) The logging bucket for this CloudFront distribution.
*
* If logging is not enabled for this distribution - this property will be undefined.
*
* @experimental
*/
readonly loggingBucket?: s3.IBucket;
/**
* (deprecated) The domain name created by CloudFront for this distribution.
*
* If you are using aliases for your distribution, this is the domainName your DNS records should point to.
* (In Route53, you could create an ALIAS record to this value, for example.)
*
* @deprecated - Use `distributionDomainName` instead.
*/
readonly domainName: string;
/**
* (experimental) The domain name created by CloudFront for this distribution.
*
* If you are using aliases for your distribution, this is the domainName your DNS records should point to.
* (In Route53, you could create an ALIAS record to this value, for example.)
*
* @experimental
*/
readonly distributionDomainName: string;
/**
* (experimental) The distribution ID for this distribution.
*
* @experimental
*/
readonly distributionId: string;
/**
* Maps our methods to the string arrays they are
*/
private readonly METHOD_LOOKUP_MAP;
/**
* Maps for which SecurityPolicyProtocol are available to which SSLMethods
*/
private readonly VALID_SSL_PROTOCOLS;
/**
* @experimental
*/
constructor(scope: Construct, id: string, props: CloudFrontWebDistributionProps);
private toBehavior;
private toOriginProperty;
} | the_stack |
import {
cleanup,
initStream,
jetstreamExportServerConf,
jetstreamServerConf,
setup,
time,
} from "./jstest_util.ts";
import {
AckPolicy,
ConsumerConfig,
ConsumerOpts,
consumerOpts,
createInbox,
deferred,
delay,
DeliverPolicy,
Empty,
ErrorCode,
headers,
JsHeaders,
JsMsg,
JsMsgCallback,
JSONCodec,
nanos,
NatsConnectionImpl,
NatsError,
nuid,
QueuedIterator,
RetentionPolicy,
StorageType,
StringCodec,
} from "../nats-base-client/internal_mod.ts";
import {
assertEquals,
assertThrows,
assertThrowsAsync,
fail,
} from "https://deno.land/std@0.95.0/testing/asserts.ts";
import { assert } from "../nats-base-client/denobuffer.ts";
import { PubAck } from "../nats-base-client/types.ts";
import {
JetStreamClientImpl,
JetStreamSubscriptionInfoable,
} from "../nats-base-client/jsclient.ts";
import { defaultJsOptions } from "../nats-base-client/jsbaseclient_api.ts";
import { connect } from "../src/connect.ts";
import { ConsumerOptsBuilderImpl } from "../nats-base-client/jsconsumeropts.ts";
import { assertBetween, disabled, Lock, notCompatible } from "./helpers/mod.ts";
import {
isFlowControlMsg,
isHeartbeatMsg,
} from "../nats-base-client/jsutil.ts";
function callbackConsume(debug = false): JsMsgCallback {
return (err: NatsError | null, jm: JsMsg | null) => {
if (err) {
switch (err.code) {
case ErrorCode.JetStream408RequestTimeout:
case ErrorCode.JetStream409MaxAckPendingExceeded:
case ErrorCode.JetStream404NoMessages:
return;
default:
fail(err.code);
}
}
if (debug && jm) {
console.dir(jm.info);
if (jm.headers) {
console.info(jm.headers.toString());
}
}
if (jm) {
jm.ack();
}
};
}
async function consume(iter: QueuedIterator<JsMsg>): Promise<JsMsg[]> {
const buf: JsMsg[] = [];
await (async () => {
for await (const m of iter) {
m.ack();
buf.push(m);
}
})();
return buf;
}
Deno.test("jetstream - default options", () => {
const opts = defaultJsOptions();
assertEquals(opts, { apiPrefix: "$JS.API", timeout: 5000 });
});
Deno.test("jetstream - default override timeout", () => {
const opts = defaultJsOptions({ timeout: 1000 });
assertEquals(opts, { apiPrefix: "$JS.API", timeout: 1000 });
});
Deno.test("jetstream - default override prefix", () => {
const opts = defaultJsOptions({ apiPrefix: "$XX.API" });
assertEquals(opts, { apiPrefix: "$XX.API", timeout: 5000 });
});
Deno.test("jetstream - options rejects empty prefix", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
assertThrows(() => {
nc.jetstream({ apiPrefix: "" });
});
await cleanup(ns, nc);
});
Deno.test("jetstream - options removes trailing dot", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const js = nc.jetstream({ apiPrefix: "hello." }) as JetStreamClientImpl;
assertEquals(js.opts.apiPrefix, "hello");
await cleanup(ns, nc);
});
Deno.test("jetstream - find stream throws when not found", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const js = nc.jetstream() as JetStreamClientImpl;
await assertThrowsAsync(
async () => {
await js.findStream("hello");
},
Error,
"no stream matches subject",
);
await cleanup(ns, nc);
});
Deno.test("jetstream - publish basic", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const js = nc.jetstream();
let pa = await js.publish(subj);
assertEquals(pa.stream, stream);
assertEquals(pa.duplicate, false);
assertEquals(pa.seq, 1);
pa = await js.publish(subj);
assertEquals(pa.stream, stream);
assertEquals(pa.duplicate, false);
assertEquals(pa.seq, 2);
await cleanup(ns, nc);
});
Deno.test("jetstream - ackAck", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
await js.publish(subj);
const ms = await js.pull(stream, "me");
assertEquals(await ms.ackAck(), true);
assertEquals(await ms.ackAck(), false);
await cleanup(ns, nc);
});
Deno.test("jetstream - publish id", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const js = nc.jetstream();
const pa = await js.publish(subj, Empty, { msgID: "a" });
assertEquals(pa.stream, stream);
assertEquals(pa.duplicate, false);
assertEquals(pa.seq, 1);
const jsm = await nc.jetstreamManager();
const sm = await jsm.streams.getMessage(stream, { seq: 1 });
assertEquals(sm.header.get("Nats-Msg-Id"), "a");
await cleanup(ns, nc);
});
Deno.test("jetstream - publish require stream", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const js = nc.jetstream();
await assertThrowsAsync(
async () => {
await js.publish(subj, Empty, { expect: { streamName: "xxx" } });
},
Error,
"expected stream does not match",
);
const pa = await js.publish(subj, Empty, { expect: { streamName: stream } });
assertEquals(pa.stream, stream);
assertEquals(pa.duplicate, false);
assertEquals(pa.seq, 1);
await cleanup(ns, nc);
});
Deno.test("jetstream - publish require last message id", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const js = nc.jetstream();
let pa = await js.publish(subj, Empty, { msgID: "a" });
assertEquals(pa.stream, stream);
assertEquals(pa.duplicate, false);
assertEquals(pa.seq, 1);
await assertThrowsAsync(
async () => {
await js.publish(subj, Empty, { msgID: "b", expect: { lastMsgID: "b" } });
},
Error,
"wrong last msg id: a",
);
pa = await js.publish(subj, Empty, {
msgID: "b",
expect: { lastMsgID: "a" },
});
assertEquals(pa.stream, stream);
assertEquals(pa.duplicate, false);
assertEquals(pa.seq, 2);
await cleanup(ns, nc);
});
Deno.test("jetstream - get message last by subject", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const jsm = await nc.jetstreamManager();
const stream = nuid.next();
await jsm.streams.add({ name: stream, subjects: [`${stream}.*`] });
const js = nc.jetstream();
const sc = StringCodec();
await js.publish(`${stream}.A`, sc.encode("a"));
await js.publish(`${stream}.A`, sc.encode("aa"));
await js.publish(`${stream}.B`, sc.encode("b"));
await js.publish(`${stream}.B`, sc.encode("bb"));
const sm = await jsm.streams.getMessage(stream, {
last_by_subj: `${stream}.A`,
});
assertEquals(sc.decode(sm.data), "aa");
await cleanup(ns, nc);
});
Deno.test("jetstream - publish require last sequence", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const js = nc.jetstream();
await js.publish(subj, Empty);
await assertThrowsAsync(
async () => {
await js.publish(subj, Empty, {
msgID: "b",
expect: { lastSequence: 2 },
});
},
Error,
"wrong last sequence: 1",
);
const pa = await js.publish(subj, Empty, {
msgID: "b",
expect: { lastSequence: 1 },
});
assertEquals(pa.stream, stream);
assertEquals(pa.duplicate, false);
assertEquals(pa.seq, 2);
await cleanup(ns, nc);
});
Deno.test("jetstream - publish require last sequence by subject", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const jsm = await nc.jetstreamManager();
const stream = nuid.next();
await jsm.streams.add({ name: stream, subjects: [`${stream}.*`] });
const js = nc.jetstream();
await js.publish(`${stream}.A`, Empty);
await js.publish(`${stream}.B`, Empty);
const pa = await js.publish(`${stream}.A`, Empty, {
expect: { lastSubjectSequence: 1 },
});
for (let i = 0; i < 100; i++) {
await js.publish(`${stream}.B`, Empty);
}
// this will only succeed if the last recording sequence for the subject matches
await js.publish(`${stream}.A`, Empty, {
expect: { lastSubjectSequence: pa.seq },
});
await cleanup(ns, nc);
});
Deno.test("jetstream - ephemeral push", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { subj } = await initStream(nc);
const js = nc.jetstream();
await js.publish(subj);
const opts = {
max: 1,
config: { deliver_subject: createInbox() },
} as ConsumerOpts;
opts.callbackFn = callbackConsume();
const sub = await js.subscribe(subj, opts);
await sub.closed;
assertEquals(sub.getProcessed(), 1);
await cleanup(ns, nc);
});
Deno.test("jetstream - durable", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const js = nc.jetstream();
await js.publish(subj);
const opts = consumerOpts();
opts.durable("me");
opts.manualAck();
opts.ackExplicit();
opts.maxMessages(1);
opts.deliverTo(createInbox());
let sub = await js.subscribe(subj, opts);
const done = (async () => {
for await (const m of sub) {
m.ack();
}
})();
await done;
assertEquals(sub.getProcessed(), 1);
// consumer should exist
const jsm = await nc.jetstreamManager();
const ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.name, "me");
// delete the consumer
sub = await js.subscribe(subj, opts);
await sub.destroy();
await assertThrowsAsync(
async () => {
await jsm.consumers.info(stream, "me");
},
Error,
"consumer not found",
);
await cleanup(ns, nc);
});
Deno.test("jetstream - queue error checks", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
if (await notCompatible(ns, nc, "2.3.5")) {
return;
}
const { stream, subj } = await initStream(nc);
const js = nc.jetstream();
await assertThrowsAsync(
async () => {
const opts = consumerOpts();
opts.durable("me");
opts.deliverTo("x");
opts.queue("x");
opts.idleHeartbeat(1000);
await js.subscribe(subj, opts);
},
Error,
"jetstream idle heartbeat is not supported with queue groups",
);
await assertThrowsAsync(
async () => {
const opts = consumerOpts();
opts.durable("me");
opts.deliverTo("x");
opts.queue("x");
opts.flowControl();
await js.subscribe(subj, opts);
},
Error,
"jetstream flow control is not supported with queue groups",
);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
deliver_group: "x",
ack_policy: AckPolicy.Explicit,
deliver_subject: "x",
});
await assertThrowsAsync(
async () => {
await js.subscribe(subj, {
stream: stream,
config: { durable_name: "me", deliver_group: "y" },
});
},
Error,
"durable requires queue group 'x'",
);
await jsm.consumers.add(stream, {
durable_name: "memo",
ack_policy: AckPolicy.Explicit,
deliver_subject: "z",
});
await assertThrowsAsync(
async () => {
await js.subscribe(subj, {
stream: stream,
config: { durable_name: "memo", deliver_group: "y" },
});
},
Error,
"durable requires no queue group",
);
await cleanup(ns, nc);
});
Deno.test("jetstream - pull no messages", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
await assertThrowsAsync(
async () => {
await js.pull(stream, "me");
},
Error,
"no messages",
);
await cleanup(ns, nc);
});
Deno.test("jetstream - pull", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
await js.publish(subj, Empty, { msgID: "a" });
let ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 1);
const jm = await js.pull(stream, "me");
jm.ack();
ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 0);
assertEquals(ci.delivered.stream_seq, 1);
assertEquals(ci.ack_floor.stream_seq, 1);
await cleanup(ns, nc);
});
Deno.test("jetstream - fetch expires waits", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
const start = Date.now();
const iter = js.fetch(stream, "me", { expires: 1000 });
await (async () => {
for await (const _m of iter) {
// nothing
}
})();
const elapsed = Date.now() - start;
assertBetween(elapsed, 950, 1050);
assertEquals(iter.getReceived(), 0);
await cleanup(ns, nc);
});
Deno.test("jetstream - fetch expires waits after initial", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
await js.publish(subj, Empty);
const start = Date.now();
const iter = js.fetch(stream, "me", { expires: 1000, batch: 5 });
await (async () => {
for await (const _m of iter) {
// nothing
}
})();
const elapsed = Date.now() - start;
assertBetween(elapsed, 950, 1050);
assertEquals(iter.getReceived(), 1);
await cleanup(ns, nc);
});
Deno.test("jetstream - fetch expires or no_wait is required", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
assertThrows(
() => {
js.fetch(stream, "me");
},
Error,
"expires or no_wait is required",
);
await cleanup(ns, nc);
});
Deno.test("jetstream - fetch: no_wait with more left", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
await js.publish(subj);
await js.publish(subj);
const iter = js.fetch(stream, "me", { no_wait: true });
await consume(iter);
await cleanup(ns, nc);
});
Deno.test("jetstream - fetch some messages", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
// try to get messages = none available
let sub = await js.fetch(stream, "me", { batch: 2, no_wait: true });
await (async () => {
for await (const m of sub) {
m.ack();
}
})();
assertEquals(sub.getProcessed(), 0);
// seed some messages
await js.publish(subj, Empty, { msgID: "a" });
await js.publish(subj, Empty, { msgID: "b" });
await js.publish(subj, Empty, { msgID: "c" });
// try to get 2 messages - OK
sub = await js.fetch(stream, "me", { batch: 2, no_wait: true });
await (async () => {
for await (const m of sub) {
m.ack();
}
})();
assertEquals(sub.getProcessed(), 2);
let ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 1);
assertEquals(ci.delivered.stream_seq, 2);
assertEquals(ci.ack_floor.stream_seq, 2);
// try to get 2 messages - OK, but only gets 1
sub = await js.fetch(stream, "me", { batch: 2, no_wait: true });
await (async () => {
for await (const m of sub) {
m.ack();
}
})();
assertEquals(sub.getProcessed(), 1);
ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 0);
assertEquals(ci.delivered.stream_seq, 3);
assertEquals(ci.ack_floor.stream_seq, 3);
// try to get 2 messages - OK, none available
sub = await js.fetch(stream, "me", { batch: 2, no_wait: true });
await (async () => {
for await (const m of sub) {
m.ack();
}
})();
assertEquals(sub.getProcessed(), 0);
await cleanup(ns, nc);
});
Deno.test("jetstream - max ack pending", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
const sc = StringCodec();
const d = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
const buf: Promise<PubAck>[] = [];
const js = nc.jetstream();
d.forEach((v) => {
buf.push(js.publish(subj, sc.encode(v), { msgID: v }));
});
await Promise.all(buf);
const consumers = await jsm.consumers.list(stream).next();
assert(consumers.length === 0);
const opts = consumerOpts();
opts.maxAckPending(2);
opts.maxMessages(10);
opts.manualAck();
opts.deliverTo(createInbox());
const sub = await js.subscribe(subj, opts);
await (async () => {
for await (const m of sub) {
assert(
sub.getPending() < 3,
`didn't expect pending messages greater than 2`,
);
m.ack();
}
})();
await cleanup(ns, nc);
});
Deno.test("jetstream - pull sub - attached iterator", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const jc = JSONCodec<number>();
let sum = 0;
const opts = consumerOpts();
opts.durable("me");
const js = nc.jetstream();
const sub = await js.pullSubscribe(subj, opts);
(async () => {
for await (const msg of sub) {
assert(msg);
const n = jc.decode(msg.data);
sum += n;
msg.ack();
}
})().then();
sub.pull({ expires: 500, batch: 5 });
const subin = sub as unknown as JetStreamSubscriptionInfoable;
assert(subin.info);
assertEquals(subin.info.attached, true);
await delay(250);
assertEquals(sum, 0);
let ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 0);
assertEquals(ci.delivered.stream_seq, 0);
assertEquals(ci.ack_floor.stream_seq, 0);
await js.publish(subj, jc.encode(1), { msgID: "1" });
await js.publish(subj, jc.encode(2), { msgID: "2" });
sub.pull({ expires: 500, batch: 5 });
await delay(500);
assertEquals(sum, 3);
ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 0);
assertEquals(ci.delivered.stream_seq, 2);
assertEquals(ci.ack_floor.stream_seq, 2);
await js.publish(subj, jc.encode(3), { msgID: "3" });
await js.publish(subj, jc.encode(5), { msgID: "4" });
sub.pull({ expires: 500, batch: 5 });
await delay(1000);
assertEquals(sum, 11);
ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 0);
assertEquals(ci.delivered.stream_seq, 4);
assertEquals(ci.ack_floor.stream_seq, 4);
await js.publish(subj, jc.encode(7), { msgID: "5" });
ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 1);
await cleanup(ns, nc);
});
Deno.test("jetstream - pull sub - attached callback", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const jc = JSONCodec<number>();
let sum = 0;
const opts = consumerOpts();
opts.durable("me");
opts.callback((err, msg) => {
if (err) {
switch (err.code) {
case ErrorCode.JetStream408RequestTimeout:
case ErrorCode.JetStream409MaxAckPendingExceeded:
case ErrorCode.JetStream404NoMessages:
return;
default:
fail(err.code);
}
}
if (msg) {
const n = jc.decode(msg.data);
sum += n;
msg.ack();
}
});
const js = nc.jetstream();
const sub = await js.pullSubscribe(subj, opts);
sub.pull({ expires: 500, batch: 5 });
const subin = sub as unknown as JetStreamSubscriptionInfoable;
assert(subin.info);
assertEquals(subin.info.attached, true);
await delay(250);
assertEquals(sum, 0);
let ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 0);
assertEquals(ci.delivered.stream_seq, 0);
assertEquals(ci.ack_floor.stream_seq, 0);
await js.publish(subj, jc.encode(1), { msgID: "1" });
await js.publish(subj, jc.encode(2), { msgID: "2" });
sub.pull({ expires: 500, batch: 5 });
await delay(500);
assertEquals(sum, 3);
ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 0);
assertEquals(ci.delivered.stream_seq, 2);
assertEquals(ci.ack_floor.stream_seq, 2);
await js.publish(subj, jc.encode(3), { msgID: "3" });
await js.publish(subj, jc.encode(5), { msgID: "4" });
sub.pull({ expires: 500, batch: 5 });
await delay(1000);
assertEquals(sum, 11);
ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 0);
assertEquals(ci.delivered.stream_seq, 4);
assertEquals(ci.ack_floor.stream_seq, 4);
await js.publish(subj, jc.encode(7), { msgID: "5" });
ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 1);
await cleanup(ns, nc);
});
Deno.test("jetstream - pull sub - not attached callback", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const js = nc.jetstream();
await js.publish(subj);
const opts = consumerOpts();
opts.durable("me");
opts.ackExplicit();
opts.maxMessages(1);
opts.callback(callbackConsume(false));
const sub = await js.pullSubscribe(subj, opts);
sub.pull();
const subin = sub as unknown as JetStreamSubscriptionInfoable;
assert(subin.info);
assertEquals(subin.info.attached, false);
await sub.closed;
const jsm = await nc.jetstreamManager();
const ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 0);
assertEquals(ci.delivered.stream_seq, 1);
assertEquals(ci.ack_floor.stream_seq, 1);
await cleanup(ns, nc);
});
Deno.test("jetstream - pull sub requires explicit", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { subj } = await initStream(nc);
const js = nc.jetstream();
await assertThrowsAsync(
async () => {
const opts = consumerOpts();
opts.durable("me");
opts.ackAll();
await js.pullSubscribe(subj, opts);
},
Error,
"ack policy for pull",
);
await cleanup(ns, nc);
});
Deno.test("jetstream - subscribe - not attached callback", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const js = nc.jetstream();
await js.publish(subj, Empty, { expect: { lastSequence: 0 } });
await js.publish(subj, Empty, { expect: { lastSequence: 1 } });
await js.publish(subj, Empty, { expect: { lastSequence: 2 } });
await js.publish(subj, Empty, { expect: { lastSequence: 3 } });
await js.publish(subj, Empty, { expect: { lastSequence: 4 } });
const opts = consumerOpts();
opts.durable("me");
opts.ackExplicit();
opts.callback(callbackConsume(false));
opts.deliverTo(createInbox());
const sub = await js.subscribe(subj, opts);
const subin = sub as unknown as JetStreamSubscriptionInfoable;
assert(subin.info);
assertEquals(subin.info.attached, false);
await delay(500);
sub.unsubscribe();
await nc.flush();
const jsm = await nc.jetstreamManager();
const ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 0);
assertEquals(ci.delivered.stream_seq, 5);
assertEquals(ci.ack_floor.stream_seq, 5);
await cleanup(ns, nc);
});
Deno.test("jetstream - subscribe - not attached non-durable", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { subj } = await initStream(nc);
const js = nc.jetstream();
await js.publish(subj, Empty, { expect: { lastSequence: 0 } });
await js.publish(subj, Empty, { expect: { lastSequence: 1 } });
await js.publish(subj, Empty, { expect: { lastSequence: 2 } });
await js.publish(subj, Empty, { expect: { lastSequence: 3 } });
await js.publish(subj, Empty, { expect: { lastSequence: 4 } });
const opts = consumerOpts();
opts.ackExplicit();
opts.callback(callbackConsume());
opts.deliverTo(createInbox());
const sub = await js.subscribe(subj, opts);
const subin = sub as unknown as JetStreamSubscriptionInfoable;
assert(subin.info);
assertEquals(subin.info.attached, false);
await delay(500);
assertEquals(sub.getProcessed(), 5);
sub.unsubscribe();
await cleanup(ns, nc);
});
Deno.test("jetstream - fetch none - breaks after expires", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
const sw = time();
const batch = js.fetch(stream, "me", {
batch: 10,
expires: 1000,
});
const done = (async () => {
for await (const m of batch) {
console.log(m.info);
fail("expected no messages");
}
})();
await done;
sw.mark();
sw.assertInRange(1000);
assertEquals(batch.getReceived(), 0);
await cleanup(ns, nc);
});
Deno.test("jetstream - fetch none - no wait breaks fast", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
const sw = time();
const batch = js.fetch(stream, "me", {
batch: 10,
no_wait: true,
});
const done = (async () => {
for await (const m of batch) {
m.ack();
}
})();
await done;
sw.mark();
assert(25 > sw.duration());
assertEquals(batch.getReceived(), 0);
await cleanup(ns, nc);
});
Deno.test("jetstream - fetch one - no wait breaks fast", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
await js.publish(subj);
const sw = time();
const batch = js.fetch(stream, "me", {
batch: 10,
no_wait: true,
});
const done = (async () => {
for await (const m of batch) {
m.ack();
}
})();
await done;
sw.mark();
assert(25 > sw.duration());
assertEquals(batch.getReceived(), 1);
await cleanup(ns, nc);
});
Deno.test("jetstream - fetch none - cancel timers", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
const sw = time();
const batch = js.fetch(stream, "me", {
batch: 10,
expires: 1000,
});
const done = (async () => {
for await (const m of batch) {
m.ack();
}
})();
const nci = nc as NatsConnectionImpl;
const last = nci.protocol.subscriptions.sidCounter;
const sub = nci.protocol.subscriptions.get(last);
assert(sub);
sub.unsubscribe();
await done;
sw.mark();
assert(25 > sw.duration());
assertEquals(batch.getReceived(), 0);
await cleanup(ns, nc);
});
Deno.test("jetstream - fetch one - breaks after expires", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
nc.publish(subj);
const js = nc.jetstream();
const sw = time();
const batch = js.fetch(stream, "me", {
batch: 10,
expires: 1000,
});
const done = (async () => {
for await (const m of batch) {
m.ack();
}
})();
await done;
sw.mark();
sw.assertInRange(1000);
assertEquals(batch.getReceived(), 1);
await cleanup(ns, nc);
});
Deno.test("jetstream - pull consumer info without pull", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
await js.publish(subj);
const ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 1);
const sopts = consumerOpts();
sopts.durable("me");
await assertThrowsAsync(
async () => {
await js.subscribe(subj, sopts);
},
Error,
"consumer info specifies a pull consumer",
);
await cleanup(ns, nc);
});
Deno.test("jetstream - autoack", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
deliver_subject: createInbox(),
});
const js = nc.jetstream();
await js.publish(subj);
let ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 1);
const sopts = consumerOpts();
sopts.ackAll();
sopts.durable("me");
sopts.callback(() => {
// nothing
});
sopts.maxMessages(1);
const sub = await js.subscribe(subj, sopts);
await sub.closed;
ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 0);
assertEquals(ci.num_waiting, 0);
assertEquals(ci.num_ack_pending, 0);
await cleanup(ns, nc);
});
Deno.test("jetstream - subscribe - info", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { subj } = await initStream(nc);
const js = nc.jetstream();
await js.publish(subj, Empty, { expect: { lastSequence: 0 } });
await js.publish(subj, Empty, { expect: { lastSequence: 1 } });
await js.publish(subj, Empty, { expect: { lastSequence: 2 } });
await js.publish(subj, Empty, { expect: { lastSequence: 3 } });
await js.publish(subj, Empty, { expect: { lastSequence: 4 } });
const opts = consumerOpts();
opts.ackExplicit();
opts.callback(callbackConsume());
opts.deliverTo(createInbox());
const sub = await js.subscribe(subj, opts);
await delay(250);
const ci = await sub.consumerInfo();
assertEquals(ci.delivered.stream_seq, 5);
assertEquals(ci.ack_floor.stream_seq, 5);
await sub.destroy();
await assertThrowsAsync(
async () => {
await sub.consumerInfo();
},
Error,
"consumer not found",
);
await cleanup(ns, nc);
});
Deno.test("jetstream - deliver new", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { subj } = await initStream(nc);
const js = nc.jetstream();
await js.publish(subj, Empty, { expect: { lastSequence: 0 } });
await js.publish(subj, Empty, { expect: { lastSequence: 1 } });
await js.publish(subj, Empty, { expect: { lastSequence: 2 } });
await js.publish(subj, Empty, { expect: { lastSequence: 3 } });
await js.publish(subj, Empty, { expect: { lastSequence: 4 } });
const opts = consumerOpts();
opts.ackExplicit();
opts.deliverNew();
opts.maxMessages(1);
opts.deliverTo(createInbox());
const sub = await js.subscribe(subj, opts);
const done = (async () => {
for await (const m of sub) {
assertEquals(m.seq, 6);
}
})();
await js.publish(subj, Empty, { expect: { lastSequence: 5 } });
await done;
await cleanup(ns, nc);
});
Deno.test("jetstream - deliver last", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { subj } = await initStream(nc);
const js = nc.jetstream();
await js.publish(subj, Empty, { expect: { lastSequence: 0 } });
await js.publish(subj, Empty, { expect: { lastSequence: 1 } });
await js.publish(subj, Empty, { expect: { lastSequence: 2 } });
await js.publish(subj, Empty, { expect: { lastSequence: 3 } });
await js.publish(subj, Empty, { expect: { lastSequence: 4 } });
const opts = consumerOpts();
opts.ackExplicit();
opts.deliverLast();
opts.maxMessages(1);
opts.deliverTo(createInbox());
const sub = await js.subscribe(subj, opts);
const done = (async () => {
for await (const m of sub) {
assertEquals(m.seq, 5);
}
})();
await done;
await cleanup(ns, nc);
});
Deno.test("jetstream - last of", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const jsm = await nc.jetstreamManager();
const n = nuid.next();
await jsm.streams.add({
name: n,
subjects: [`${n}.>`],
});
const subja = `${n}.A`;
const subjb = `${n}.B`;
const js = nc.jetstream();
await js.publish(subja, Empty);
await js.publish(subjb, Empty);
await js.publish(subjb, Empty);
await js.publish(subja, Empty);
const opts = {
durable_name: "B",
filter_subject: subjb,
deliver_policy: DeliverPolicy.Last,
ack_policy: AckPolicy.Explicit,
} as Partial<ConsumerConfig>;
await jsm.consumers.add(n, opts);
const m = await js.pull(n, "B");
assertEquals(m.seq, 3);
await cleanup(ns, nc);
});
Deno.test("jetstream - deliver seq", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { subj } = await initStream(nc);
const js = nc.jetstream();
await js.publish(subj, Empty, { expect: { lastSequence: 0 } });
await js.publish(subj, Empty, { expect: { lastSequence: 1 } });
await js.publish(subj, Empty, { expect: { lastSequence: 2 } });
await js.publish(subj, Empty, { expect: { lastSequence: 3 } });
await js.publish(subj, Empty, { expect: { lastSequence: 4 } });
const opts = consumerOpts();
opts.ackExplicit();
opts.startSequence(2);
opts.maxMessages(1);
opts.deliverTo(createInbox());
const sub = await js.subscribe(subj, opts);
const done = (async () => {
for await (const m of sub) {
assertEquals(m.seq, 2);
}
})();
await done;
await cleanup(ns, nc);
});
Deno.test("jetstream - deliver start time", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { subj } = await initStream(nc);
const js = nc.jetstream();
await js.publish(subj, Empty, { expect: { lastSequence: 0 } });
await js.publish(subj, Empty, { expect: { lastSequence: 1 } });
await delay(1000);
const now = new Date();
await js.publish(subj, Empty, { expect: { lastSequence: 2 } });
const opts = consumerOpts();
opts.ackExplicit();
opts.startTime(now);
opts.maxMessages(1);
opts.deliverTo(createInbox());
const sub = await js.subscribe(subj, opts);
const done = (async () => {
for await (const m of sub) {
assertEquals(m.seq, 3);
}
})();
await done;
await cleanup(ns, nc);
});
Deno.test("jetstream - deliver last per subject", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
if (await notCompatible(ns, nc)) {
return;
}
const jsm = await nc.jetstreamManager();
const stream = nuid.next();
const subj = `${stream}.*`;
await jsm.streams.add(
{ name: stream, subjects: [subj] },
);
const js = nc.jetstream();
await js.publish(`${stream}.A`, Empty, { expect: { lastSequence: 0 } });
await js.publish(`${stream}.B`, Empty, { expect: { lastSequence: 1 } });
await js.publish(`${stream}.A`, Empty, { expect: { lastSequence: 2 } });
await js.publish(`${stream}.B`, Empty, { expect: { lastSequence: 3 } });
await js.publish(`${stream}.A`, Empty, { expect: { lastSequence: 4 } });
await js.publish(`${stream}.B`, Empty, { expect: { lastSequence: 5 } });
const opts = consumerOpts();
opts.ackExplicit();
opts.deliverLastPerSubject();
opts.deliverTo(createInbox());
const sub = await js.subscribe(subj, opts);
const ci = await sub.consumerInfo();
const buf: JsMsg[] = [];
assertEquals(ci.num_ack_pending, 2);
const done = (async () => {
for await (const m of sub) {
buf.push(m);
if (buf.length === 2) {
sub.unsubscribe();
}
}
})();
await done;
assertEquals(buf[0].info.streamSequence, 5);
assertEquals(buf[1].info.streamSequence, 6);
await cleanup(ns, nc);
});
Deno.test("jetstream - cross account subscribe", async () => {
const { ns, nc: admin } = await setup(
jetstreamExportServerConf(),
{
user: "js",
pass: "js",
},
);
// add a stream
const { subj } = await initStream(admin);
const adminjs = admin.jetstream();
await adminjs.publish(subj);
await adminjs.publish(subj);
// create a durable config
const bo = consumerOpts() as ConsumerOptsBuilderImpl;
bo.durable("me");
bo.manualAck();
bo.maxMessages(2);
bo.deliverTo(createInbox("A"));
const nc = await connect({
port: ns.port,
user: "a",
pass: "s3cret",
});
const js = nc.jetstream({ apiPrefix: "IPA" });
const opts = bo.getOpts();
const sub = await js.subscribe(subj, opts);
await (async () => {
for await (const m of sub) {
m.ack();
}
})();
const ci = await sub.consumerInfo();
assertEquals(ci.num_pending, 0);
assertEquals(ci.delivered.stream_seq, 2);
await sub.destroy();
await assertThrowsAsync(
async () => {
await sub.consumerInfo();
},
Error,
"consumer not found",
);
await cleanup(ns, admin, nc);
});
Deno.test("jetstream - cross account pull subscribe", () => {
disabled("cross account pull subscribe test needs updating");
// const { ns, nc: admin } = await setup(
// jetstreamExportServerConf(),
// {
// user: "js",
// pass: "js",
// },
// );
//
// // add a stream
// const { stream, subj } = await initStream(admin);
// const adminjs = admin.jetstream();
// await adminjs.publish(subj);
// await adminjs.publish(subj);
//
// // FIXME: create a durable config
// const bo = consumerOpts() as ConsumerOptsBuilderImpl;
// bo.manualAck();
// bo.ackExplicit();
// bo.maxMessages(2);
// bo.durable("me");
//
// // pull subscriber stalls
// const nc = await connect({
// port: ns.port,
// user: "a",
// pass: "s3cret",
// inboxPrefix: "A",
// });
// const js = nc.jetstream({ apiPrefix: "IPA" });
//
// const opts = bo.getOpts();
// const sub = await js.pullSubscribe(subj, opts);
// const done = (async () => {
// for await (const m of sub) {
// m.ack();
// }
// })();
// sub.pull({ batch: 2 });
// await done;
// assertEquals(sub.getProcessed(), 2);
//
// const ci = await sub.consumerInfo();
// assertEquals(ci.num_pending, 0);
// assertEquals(ci.delivered.stream_seq, 2);
//
// await sub.destroy();
// await assertThrowsAsync(
// async () => {
// await sub.consumerInfo();
// },
// Error,
// "consumer not found",
// );
//
// await cleanup(ns, admin, nc);
});
Deno.test("jetstream - cross account pull", async () => {
const { ns, nc: admin } = await setup(
jetstreamExportServerConf(),
{
user: "js",
pass: "js",
},
);
// add a stream
const { stream, subj } = await initStream(admin);
const admjs = admin.jetstream();
await admjs.publish(subj);
await admjs.publish(subj);
const admjsm = await admin.jetstreamManager();
// create a durable config
const bo = consumerOpts() as ConsumerOptsBuilderImpl;
bo.manualAck();
bo.ackExplicit();
bo.durable("me");
const opts = bo.getOpts();
await admjsm.consumers.add(stream, opts.config);
const nc = await connect({
port: ns.port,
user: "a",
pass: "s3cret",
inboxPrefix: "A",
});
// the api prefix is not used for pull/fetch()
const js = nc.jetstream({ apiPrefix: "IPA" });
let msg = await js.pull(stream, "me");
assertEquals(msg.seq, 1);
msg = await js.pull(stream, "me");
assertEquals(msg.seq, 2);
await assertThrowsAsync(
async () => {
await js.pull(stream, "me");
},
Error,
"no messages",
);
await cleanup(ns, admin, nc);
});
Deno.test("jetstream - publish headers", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
const js = nc.jetstream();
const h = headers();
h.set("a", "b");
await js.publish(subj, Empty, { headers: h });
const ms = await js.pull(stream, "me");
ms.ack();
assertEquals(ms.headers!.get("a"), "b");
await cleanup(ns, nc);
});
Deno.test("jetstream - pull stream doesn't exist", async () => {
const { ns, nc } = await setup(jetstreamServerConf());
const js = nc.jetstream({ timeout: 1000 });
await assertThrowsAsync(
async () => {
await js.pull("helloworld", "me");
},
Error,
ErrorCode.Timeout,
);
await cleanup(ns, nc);
});
Deno.test("jetstream - pull consumer doesn't exist", async () => {
const { ns, nc } = await setup(jetstreamServerConf());
const { stream } = await initStream(nc);
const js = nc.jetstream({ timeout: 1000 });
await assertThrowsAsync(
async () => {
await js.pull(stream, "me");
},
Error,
ErrorCode.Timeout,
);
await cleanup(ns, nc);
});
// Deno.test("jetstream - cross account fetch", async () => {
// const { ns, nc: admin } = await setup(
// jetstreamExportServerConf(),
// {
// user: "js",
// pass: "js",
// },
// );
//
// // add a stream
// const { stream, subj } = await initStream(admin);
// const admjs = admin.jetstream();
// await admjs.publish(subj, Empty, {msgID: "1"});
// await admjs.publish(subj, Empty, {msgID: "2"});
//
// const admjsm = await admin.jetstreamManager();
//
// // create a durable config
// const bo = consumerOpts() as ConsumerOptsBuilderImpl;
// bo.manualAck();
// bo.ackExplicit();
// bo.durable("me");
// bo.maxAckPending(10);
// const opts = bo.getOpts();
// await admjsm.consumers.add(stream, opts.config);
//
// const nc = await connect({
// port: ns.port,
// user: "a",
// pass: "s3cret",
// inboxPrefix: "A",
// debug: true,
// });
//
// // the api prefix is not used for pull/fetch()
// const js = nc.jetstream({ apiPrefix: "IPA" });
// let iter = js.fetch(stream, "me", { batch: 20, expires: 1000 });
// const msgs = await consume(iter);
//
// assertEquals(msgs.length, 2);
//
// // msg = await js.pull(stream, "me");
// // assertEquals(msg.seq, 2);
// // await assertThrowsAsync(async () => {
// // await js.pull(stream, "me");
// // }, Error, "No Messages");
//
// await cleanup(ns, admin, nc);
// });
Deno.test("jetstream - pull consumer doesn't exist", async () => {
const { ns, nc } = await setup(jetstreamServerConf());
const { stream } = await initStream(nc);
const js = nc.jetstream({ timeout: 1000 });
await assertThrowsAsync(
async () => {
await js.pull(stream, "me");
},
Error,
ErrorCode.Timeout,
);
await cleanup(ns, nc);
});
Deno.test("jetstream - ack lease extends with working", async () => {
const { ns, nc } = await setup(jetstreamServerConf());
const sn = nuid.next();
const jsm = await nc.jetstreamManager();
await jsm.streams.add({ name: sn, subjects: [`${sn}.>`] });
const js = nc.jetstream();
await js.publish(`${sn}.A`, Empty, { msgID: "1" });
const inbox = createInbox();
const cc = {
"ack_wait": nanos(2000),
"deliver_subject": inbox,
"ack_policy": AckPolicy.Explicit,
"durable_name": "me",
};
await jsm.consumers.add(sn, cc);
const opts = consumerOpts();
opts.durable("me");
opts.manualAck();
const sub = await js.subscribe(`${sn}.>`, opts);
const done = (async () => {
for await (const m of sub) {
const timer = setInterval(() => {
m.working();
}, 750);
// we got a message now we are going to delay for 31 sec
await delay(15);
const ci = await jsm.consumers.info(sn, "me");
assertEquals(ci.num_ack_pending, 1);
m.ack();
clearInterval(timer);
break;
}
})();
await done;
// make sure the message went out
await nc.flush();
const ci2 = await jsm.consumers.info(sn, "me");
assertEquals(ci2.delivered.stream_seq, 1);
assertEquals(ci2.num_redelivered, 0);
assertEquals(ci2.num_ack_pending, 0);
await cleanup(ns, nc);
});
Deno.test("jetstream - JSON", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jc = JSONCodec();
const js = nc.jetstream();
const values = [undefined, null, true, "", ["hello"], { hello: "world" }];
for (const v of values) {
await js.publish(subj, jc.encode(v));
}
const jsm = await nc.jetstreamManager();
await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
for (let v of values) {
const m = await js.pull(stream, "me");
m.ack();
// JSON doesn't serialize undefines, but if passed to the encoder
// it becomes a null
if (v === undefined) {
v = null;
}
assertEquals(jc.decode(m.data), v);
}
await cleanup(ns, nc);
});
Deno.test("jetstream - qsub", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
if (await notCompatible(ns, nc, "2.3.5")) {
return;
}
const { subj } = await initStream(nc);
const js = nc.jetstream();
const opts = consumerOpts();
opts.queue("q");
opts.durable("n");
opts.deliverTo("here");
opts.callback((_err, m) => {
if (m) {
m.ack();
}
});
const sub = await js.subscribe(subj, opts);
const sub2 = await js.subscribe(subj, opts);
for (let i = 0; i < 100; i++) {
await js.publish(subj, Empty);
}
await nc.flush();
await sub.drain();
await sub2.drain();
assert(sub.getProcessed() > 0);
assert(sub2.getProcessed() > 0);
assertEquals(sub.getProcessed() + sub2.getProcessed(), 100);
await cleanup(ns, nc);
});
Deno.test("jetstream - qsub ackall", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
if (await notCompatible(ns, nc, "2.3.5")) {
return;
}
const { stream, subj } = await initStream(nc);
const js = nc.jetstream();
const opts = consumerOpts();
opts.queue("q");
opts.durable("n");
opts.deliverTo("here");
opts.ackAll();
opts.callback((_err, _m) => {});
const sub = await js.subscribe(subj, opts);
const sub2 = await js.subscribe(subj, opts);
for (let i = 0; i < 100; i++) {
await js.publish(subj, Empty);
}
await nc.flush();
await sub.drain();
await sub2.drain();
assert(sub.getProcessed() > 0);
assert(sub2.getProcessed() > 0);
assertEquals(sub.getProcessed() + sub2.getProcessed(), 100);
const jsm = await nc.jetstreamManager();
const ci = await jsm.consumers.info(stream, "n");
assertEquals(ci.num_pending, 0);
assertEquals(ci.num_ack_pending, 0);
await cleanup(ns, nc);
});
Deno.test("jetstream - idle heartbeats", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
nc.publish(subj);
const jsm = await nc.jetstreamManager();
const inbox = createInbox();
await jsm.consumers.add(stream, {
durable_name: "me",
deliver_subject: inbox,
idle_heartbeat: nanos(2000),
});
const sub = nc.subscribe(inbox, {
callback: (_err, msg) => {
if (isHeartbeatMsg(msg)) {
assertEquals(msg.headers?.get(JsHeaders.LastConsumerSeqHdr), "1");
assertEquals(msg.headers?.get(JsHeaders.LastStreamSeqHdr), "1");
sub.drain();
}
},
});
await sub.closed;
await cleanup(ns, nc);
});
Deno.test("jetstream - flow control", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
for (let i = 0; i < 10000; i++) {
nc.publish(subj, Empty);
}
await nc.flush();
const jsm = await nc.jetstreamManager();
const inbox = createInbox();
await jsm.consumers.add(stream, {
durable_name: "me",
deliver_subject: inbox,
flow_control: true,
idle_heartbeat: nanos(750),
});
let fc = 0;
const sub = nc.subscribe(inbox, {
callback: (_err, msg) => {
if (isHeartbeatMsg(msg)) {
sub.drain();
return;
}
if (isFlowControlMsg(msg)) {
fc++;
}
msg.respond();
},
});
await sub.closed;
assert(fc > 0);
assertEquals(sub.getProcessed(), 10000 + fc + 1);
await cleanup(ns, nc);
});
Deno.test("jetstream - domain", async () => {
const { ns, nc } = await setup(
jetstreamServerConf({
jetstream: {
domain: "afton",
},
}, true),
);
const jsm = await nc.jetstreamManager({ domain: "afton" });
const ai = await jsm.getAccountInfo();
assert(ai.domain, "afton");
//@ts-ignore: internal use
assertEquals(jsm.prefix, `$JS.afton.API`);
await cleanup(ns, nc);
});
Deno.test("jetstream - account domain", async () => {
const conf = jetstreamServerConf({
jetstream: {
domain: "A",
},
accounts: {
A: {
users: [
{ user: "a", password: "a" },
],
jetstream: { max_memory: 10000, max_file: 10000 },
},
},
}, true);
const { ns, nc } = await setup(conf, { user: "a", pass: "a" });
const jsm = await nc.jetstreamManager({ domain: "A" });
const ai = await jsm.getAccountInfo();
assert(ai.domain, "A");
//@ts-ignore: internal use
assertEquals(jsm.prefix, `$JS.A.API`);
await cleanup(ns, nc);
});
Deno.test("jetstream - durable resumes", async () => {
let { ns, nc } = await setup(jetstreamServerConf({}, true), {
maxReconnectAttempts: -1,
reconnectTimeWait: 100,
});
const { stream, subj } = await initStream(nc);
const jc = JSONCodec();
const jsm = await nc.jetstreamManager();
const js = nc.jetstream();
let values = ["a", "b", "c"];
for (const v of values) {
await js.publish(subj, jc.encode(v));
}
const dsubj = createInbox();
const opts = consumerOpts();
opts.ackExplicit();
opts.deliverAll();
opts.deliverTo(dsubj);
opts.durable("me");
const sub = await js.subscribe(subj, opts);
const done = (async () => {
for await (const m of sub) {
m.ack();
if (m.seq === 6) {
sub.unsubscribe();
}
}
})();
await nc.flush();
await ns.stop();
ns = await ns.restart();
await delay(300);
values = ["d", "e", "f"];
for (const v of values) {
await js.publish(subj, jc.encode(v));
}
await nc.flush();
await done;
const si = await jsm.streams.info(stream);
assertEquals(si.state.messages, 6);
const ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.delivered.stream_seq, 6);
assertEquals(ci.num_pending, 0);
await cleanup(ns, nc);
});
Deno.test("jetstream - puback domain", async () => {
const { ns, nc } = await setup(
jetstreamServerConf({
jetstream: {
domain: "A",
},
}, true),
);
if (await notCompatible(ns, nc, "2.3.5")) {
return;
}
const { subj } = await initStream(nc);
const js = nc.jetstream();
const pa = await js.publish(subj);
assertEquals(pa.domain, "A");
await cleanup(ns, nc);
});
Deno.test("jetstream - cleanup", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { subj } = await initStream(nc);
const js = nc.jetstream();
for (let i = 0; i < 100; i++) {
await js.publish(subj, Empty);
}
const opts = consumerOpts();
opts.deliverTo(createInbox());
const sub = await js.subscribe(subj, opts);
let counter = 0;
const done = (async () => {
for await (const m of sub) {
counter++;
m.ack();
break;
}
})();
await done;
assertEquals(counter, 1);
assertEquals(sub.isClosed(), true);
const nci = nc as NatsConnectionImpl;
const min = nci.protocol.subscriptions.getMux() ? 1 : 0;
assertEquals(nci.protocol.subscriptions.subs.size, min);
await cleanup(ns, nc);
});
Deno.test("jetstream - reuse consumer", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const id = nuid.next();
const jsm = await nc.jetstreamManager();
await jsm.streams.add({
subjects: [`${id}.*`],
name: id,
retention: RetentionPolicy.Workqueue,
});
await jsm.consumers.add(id, {
"durable_name": "X",
"deliver_subject": "out",
"deliver_policy": DeliverPolicy.All,
"ack_policy": AckPolicy.Explicit,
"deliver_group": "queuea",
});
// second create should be OK, since it is idempotent
await jsm.consumers.add(id, {
"durable_name": "X",
"deliver_subject": "out",
"deliver_policy": DeliverPolicy.All,
"ack_policy": AckPolicy.Explicit,
"deliver_group": "queuea",
});
const js = nc.jetstream();
const opts = consumerOpts();
opts.ackExplicit();
opts.durable("X");
opts.deliverAll();
opts.deliverTo("out2");
opts.queue("queuea");
const sub = await js.subscribe(`${id}.*`, opts);
const ci = await sub.consumerInfo();
// the deliver subject we specified should be ignored
// the one specified by the consumer is used
assertEquals(ci.config.deliver_subject, "out");
await cleanup(ns, nc);
});
Deno.test("jetstream - pull sub - multiple consumers", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const { stream, subj } = await initStream(nc);
const jsm = await nc.jetstreamManager();
const js = nc.jetstream();
const buf: Promise<PubAck>[] = [];
for (let i = 0; i < 100; i++) {
buf.push(js.publish(subj, Empty));
}
await Promise.all(buf);
let ci = await jsm.consumers.add(stream, {
durable_name: "me",
ack_policy: AckPolicy.Explicit,
});
assertEquals(ci.num_pending, 100);
let countA = 0;
let countB = 0;
const m = new Map<number, number>();
const opts = consumerOpts();
opts.durable("me");
opts.ackExplicit();
opts.deliverAll();
const subA = await js.pullSubscribe(subj, opts);
(async () => {
for await (const msg of subA) {
const v = m.get(msg.seq) ?? 0;
m.set(msg.seq, v + 1);
countA++;
msg.ack();
}
})().then();
const subB = await js.pullSubscribe(subj, opts);
(async () => {
for await (const msg of subB) {
const v = m.get(msg.seq) ?? 0;
m.set(msg.seq, v + 1);
countB++;
msg.ack();
}
})().then();
const done = deferred<void>();
// deno-lint-ignore no-unused-vars
const interval = setInterval(() => {
if (countA + countB < 100) {
subA.pull({ expires: 500, batch: 25 });
subB.pull({ expires: 500, batch: 25 });
} else {
clearInterval(interval);
done.resolve();
}
}, 25);
await done;
ci = await jsm.consumers.info(stream, "me");
assertEquals(ci.num_pending, 0);
assert(countA > 0);
assert(countB > 0);
assertEquals(countA + countB, 100);
for (let i = 1; i <= 100; i++) {
assertEquals(m.get(i), 1);
}
await cleanup(ns, nc);
});
Deno.test("jetstream - source", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
const stream = nuid.next();
const subj = `${stream}.*`;
const jsm = await nc.jetstreamManager();
await jsm.streams.add(
{ name: stream, subjects: [subj] },
);
const js = nc.jetstream();
for (let i = 0; i < 10; i++) {
await js.publish(`${stream}.A`);
await js.publish(`${stream}.B`);
}
await jsm.streams.add({
name: "work",
storage: StorageType.File,
retention: RetentionPolicy.Workqueue,
sources: [
{ name: stream, filter_subject: ">" },
],
});
const ci = await jsm.consumers.add("work", {
ack_policy: AckPolicy.Explicit,
durable_name: "worker",
filter_subject: `${stream}.B`,
deliver_subject: createInbox(),
});
const sub = await js.subscribe(`${stream}.B`, { config: ci.config });
for await (const m of sub) {
m.ack();
if (m.info.pending === 0) {
break;
}
}
const si = await jsm.streams.info("work");
// stream still has all the 'A' messages
assertEquals(si.state.messages, 10);
await cleanup(ns, nc);
});
Deno.test("jetstream - redelivery property works", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
if (await notCompatible(ns, nc, "2.3.5")) {
return;
}
const { stream, subj } = await initStream(nc);
const js = nc.jetstream();
let r = 0;
const opts = consumerOpts();
opts.ackAll();
opts.queue("q");
opts.durable("n");
opts.deliverTo(createInbox());
opts.callback((_err, m) => {
if (m) {
if (m.info.redelivered) {
r++;
}
if (m.seq === 100) {
m.ack();
}
if (m.seq % 3 === 0) {
m.nak();
}
}
});
const sub = await js.subscribe(subj, opts);
const sub2 = await js.subscribe(subj, opts);
for (let i = 0; i < 100; i++) {
await js.publish(subj, Empty);
}
await nc.flush();
await sub.drain();
await sub2.drain();
assert(sub.getProcessed() > 0);
assert(sub2.getProcessed() > 0);
assertEquals(sub.getProcessed() + sub2.getProcessed(), 100 + r);
const jsm = await nc.jetstreamManager();
const ci = await jsm.consumers.info(stream, "n");
assertEquals(ci.delivered.consumer_seq, 100 + r);
await cleanup(ns, nc);
});
async function ocTest(
N: number,
S: number,
callback: boolean,
): Promise<void> {
if (N % 10 !== 0) {
throw new Error("N must be divisible by 10");
}
const storage = N * S + (1024 * 1024);
const { ns, nc } = await setup(jetstreamServerConf({
jetstream: {
max_file_store: storage,
},
}, true));
const { subj } = await initStream(nc);
const js = nc.jetstream();
const buf = new Uint8Array(S);
for (let i = 0; i < S; i++) {
buf[i] = "a".charCodeAt(0) + (i % 26);
}
// speed up the loading by sending 10 at time
const n = N / 10;
for (let i = 0; i < n; i++) {
await Promise.all([
js.publish(subj, buf),
js.publish(subj, buf),
js.publish(subj, buf),
js.publish(subj, buf),
js.publish(subj, buf),
js.publish(subj, buf),
js.publish(subj, buf),
js.publish(subj, buf),
js.publish(subj, buf),
js.publish(subj, buf),
]);
}
const lock = Lock(N, 1000 * 60);
const opts = consumerOpts({ idle_heartbeat: nanos(1000) });
opts.orderedConsumer();
if (callback) {
opts.callback((err: NatsError | null, msg: JsMsg | null): void => {
if (err) {
fail(err.message);
return;
}
if (!msg) {
fail(`didn't expect to get null msg`);
return;
}
lock.unlock();
});
}
const sub = await js.subscribe(subj, opts);
if (!callback) {
(async () => {
for await (const _jm of sub) {
lock.unlock();
}
})().then();
}
await lock;
//@ts-ignore: test
assertEquals(sub.sub.info.ordered_consumer_sequence.stream_seq, N);
//@ts-ignore: test
assertEquals(sub.sub.info.ordered_consumer_sequence.delivery_seq, N);
await delay(3 * 1000);
// @ts-ignore: test
const hbc = sub.sub.info.flow_control.heartbeat_count;
assert(hbc >= 2);
// @ts-ignore: test
const fcc = sub.sub.info.flow_control.fc_count;
assert(fcc > 0);
// @ts-ignore: test
assert(sub.sub.info.flow_control.consumer_restarts >= 0);
// @ts-ignore: test
assert(sub.sub.info.flow_control.heartbeat_count > 0);
const ci = await sub.consumerInfo();
assertEquals(ci.config.deliver_policy, DeliverPolicy.All);
assertEquals(ci.config.ack_policy, AckPolicy.None);
assertEquals(ci.config.max_deliver, 1);
assertEquals(ci.num_pending, 0);
assertEquals(ci.delivered.consumer_seq, N);
assertEquals(ci.delivered.stream_seq, N);
await cleanup(ns, nc);
}
Deno.test("jetstream - ordered consumer callback", async () => {
await ocTest(500, 1024, true);
});
Deno.test("jetstream - ordered consumer iterator", async () => {
await ocTest(500, 1024, false);
});
Deno.test("jetstream - seal", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
if (await notCompatible(ns, nc, "2.6.2")) {
return;
}
const { stream, subj } = await initStream(nc);
const js = nc.jetstream();
const sc = StringCodec();
await js.publish(subj, sc.encode("hello"));
await js.publish(subj, sc.encode("second"));
const jsm = await nc.jetstreamManager();
const si = await jsm.streams.info(stream);
assertEquals(si.config.sealed, false);
assertEquals(si.config.deny_purge, false);
assertEquals(si.config.deny_delete, false);
await jsm.streams.deleteMessage(stream, 1);
si.config.sealed = true;
const usi = await jsm.streams.update(si.config);
assertEquals(usi.config.sealed, true);
await assertThrowsAsync(
async () => {
await jsm.streams.deleteMessage(stream, 2);
},
Error,
"invalid operation on sealed stream",
);
await cleanup(ns, nc);
});
Deno.test("jetstream - deny delete", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
if (await notCompatible(ns, nc, "2.6.2")) {
return;
}
const jsm = await nc.jetstreamManager();
const stream = nuid.next();
const subj = `${stream}.*`;
await jsm.streams.add({
name: stream,
subjects: [subj],
deny_delete: true,
});
const js = nc.jetstream();
const sc = StringCodec();
await js.publish(subj, sc.encode("hello"));
await js.publish(subj, sc.encode("second"));
const si = await jsm.streams.info(stream);
assertEquals(si.config.deny_delete, true);
await assertThrowsAsync(
async () => {
await jsm.streams.deleteMessage(stream, 1);
},
Error,
"message delete not permitted",
);
await cleanup(ns, nc);
});
Deno.test("jetstream - deny purge", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
if (await notCompatible(ns, nc, "2.6.2")) {
return;
}
const jsm = await nc.jetstreamManager();
const stream = nuid.next();
const subj = `${stream}.*`;
await jsm.streams.add({
name: stream,
subjects: [subj],
deny_purge: true,
});
const js = nc.jetstream();
const sc = StringCodec();
await js.publish(subj, sc.encode("hello"));
await js.publish(subj, sc.encode("second"));
const si = await jsm.streams.info(stream);
assertEquals(si.config.deny_purge, true);
await assertThrowsAsync(
async () => {
await jsm.streams.purge(stream);
},
Error,
"stream purge not permitted",
);
await cleanup(ns, nc);
});
Deno.test("jetstream - rollup all", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
if (await notCompatible(ns, nc, "2.6.3")) {
return;
}
const jsm = await nc.jetstreamManager();
const stream = nuid.next();
const subj = `${stream}.*`;
await jsm.streams.add({
name: stream,
subjects: [subj],
allow_rollup_hdrs: true,
});
const js = nc.jetstream();
const jc = JSONCodec();
const buf = [];
for (let i = 1; i < 11; i++) {
buf.push(js.publish(`${stream}.A`, jc.encode({ value: i })));
}
await Promise.all(buf);
const h = headers();
h.set(JsHeaders.RollupHdr, JsHeaders.RollupValueAll);
await js.publish(`${stream}.summary`, jc.encode({ value: 42 }), {
headers: h,
});
const si = await jsm.streams.info(stream);
assertEquals(si.state.messages, 1);
const opts = consumerOpts();
opts.manualAck();
opts.deliverTo(createInbox());
opts.callback((_err, jm) => {
assert(jm);
assertEquals(jm.subject, `${stream}.summary`);
const obj = jc.decode(jm.data) as Record<string, number>;
assertEquals(obj.value, 42);
});
opts.maxMessages(1);
const sub = await js.subscribe(subj, opts);
await sub;
assertEquals(sub.getProcessed(), 1);
await cleanup(ns, nc);
});
Deno.test("jetstream - rollup subject", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
if (await notCompatible(ns, nc, "2.6.3")) {
return;
}
const jsm = await nc.jetstreamManager();
const stream = "S";
const subj = `${stream}.*`;
await jsm.streams.add({
name: stream,
subjects: [subj],
allow_rollup_hdrs: true,
});
const js = nc.jetstream();
const jc = JSONCodec<Record<string, number>>();
const buf = [];
for (let i = 1; i < 11; i++) {
buf.push(js.publish(`${stream}.A`, jc.encode({ value: i })));
buf.push(js.publish(`${stream}.B`, jc.encode({ value: i })));
}
await Promise.all(buf);
let si = await jsm.streams.info(stream);
assertEquals(si.state.messages, 20);
let cia = await jsm.consumers.add(stream, {
durable_name: "dura",
filter_subject: `${stream}.A`,
ack_policy: AckPolicy.Explicit,
});
assertEquals(cia.num_pending, 10);
const h = headers();
h.set(JsHeaders.RollupHdr, JsHeaders.RollupValueSubject);
await js.publish(`${stream}.A`, jc.encode({ value: 42 }), {
headers: h,
});
await delay(5000);
cia = await jsm.consumers.info(stream, "dura");
assertEquals(cia.num_pending, 1);
si = await jsm.streams.info(stream);
assertEquals(si.state.messages, 11);
const cib = await jsm.consumers.add(stream, {
durable_name: "durb",
filter_subject: `${stream}.B`,
ack_policy: AckPolicy.Explicit,
});
assertEquals(cib.num_pending, 10);
await cleanup(ns, nc);
});
Deno.test("jetstream - no rollup", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
if (await notCompatible(ns, nc, "2.6.3")) {
return;
}
const jsm = await nc.jetstreamManager();
const stream = "S";
const subj = `${stream}.*`;
const si = await jsm.streams.add({
name: stream,
subjects: [subj],
allow_rollup_hdrs: false,
});
assertEquals(si.config.allow_rollup_hdrs, false);
const js = nc.jetstream();
const jc = JSONCodec<Record<string, number>>();
const buf = [];
for (let i = 1; i < 11; i++) {
buf.push(js.publish(`${stream}.A`, jc.encode({ value: i })));
}
await Promise.all(buf);
const h = headers();
h.set(JsHeaders.RollupHdr, JsHeaders.RollupValueSubject);
await assertThrowsAsync(
async () => {
await js.publish(`${stream}.A`, jc.encode({ value: 42 }), {
headers: h,
});
},
Error,
"rollup not permitted",
);
await cleanup(ns, nc);
});
Deno.test("jetstream - headers only", async () => {
const { ns, nc } = await setup(jetstreamServerConf({}, true));
if (await notCompatible(ns, nc, "2.6.2")) {
return;
}
const jsm = await nc.jetstreamManager();
const stream = nuid.next();
const subj = `${stream}.*`;
await jsm.streams.add({
name: stream,
subjects: [subj],
});
const js = nc.jetstream();
const sc = StringCodec();
await js.publish(`${stream}.A`, sc.encode("a"));
await js.publish(`${stream}.B`, sc.encode("b"));
const opts = consumerOpts();
opts.deliverTo(createInbox());
opts.headersOnly();
opts.manualAck();
opts.callback((_err, jm) => {
assert(jm);
assert(jm.headers);
const size = parseInt(jm.headers.get(JsHeaders.MessageSizeHdr), 10);
assertEquals(size, 1);
assertEquals(jm.data, Empty);
jm.ack();
});
opts.maxMessages(2);
const sub = await js.subscribe(subj, opts);
await sub.closed;
assertEquals(sub.getProcessed(), 2);
await cleanup(ns, nc);
}); | the_stack |
import { Utils } from "./Utils.js";
import { DockManager } from "./DockManager.js";
import { DockWheelItem } from "./DockWheelItem.js";
import { WheelTypes } from "./enums/WheelTypes.js";
import { Dialog } from "./Dialog.js";
import { DockNode } from "./DockNode.js";
/**
* Manages the dock overlay buttons that are displayed over the dock manager
*/
export class DockWheel {
dockManager: DockManager;
elementMainWheel: HTMLDivElement;
elementSideWheel: HTMLDivElement;
wheelItems: { [index in WheelTypes]?: DockWheelItem; };
elementPanelPreview: HTMLDivElement;
activeDialog: Dialog;
_activeNode?: DockNode;
_visible: boolean;
constructor(dockManager: DockManager) {
this.dockManager = dockManager;
this.elementMainWheel = document.createElement('div'); // Contains the main wheel's 5 dock buttons
this.elementSideWheel = document.createElement('div'); // Contains the 4 buttons on the side
this.wheelItems = {};
for (let wheelType in WheelTypes) {
this.wheelItems[wheelType] = new DockWheelItem(this, <WheelTypes>wheelType);
if (wheelType.substr(-2, 2) === '-s')
// Side button
this.elementSideWheel.appendChild(this.wheelItems[wheelType].element);
else
// Main dock wheel button
this.elementMainWheel.appendChild(this.wheelItems[wheelType].element);
};
let zIndex = 9000000;
this.elementMainWheel.classList.add('dock-wheel-base');
this.elementSideWheel.classList.add('dock-wheel-base');
this.elementMainWheel.style.zIndex = String(zIndex + 1);
this.elementSideWheel.style.zIndex = String(zIndex);
this.elementPanelPreview = document.createElement('div');
this.elementPanelPreview.classList.add('dock-wheel-panel-preview');
this.elementPanelPreview.style.zIndex = String(zIndex - 1);
this.activeDialog = undefined; // The dialog being dragged, when the wheel is visible
this._activeNode = undefined;
this._visible = false;
}
/** The node over which the dock wheel is being displayed on */
get activeNode(): DockNode {
return this._activeNode;
}
set activeNode(value: DockNode) {
let previousValue = this._activeNode;
this._activeNode = value;
if (previousValue !== this._activeNode) {
// The active node has been changed.
// Reattach the wheel to the new node's element and show it again
if (this._visible)
this.showWheel();
}
}
showWheel() {
this._visible = true;
if (!this.activeNode) {
// No active node selected. make sure the wheel is invisible
Utils.removeNode(this.elementMainWheel);
Utils.removeNode(this.elementSideWheel);
return;
}
let element = this.activeNode.container.containerElement;
let containerWidth = element.clientWidth;
let containerHeight = element.clientHeight;
let baseX = Math.floor(containerWidth / 2); // + element.offsetLeft;
let baseY = Math.floor(containerHeight / 2); // + element.offsetTop;
let bcElement = element.getBoundingClientRect();
let bcdockManagerElement = this.dockManager.element.getBoundingClientRect()
this.elementMainWheel.style.left = (bcElement.left - bcdockManagerElement.left + baseX) + 'px';
this.elementMainWheel.style.top = (bcElement.top - bcdockManagerElement.top + baseY) + 'px';
// The positioning of the main dock wheel buttons is done automatically through CSS
// Dynamically calculate the positions of the buttons on the extreme sides of the dock manager
let sideMargin = 20;
let dockManagerWidth = this.dockManager.element.clientWidth;
let dockManagerHeight = this.dockManager.element.clientHeight;
Utils.removeNode(this.elementMainWheel);
Utils.removeNode(this.elementSideWheel);
this.dockManager.element.appendChild(this.elementMainWheel);
this.dockManager.element.appendChild(this.elementSideWheel);
this._setWheelButtonPosition(WheelTypes["left-s"], sideMargin, -dockManagerHeight / 2);
this._setWheelButtonPosition(WheelTypes["right-s"], dockManagerWidth - sideMargin * 2, -dockManagerHeight / 2);
this._setWheelButtonPosition(WheelTypes["top-s"], dockManagerWidth / 2, -dockManagerHeight + sideMargin);
this._setWheelButtonPosition(WheelTypes["down-s"], dockManagerWidth / 2, -sideMargin);
}
_setWheelButtonPosition(wheelId: WheelTypes, left: number, top: number) {
let item = this.wheelItems[wheelId];
let itemHalfWidth = item.element.clientWidth / 2;
let itemHalfHeight = item.element.clientHeight / 2;
let x = Math.floor(left - itemHalfWidth);
let y = Math.floor(top - itemHalfHeight);
// item.element.style.left = '${x}px';
// item.element.style.top = '${y}px';
item.element.style.marginLeft = x + 'px';
item.element.style.marginTop = y + 'px';
}
hideWheel() {
this._visible = false;
this.activeNode = undefined;
Utils.removeNode(this.elementMainWheel);
Utils.removeNode(this.elementSideWheel);
Utils.removeNode(this.elementPanelPreview);
// deactivate all wheels
for (let wheelType in this.wheelItems)
this.wheelItems[wheelType].active = false;
}
onMouseOver(wheelItem: DockWheelItem) {
if (!this.activeDialog)
return;
// Display the preview panel to show where the panel would be docked
let rootNode = this.dockManager.context.model.rootNode;
let bounds;
if (wheelItem.id === WheelTypes.top) {
bounds = this.dockManager.layoutEngine.getDockBounds(this.activeNode, this.activeDialog.panel, 'vertical', true);
} else if (wheelItem.id === WheelTypes.down) {
bounds = this.dockManager.layoutEngine.getDockBounds(this.activeNode, this.activeDialog.panel, 'vertical', false);
} else if (wheelItem.id === WheelTypes.left) {
bounds = this.dockManager.layoutEngine.getDockBounds(this.activeNode, this.activeDialog.panel, 'horizontal', true);
} else if (wheelItem.id === WheelTypes.right) {
bounds = this.dockManager.layoutEngine.getDockBounds(this.activeNode, this.activeDialog.panel, 'horizontal', false);
} else if (wheelItem.id === WheelTypes.fill) {
bounds = this.dockManager.layoutEngine.getDockBounds(this.activeNode, this.activeDialog.panel, 'fill', false);
} else if (wheelItem.id === WheelTypes["top-s"]) {
bounds = this.dockManager.layoutEngine.getDockBounds(rootNode, this.activeDialog.panel, 'vertical', true);
} else if (wheelItem.id === WheelTypes["down-s"]) {
bounds = this.dockManager.layoutEngine.getDockBounds(rootNode, this.activeDialog.panel, 'vertical', false);
} else if (wheelItem.id === WheelTypes["left-s"]) {
bounds = this.dockManager.layoutEngine.getDockBounds(rootNode, this.activeDialog.panel, 'horizontal', true);
} else if (wheelItem.id === WheelTypes["right-s"]) {
bounds = this.dockManager.layoutEngine.getDockBounds(rootNode, this.activeDialog.panel, 'horizontal', false);
}
if (bounds) {
this.dockManager.element.appendChild(this.elementPanelPreview);
this.elementPanelPreview.style.left = Math.round(bounds.x) + 'px';
this.elementPanelPreview.style.top = Math.round(bounds.y) + 'px';
this.elementPanelPreview.style.width = Math.round(bounds.width) + 'px';
this.elementPanelPreview.style.height = Math.round(bounds.height) + 'px';
}
}
onMouseOut() {
Utils.removeNode(this.elementPanelPreview);
}
/**
* Called if the dialog is dropped in a dock panel.
* The dialog might not necessarily be dropped in one of the dock wheel buttons,
* in which case the request will be ignored
*/
onDialogDropped(dialog: Dialog) {
// Check if the dialog was dropped in one of the wheel items
let wheelItem = this._getActiveWheelItem();
if (wheelItem)
this._handleDockRequest(wheelItem, dialog);
}
/**
* Returns the wheel item which has the mouse cursor on top of it
*/
_getActiveWheelItem(): DockWheelItem {
for (let wheelType in this.wheelItems) {
let wheelItem = this.wheelItems[wheelType];
if (wheelItem.active)
return wheelItem;
}
return undefined;
}
_handleDockRequest(wheelItem: DockWheelItem, dialog: Dialog) {
wheelItem.active = false;
wheelItem.element.classList.remove(wheelItem.hoverIconClass);
if (!this.activeNode)
return;
if (wheelItem.id === WheelTypes.left) {
this.dockManager.dockDialogLeft(this.activeNode, dialog);
} else if (wheelItem.id === WheelTypes.right) {
this.dockManager.dockDialogRight(this.activeNode, dialog);
} else if (wheelItem.id === WheelTypes.top) {
this.dockManager.dockDialogUp(this.activeNode, dialog);
} else if (wheelItem.id === WheelTypes.down) {
this.dockManager.dockDialogDown(this.activeNode, dialog);
} else if (wheelItem.id === WheelTypes.fill) {
this.dockManager.dockDialogFill(this.activeNode, dialog);
} else if (wheelItem.id === WheelTypes["left-s"]) {
this.dockManager.dockDialogLeft(this.dockManager.context.model.rootNode, dialog);
} else if (wheelItem.id === WheelTypes["right-s"]) {
this.dockManager.dockDialogRight(this.dockManager.context.model.rootNode, dialog);
} else if (wheelItem.id === WheelTypes["top-s"]) {
this.dockManager.dockDialogUp(this.dockManager.context.model.rootNode, dialog);
} else if (wheelItem.id === WheelTypes["down-s"]) {
this.dockManager.dockDialogDown(this.dockManager.context.model.rootNode, dialog);
}
}
} | the_stack |
* @module Toolbar
*/
import "./Toolbar.scss";
import classnames from "classnames";
import * as React from "react";
import {
ActionButton, CommonToolbarItem, ConditionalBooleanValue, ConditionalStringValue, CustomButtonDefinition,
GroupButton, OnItemExecutedFunc, ToolbarItemUtilities,
} from "@itwin/appui-abstract";
import { BadgeUtilities, CommonProps, IconHelper, NoChildrenProps, useRefs } from "@itwin/core-react";
import { ToolbarButtonItem } from "./Item";
import { ToolbarItems } from "./Items";
import { ItemWrapper, useResizeObserverSingleDimension } from "./ItemWrapper";
import { ToolbarOverflowButton } from "./Overflow";
import { ToolbarOverflowPanel } from "./OverflowPanel";
import { PopupItem } from "./PopupItem";
import { PopupItemsPanel } from "./PopupItemsPanel";
import { PopupItemWithDrag } from "./PopupItemWithDrag";
import { Direction, DirectionHelpers, OrthogonalDirection, OrthogonalDirectionHelpers } from "./utilities/Direction";
import { UiComponents } from "../UiComponents";
/** Describes the data needed to insert a custom `React` button into an ToolbarWithOverflow.
* @public
*/
export interface CustomToolbarItem extends CustomButtonDefinition {
/** React node that must result in providing a PopupItem @deprecated use panelContentNode */
buttonNode?: React.ReactNode;
/** defines the content to display in popup panel */
panelContentNode?: React.ReactNode;
/** If true the popup panel is mounted once and unmounted when button is unmounted. If false the
* content node is unmounted each time the popup is closed. */
keepContentsLoaded?: boolean;
}
/**
* Context used by Toolbar items to know if popup panel should be hidden - via AutoHide.
* @public
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
export const ToolbarPopupAutoHideContext = React.createContext<boolean>(false);
/**
* React hook used to retrieve the ToolbarPopupAutoHideContext.
* @public
*/
export function useToolbarPopupAutoHideContext() {
return React.useContext(ToolbarPopupAutoHideContext);
}
/** Describes toolbar item.
* @public
*/
export type ToolbarItem = ActionButton | GroupButton | CustomToolbarItem;
/** CustomToolbarItem type guard.
* @internal
*/
export function isCustomToolbarItem(item: ToolbarItem): item is CustomToolbarItem {
return !!(item as CustomToolbarItem).isCustom && (("buttonNode" in item) || ("panelContentNode" in item));
}
/** @internal */
export const getToolbarDirection = (expandsTo: Direction): OrthogonalDirection => {
const orthogonalDirection = DirectionHelpers.getOrthogonalDirection(expandsTo);
return OrthogonalDirectionHelpers.inverse(orthogonalDirection);
};
/** Available alignment modes of [[ToolbarWithOverflow]] panels.
* @public
*/
export enum ToolbarPanelAlignment {
Start,
End,
}
/** Enumeration of Toolbar Opacity setting.
* @public
*/
export enum ToolbarOpacitySetting {
/** Use the default background, box-shadow opacity and backdrop-filter blur */
Defaults,
/** Alter the opacity from transparent to the defaults based on mouse proximity */
Proximity,
/** Use a transparent background, box-shadow opacity and backdrop-filter blur */
Transparent,
}
/** Helpers for [[ToolbarPanelAlignment]].
* @internal
*/
export class ToolbarPanelAlignmentHelpers {
/** Class name of [[ToolbarPanelAlignment.Start]] */
public static readonly START_CLASS_NAME = "components-panel-alignment-start";
/** Class name of [[ToolbarPanelAlignment.End]] */
public static readonly END_CLASS_NAME = "components-panel-alignment-end";
/** @returns Class name of specified [[ToolbarPanelAlignment]] */
public static getCssClassName(panelAlignment: ToolbarPanelAlignment): string {
switch (panelAlignment) {
case ToolbarPanelAlignment.Start:
return ToolbarPanelAlignmentHelpers.START_CLASS_NAME;
case ToolbarPanelAlignment.End:
return ToolbarPanelAlignmentHelpers.END_CLASS_NAME;
}
}
}
/** @internal */
export interface ToolbarOverflowContextProps {
readonly expandsTo: Direction;
readonly direction: OrthogonalDirection;
readonly overflowExpandsTo: Direction;
readonly overflowDirection: OrthogonalDirection;
readonly panelAlignment: ToolbarPanelAlignment;
readonly useDragInteraction: boolean;
readonly toolbarOpacitySetting: ToolbarOpacitySetting;
readonly openPopupCount: number;
readonly onPopupPanelOpenClose: (isOpening: boolean) => void;
readonly overflowDisplayActive: boolean;
readonly onItemExecuted: OnItemExecutedFunc;
readonly onKeyDown: (e: React.KeyboardEvent) => void;
}
/**
* Context used by Toolbar component to provide Direction to child components.
* @internal
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
export const ToolbarWithOverflowDirectionContext = React.createContext<ToolbarOverflowContextProps>({
expandsTo: Direction.Bottom,
direction: OrthogonalDirection.Horizontal,
overflowExpandsTo: Direction.Right,
overflowDirection: OrthogonalDirection.Vertical,
panelAlignment: ToolbarPanelAlignment.Start,
useDragInteraction: false,
toolbarOpacitySetting: ToolbarOpacitySetting.Proximity,
openPopupCount: 0,
onPopupPanelOpenClose: /* istanbul ignore next */ (_isOpening: boolean) => { },
overflowDisplayActive: false,
onItemExecuted: /* istanbul ignore next */ (_item: any) => void {},
onKeyDown: /* istanbul ignore next */ (_e: React.KeyboardEvent) => void {},
});
/** @internal */
export function CustomItem({ item, addGroupSeparator }: { item: CustomToolbarItem, addGroupSeparator: boolean }) {
const { useDragInteraction } = useToolbarWithOverflowDirectionContext();
const icon = React.useMemo(() => (item.icon &&
IconHelper.getIconReactNode(item.icon, item.internalData)) || /* istanbul ignore next */
<i className="icon icon-placeholder" />, [item.icon, item.internalData]);
const isDisabled = React.useMemo(() => ConditionalBooleanValue.getValue(item.isDisabled), [item.isDisabled]);
const title = React.useMemo(() => /* istanbul ignore next */ ConditionalStringValue.getValue(item.label) ?? item.id, [item.id, item.label]);
const badge = React.useMemo(() => BadgeUtilities.getComponentForBadgeType(item.badgeType), [item.badgeType]);
if (item.panelContentNode) {
return <PopupItem
key={item.id}
itemId={item.id}
icon={icon}
isDisabled={isDisabled}
title={title}
panel={item.panelContentNode}
hideIndicator={useDragInteraction}
badge={badge}
addGroupSeparator={addGroupSeparator}
keepContentsMounted={item.keepContentsLoaded}
/>;
}
// istanbul ignore else
if (item.buttonNode)
return <>{item.buttonNode}</>;
// istanbul ignore next
return null;
}
/** @internal */
export function GroupPopupItem({ item, addGroupSeparator }: { item: GroupButton, addGroupSeparator: boolean }) {
const { useDragInteraction } = useToolbarWithOverflowDirectionContext();
const title = ConditionalStringValue.getValue(item.label)!;
const badge = BadgeUtilities.getComponentForBadgeType(item.badgeType);
const panel = React.useMemo(() => <PopupItemsPanel groupItem={item} activateOnPointerUp={false} />, [item]);
if (useDragInteraction) {
return <PopupItemWithDrag
key={item.id}
itemId={item.id}
providerId={item.providerId}
itemPriority={item.itemPriority}
groupPriority={item.groupPriority}
icon={IconHelper.getIconReactNode(item.icon, item.internalData)}
isDisabled={ConditionalBooleanValue.getValue(item.isDisabled)}
title={title}
groupItem={item}
badge={badge}
addGroupSeparator={addGroupSeparator}
/>;
}
return <PopupItem
key={item.id}
itemId={item.id}
providerId={item.providerId}
itemPriority={item.itemPriority}
groupPriority={item.groupPriority}
icon={IconHelper.getIconReactNode(item.icon, item.internalData)}
isDisabled={ConditionalBooleanValue.getValue(item.isDisabled)}
title={title}
panel={panel}
badge={badge}
hideIndicator={useDragInteraction}
addGroupSeparator={addGroupSeparator}
/>;
}
/** @internal */
export function ActionItem({ item, addGroupSeparator }: { item: ActionButton, addGroupSeparator: boolean }) {
const title = ConditionalStringValue.getValue(item.label)!;
const badge = BadgeUtilities.getComponentForBadgeType(item.badgeType);
const { onItemExecuted } = useToolbarWithOverflowDirectionContext();
const onExecute = React.useCallback(() => {
item.execute();
onItemExecuted(item);
}, [item, onItemExecuted]);
return <ToolbarButtonItem
itemId={item.id}
providerId={item.providerId}
itemPriority={item.itemPriority}
groupPriority={item.groupPriority}
key={item.id}
isDisabled={ConditionalBooleanValue.getValue(item.isDisabled)}
title={title}
icon={IconHelper.getIconReactNode(item.icon, item.internalData)}
isActive={item.isActive}
onClick={onExecute}
badge={badge}
addGroupSeparator={addGroupSeparator}
/>;
}
/** @internal */
export function ToolbarItemComponent({ item, addGroupSeparator }: { item: ToolbarItem, addGroupSeparator: boolean }) {
if (ToolbarItemUtilities.isGroupButton(item)) {
return <GroupPopupItem item={item} addGroupSeparator={addGroupSeparator} />;
} else if (isCustomToolbarItem(item)) {
return <CustomItem item={item} addGroupSeparator={addGroupSeparator} />;
} else {
// istanbul ignore else
if (ToolbarItemUtilities.isActionButton(item)) {
return <ActionItem item={item} addGroupSeparator={addGroupSeparator} />;
}
}
// istanbul ignore next
return null;
}
/** @internal */
export function useToolbarWithOverflowDirectionContext() {
return React.useContext(ToolbarWithOverflowDirectionContext);
}
function OverflowItemsContainer(p: { children: React.ReactNode }) {
return <>{p.children}</>;
}
function getItemWrapperClass(child: React.ReactNode) {
// istanbul ignore else
if (React.isValidElement(child)) {
if (child.props && child.props.addGroupSeparator)
return "components-toolbar-button-add-gap-before";
}
return undefined;
}
/** Properties of [[ToolbarWithOverflow]] component.
* @public
*/
export interface ToolbarWithOverflowProps extends CommonProps, NoChildrenProps {
/** Describes to which direction the popup panels are expanded. Defaults to: [[Direction.Bottom]] */
expandsTo?: Direction;
/** Describes to which direction the overflow popup panels are expanded. Defaults to: [[Direction.Right]] */
overflowExpandsTo?: Direction;
/** definitions for items of the toolbar. i.e. [[CommonToolbarItem]]. Items are expected to be already sorted by group and item. */
items: CommonToolbarItem[];
/** Describes how expanded panels are aligned. Defaults to: [[ToolbarPanelAlignment.Start]] */
panelAlignment?: ToolbarPanelAlignment;
/** Use Drag Interaction to open popups with nest action buttons */
useDragInteraction?: boolean;
/** Determines whether to use mouse proximity to alter the opacity of the toolbar */
toolbarOpacitySetting?: ToolbarOpacitySetting;
/** Optional function to call on any item execution */
onItemExecuted?: OnItemExecutedFunc;
/** Optional function to call on any KeyDown events processed by toolbar */
onKeyDown?: (e: React.KeyboardEvent) => void;
}
/** Component that displays tool settings as a bar across the top of the content view.
* @public
*/
export function ToolbarWithOverflow(props: ToolbarWithOverflowProps) {
const expandsTo = props.expandsTo ? props.expandsTo : Direction.Bottom;
const useDragInteraction = !!props.useDragInteraction;
const panelAlignment = props.panelAlignment ? props.panelAlignment : ToolbarPanelAlignment.Start;
const useHeight = (expandsTo === Direction.Right || expandsTo === Direction.Left);
const [isOverflowPanelOpen, setIsOverflowPanelOpen] = React.useState(false);
const [popupPanelCount, setPopupPanelCount] = React.useState(0);
const overflowTitle = React.useRef(UiComponents.translate("toolbar.overflow"));
const isMounted = React.useRef(false);
React.useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
});
const handlePopupPanelOpenClose = React.useCallback((isOpening: boolean) => {
// use setTimeout to avoid warning about setting state in ToolbarWithOverflow from render method of PopupItem/PopupItemWithDrag
setTimeout(() => {
// istanbul ignore next
if (!isMounted.current)
return;
setPopupPanelCount((prev) => {
const nextCount = isOpening ? (prev + 1) : (prev - 1);
// eslint-disable-next-line no-console
// console.log(`new popup count = ${nextCount}`);
return nextCount < 0 ? /* istanbul ignore next */ 0 : nextCount;
});
});
}, []);
const ref = React.useRef<HTMLDivElement>(null);
const width = React.useRef<number | undefined>(undefined);
const availableNodes = React.useMemo<React.ReactNode>(() => {
return props.items.map((item, index) => {
let addGroupSeparator = false;
if (index > 0)
addGroupSeparator = item.groupPriority !== props.items[index - 1].groupPriority;
return (
<ToolbarItemComponent
key={item.id}
item={item}
addGroupSeparator={!!addGroupSeparator}
/>
);
});
}, [props.items]);
/* overflowItemKeys - keys of items to show in overflow panel
* handleContainerResize - handler called when container <div> is resized.
* handleOverflowResize - handler called when determining size of overflow indicator/button.
* handleEntryResize - handler called when determining size of each item/button. */
const [overflowItemKeys, handleContainerResize, handleOverflowResize, handleEntryResize] = useOverflow(availableNodes, panelAlignment === ToolbarPanelAlignment.End);
// handler called by ResizeObserver
const handleResize = React.useCallback((w: number) => {
width.current = w;
width.current !== undefined && handleContainerResize(width.current);
}, [handleContainerResize]);
const resizeObserverRef = useResizeObserverSingleDimension(handleResize, useHeight);
const handleClick = React.useCallback(() => {
setIsOverflowPanelOpen((prev) => !prev);
}, []);
// istanbul ignore next - NEEDSWORK add complete tests
const handleClose = React.useCallback(() => {
setIsOverflowPanelOpen(false);
}, []);
const refs = useRefs(ref, resizeObserverRef);
const availableItems = React.Children.toArray(availableNodes);
const displayedItems = availableItems.reduce<Array<[string, React.ReactNode]>>((acc, child, index) => {
const key = getChildKey(child, index);
if (!overflowItemKeys || overflowItemKeys.indexOf(key) < 0) {
acc.push([key, child]);
}
return acc;
}, []);
// eslint-disable-next-line react-hooks/exhaustive-deps
const overflowPanelItems = overflowItemKeys ? availableItems.reduce<Array<[string, React.ReactNode]>>((acc, child, index) => {
const key = getChildKey(child, index);
if (overflowItemKeys.indexOf(key) >= 0) {
acc.push([key, child]);
}
return acc;
}, []) : [];
const direction = getToolbarDirection(expandsTo);
const overflowExpandsTo = undefined !== props.overflowExpandsTo ? props.overflowExpandsTo : Direction.Right;
const addOverflowButton = React.useCallback((atStart: boolean) => {
const overflowItems = !!atStart ? overflowPanelItems.reverse() : overflowPanelItems;
return (<ToolbarItemContext.Provider
value={{
hasOverflow: false,
useHeight,
onResize: handleOverflowResize,
}}
>
<ToolbarOverflowButton
expandsTo={expandsTo}
onClick={handleClick}
onClose={handleClose}
open={overflowItems.length > 0 && isOverflowPanelOpen}
panelNode={
<ToolbarOverflowPanel>
<OverflowItemsContainer>
{overflowItems.map(([key, child]) => {
return (
<ToolbarItemContext.Provider
key={key}
value={{
hasOverflow: true,
useHeight,
onResize: () => { },
}}
>
{<ItemWrapper className={getItemWrapperClass(child)}>{child}</ItemWrapper>}
</ToolbarItemContext.Provider>
);
})}
</OverflowItemsContainer>
</ToolbarOverflowPanel>
}
title={overflowTitle.current}
/>
</ToolbarItemContext.Provider>);
}, [handleClick, handleClose, handleOverflowResize, isOverflowPanelOpen, expandsTo, overflowPanelItems, useHeight]);
const className = classnames(
"components-toolbar-overflow-sizer",
OrthogonalDirectionHelpers.getCssClassName(direction),
props.className);
const showOverflowAtStart = (direction === OrthogonalDirection.Horizontal) && (panelAlignment === ToolbarPanelAlignment.End);
/* The ItemWrapper is used to wrap the <Item> <ExpandableItem> with a <div> that specifies a ref that the sizing logic uses to determine the
size of the item. */
return (
<ToolbarWithOverflowDirectionContext.Provider value={
{
expandsTo, direction, overflowExpandsTo, panelAlignment, useDragInteraction,
toolbarOpacitySetting: undefined !== props.toolbarOpacitySetting ? props.toolbarOpacitySetting : ToolbarOpacitySetting.Proximity,
overflowDirection: direction === OrthogonalDirection.Horizontal ? OrthogonalDirection.Vertical : OrthogonalDirection.Horizontal,
openPopupCount: popupPanelCount,
onPopupPanelOpenClose: handlePopupPanelOpenClose,
overflowDisplayActive: overflowPanelItems.length > 0 && isOverflowPanelOpen,
onItemExecuted: props.onItemExecuted ? props.onItemExecuted : () => { },
onKeyDown: props.onKeyDown ? props.onKeyDown : /* istanbul ignore next */ (_e: React.KeyboardEvent) => { },
}
}>
{(availableItems.length > 0) &&
<div
className={className}
ref={refs}
style={props.style}
onKeyDown={props.onKeyDown}
role="presentation"
>
<ToolbarItems
className="components-items"
direction={direction}
>
{(!overflowItemKeys || overflowItemKeys.length > 0) && showOverflowAtStart && addOverflowButton(true)}
{displayedItems.map(([key, child]) => {
const onEntryResize = handleEntryResize(key);
return (
<ToolbarItemContext.Provider
key={key}
value={{
hasOverflow: false,
useHeight,
onResize: onEntryResize,
}}
>
{<ItemWrapper className={getItemWrapperClass(child)}>{child}</ItemWrapper>}
</ToolbarItemContext.Provider>
);
})}
{(!overflowItemKeys || overflowItemKeys.length > 0) && !showOverflowAtStart && addOverflowButton(false)}
</ToolbarItems>
</div>
}
</ToolbarWithOverflowDirectionContext.Provider >
);
}
/** Returns key of a child. Must be used along with React.Children.toArray to preserve the semantics of availableItems.
* @internal
*/
function getChildKey(child: React.ReactNode, index: number) {
// istanbul ignore else
if (React.isValidElement(child) && child.key !== null) {
return child.key.toString();
}
// istanbul ignore next
return index.toString();
}
/** Returns a subset of toolbar item entry keys that exceed given width and should be overflowItemKeys.
* @internal
*/
function determineOverflowItems(size: number, entries: ReadonlyArray<readonly [string, number]>, overflowButtonSize: number, overflowButtonAtStart: boolean): string[] {
let toolbarSize = 0;
const buttonPadding = 2;
if (overflowButtonAtStart && entries.length > 0) {
let i = entries.length - 1;
for (; i >= 0; i--) {
const w = entries[i][1] + buttonPadding;
const newSettingsWidth = toolbarSize + w;
if (newSettingsWidth > size) {
toolbarSize += (overflowButtonSize + buttonPadding);
break;
}
toolbarSize = newSettingsWidth;
}
if (i >= 0) {
let j = i + 1;
for (; j < entries.length; j++) {
if (toolbarSize <= size)
break;
const w = entries[j][1] + buttonPadding;
toolbarSize -= w;
}
return entries.slice(0, j).map((e) => e[0]);
} else {
return [];
}
} else {
let i = 0;
for (; i < entries.length; i++) {
const w = entries[i][1] + buttonPadding;
const newSettingsWidth = toolbarSize + w;
if (newSettingsWidth > size) {
toolbarSize += (overflowButtonSize + buttonPadding);
break;
}
toolbarSize = newSettingsWidth;
}
let j = i;
for (; j > 0; j--) {
if (toolbarSize <= size)
break;
const w = entries[j][1] + buttonPadding;
toolbarSize -= w;
}
return entries.slice(j).map((e) => e[0]);
}
}
/** Hook that returns a list of overflowItemKeys availableItems.
* @internal
*/
function useOverflow(availableItems: React.ReactNode, overflowButtonAtStart: boolean): [
ReadonlyArray<string> | undefined,
(size: number) => void,
(size: number) => void,
(key: string) => (size: number) => void,
] {
const [overflowItemKeys, setOverflown] = React.useState<ReadonlyArray<string>>();
const itemSizes = React.useRef(new Map<string, number | undefined>());
const size = React.useRef<number | undefined>(undefined);
const overflowButtonSize = React.useRef<number | undefined>(undefined);
const calculateOverflow = React.useCallback(() => {
const sizes = verifiedMapEntries(itemSizes.current);
if (size.current === undefined ||
sizes === undefined ||
overflowButtonSize.current === undefined) {
setOverflown(undefined);
return;
}
// Calculate overflow.
const newOverflown = determineOverflowItems(size.current, [...sizes.entries()], overflowButtonSize.current, overflowButtonAtStart);
setOverflown((prevOverflown) => {
return eql(prevOverflown, newOverflown) ? prevOverflown : newOverflown;
});
}, [overflowButtonAtStart]);
React.useLayoutEffect(() => {
const newEntryWidths = new Map<string, number | undefined>();
const array = React.Children.toArray(availableItems);
for (let i = 0; i < array.length; i++) {
const child = array[i];
const key = getChildKey(child, i);
const lastW = itemSizes.current.get(key);
newEntryWidths.set(key, lastW);
}
itemSizes.current = newEntryWidths;
calculateOverflow();
}, [availableItems, calculateOverflow]);
const handleContainerResize = React.useCallback((w: number) => {
const calculate = size.current !== w;
size.current = w;
calculate && calculateOverflow();
}, [calculateOverflow]);
const handleOverflowResize = React.useCallback((w: number) => {
const calculate = overflowButtonSize.current !== w;
overflowButtonSize.current = w;
calculate && calculateOverflow();
}, [calculateOverflow]);
const handleEntryResize = React.useCallback((key: string) => (w: number) => {
const oldW = itemSizes.current.get(key);
if (oldW !== w) {
itemSizes.current.set(key, w);
calculateOverflow();
}
}, [calculateOverflow]);
return [overflowItemKeys, handleContainerResize, handleOverflowResize, handleEntryResize];
}
/** Interface toolbars use to define context for its items.
* @internal
*/
export interface ToolbarItemContextArgs {
readonly hasOverflow: boolean;
readonly useHeight: boolean;
readonly onResize: (w: number) => void;
}
/** Interface toolbars use to define context for its items.
* @internal
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
export const ToolbarItemContext = React.createContext<ToolbarItemContextArgs>(null!);
/** @internal */
export function useToolItemEntryContext() {
return React.useContext(ToolbarItemContext);
}
function verifiedMapEntries<T>(map: Map<string, T | undefined>) {
for (const [, val] of map) {
// istanbul ignore next during unit testing
if (val === undefined)
return undefined;
}
return map as Map<string, T>;
}
function eql(prev: readonly string[] | undefined, value: readonly string[]) {
if (!prev)
return false;
// istanbul ignore next
if (prev.length !== value.length)
return false;
for (let i = 0; i < prev.length; i++) {
const p = prev[i];
const v = value[i];
// istanbul ignore next
if (p !== v)
return false;
}
return true;
} | the_stack |
import * as React from 'react'
import {
Link
} from '@react-navigation/native'
import { withSafeAreaInsets } from 'react-native-safe-area-context'
import {
View,
TouchableWithoutFeedback,
Animated,
StyleSheet,
Platform,
Dimensions,
LayoutChangeEvent,
Keyboard
} from 'react-native'
import { getTabVisible, getTabConfig, getTabItemConfig, getDefalutTabItem, isUrl } from '../utils/index'
import { getInitSafeAreaInsets } from './tabBarUtils'
import TabBarItem, { TabBarOptions, TabOptions } from './TabBarItem'
interface TabBarProps extends TabBarOptions {
state: Record<string, any>,
navigation: any,
descriptors: Record<string, any>,
userOptions: TabOptions
}
interface TabBarState {
visible: Animated.Value,
isKeyboardShown: boolean,
tabVisible: boolean,
layout: {
height: number,
width: number,
},
insets: Record<string, number>
}
interface TabBarStyle {
color?: string,
selectedColor?: string,
backgroundColor?: string,
borderStyle?: string
}
const DEFAULT_TABBAR_HEIGHT = 55
const COMPACT_TABBAR_HEIGHT = 32
// const DEFAULT_MAX_TAB_ITEM_WIDTH = 125;
const useNativeDriver = Platform.OS !== 'web'
const styles = StyleSheet.create({
tabBar: {
left: 0,
right: 0,
bottom: 0,
borderTopWidth: StyleSheet.hairlineWidth,
elevation: 8
},
tab: {
flex: 1,
alignItems: 'center'
},
tabPortrait: {
justifyContent: 'flex-end',
flexDirection: 'column'
},
tabLandscape: {
justifyContent: 'center',
flexDirection: 'row'
}
})
export class TabBar extends React.PureComponent<TabBarProps, TabBarState> {
constructor (props: TabBarProps) {
super(props)
const { height = 0, width = 0 } = Dimensions.get('window')
const { safeAreaInsets, userOptions = {} } = this.props
const { tabBarVisible = true } = userOptions
const tabVisible = tabBarVisible === false ? false : getTabVisible()
this.state = {
visible: new Animated.Value(tabVisible ? 1 : 0),
tabVisible: tabVisible,
isKeyboardShown: false,
layout: {
width,
height
},
insets: safeAreaInsets || getInitSafeAreaInsets()
}
}
componentDidMount () {
const { keyboardHidesTabBar = false } = this.props
if (keyboardHidesTabBar) {
if (Platform.OS === 'ios') {
Keyboard.addListener('keyboardWillShow', () => this.handleKeyboardShow())
Keyboard.addListener('keyboardWillHide', () => this.handleKeyboardHide())
} else {
Keyboard.addListener('keyboardDidShow', () => this.handleKeyboardShow())
Keyboard.addListener('keyboardDidHide', () => this.handleKeyboardHide())
}
}
}
componentWillUnmount () {
const { keyboardHidesTabBar = false } = this.props
if (keyboardHidesTabBar) {
if (Platform.OS === 'ios') {
Keyboard.removeListener('keyboardWillShow', () => this.handleKeyboardShow())
Keyboard.removeListener('keyboardWillHide', () => this.handleKeyboardHide())
} else {
Keyboard.removeListener('keyboardDidShow', () => this.handleKeyboardShow())
Keyboard.removeListener('keyboardDidHide', () => this.handleKeyboardHide())
}
}
}
UNSAFE_componentWillReceiveProps (): void {
const curVisible = getTabVisible()
const { tabVisible } = this.state
if (curVisible !== tabVisible) {
this.setState({
tabVisible: curVisible
})
this.setTabBarHidden(!curVisible)
}
}
handleKeyboardShow () {
this.setState({
isKeyboardShown: true,
tabVisible: false
})
this.setTabBarHidden(true)
}
handleKeyboardHide () {
this.setState({
isKeyboardShown: false,
tabVisible: getTabVisible()
})
this.setTabBarHidden(false)
}
setTabBarHidden (isHidden: boolean) {
if (!getTabConfig('needAnimate')) return
const { visible } = this.state
if (isHidden) {
this.setState({
tabVisible: false
})
Animated.timing(visible, {
toValue: 0,
duration: 200,
useNativeDriver
}).start()
} else {
Animated.timing(visible, {
toValue: 1,
duration: 250,
useNativeDriver
}).start(({ finished }) => {
if (finished) {
this.setState({
tabVisible: true
})
}
})
}
}
isLandscape (): boolean {
const { height = 0, width = 0 } = Dimensions.get('window')
return width > height
}
getDefaultTabBarHeight (): number {
if (Platform.OS === 'ios' &&
!Platform.isPad && this.isLandscape()) {
return COMPACT_TABBAR_HEIGHT
}
return DEFAULT_TABBAR_HEIGHT
}
// 只有最简单的格式
buildLink (name: string, params: Record<string, any>): string {
const keys = Object.keys(params).sort()
let str = ''
keys.forEach((v) => {
str += (v + '=' + encodeURIComponent(params[v]) + '&')
})
str = str.slice(0, str.length - 1)
return str ? `${name}?${str}` : `${name}`
}
handleLayout (e: LayoutChangeEvent): void {
const { layout } = this.state
const { height, width } = e.nativeEvent.layout
if (layout.height !== height && layout.width !== width) {
this.setState({
layout: {
width,
height
}
})
}
}
getTabBarStyle (): Record<string, string> {
const { activeTintColor, inactiveTintColor, style = {} } = this.props
const tabStyle = getTabConfig('tabStyle') as TabBarStyle
const { color = '', selectedColor = '', backgroundColor = '', borderStyle = '' } = tabStyle
const defaultBackground: any = style?.backgroundColor || 'rgb(255, 255, 255)'
const defalutBorderTopColor: any = style?.borderTopColor || 'rgb(216, 216, 216)'
return {
backgroundColor: backgroundColor || defaultBackground,
borderTopColor: borderStyle || defalutBorderTopColor,
color: color || inactiveTintColor,
selectedColor: selectedColor || activeTintColor
}
}
getTabIconSource (index: number, focused: boolean) {
const item: any = getDefalutTabItem(index)
const iconPath = getTabItemConfig(index, 'iconPath') ?? item?.iconPath
const selectedIconPath = getTabItemConfig(index, 'selectedIconPath') ?? item?.selectedIconPath
const path = focused ? selectedIconPath : iconPath
return isUrl(path) ? { uri: path } : { uri: path }
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
renderContent () {
const { state, descriptors, navigation } = this.props
const horizontal = true
const tabSelfStyle = this.getTabBarStyle()
return <View style={{ flexDirection: 'row', flex: 1 }} onLayout={() => this.handleLayout}>
{state.routes.map((route, index) => {
const focused = index === state.index
const { options } = descriptors[route.key]
const tabLabel = getTabItemConfig(index, 'tabBarLabel')
const label = tabLabel || (options.tabBarLabel !== undefined
? options.tabBarLabel
: options.title !== undefined
? options.title
: route.name)
const accessibilityLabel =
options.tabBarAccessibilityLabel !== undefined
? options.tabBarAccessibilityLabel
: typeof label === 'string'
? `${label}, tab, ${index + 1} of ${state.routes.length}`
: undefined
const onPress = () => {
const event = navigation.emit({
type: 'tabPress',
target: route.key
})
if (!focused && !event.defaultPrevented) {
navigation.navigate(route.name)
}
}
const onLongPress = () => {
navigation.emit({
type: 'tabLongPress',
target: route.key
})
}
const badge = getTabItemConfig(index, 'tabBarBadge')
const showRedDot = getTabItemConfig(index, 'showRedDot') || false
const labelColor = focused ? tabSelfStyle.selectedColor : tabSelfStyle.color
const source = this.getTabIconSource(index, focused)
if (Platform.OS === 'web') {
const linkto = this.buildLink(route.name, route.params)
return (
<Link
to={linkto}
style={[]}
onPress={(e: any) => {
if (
!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) &&
(e.button == null || e.button === 0)
) {
e.preventDefault()
onPress()
}
}}
>
<TabBarItem
showRedDot={showRedDot}
badge={badge}
label={label}
horizontal={horizontal}
labelColor={labelColor}
iconSource={source}
size={25}
{...this.props}
/>
</Link>
)
} else {
return (
<TouchableWithoutFeedback
key={options.tabBarTestID}
accessibilityRole="button"
accessibilityState={focused ? { selected: true } : {}}
accessibilityLabel={accessibilityLabel}
testID={options.tabBarTestID}
onPress={onPress}
onLongPress={onLongPress}
>
<View
style={[styles.tab, horizontal ? styles.tabLandscape : styles.tabPortrait]}
>
<TabBarItem
label={label}
badge={badge}
showRedDot={showRedDot}
horizontal
labelColor={labelColor}
iconSource={source}
size={25}
{...this.props}
/>
</View>
</TouchableWithoutFeedback>
)
}
})}
</View>
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
render () {
const { insets, visible, layout, tabVisible, isKeyboardShown } = this.state
const paddingBottom = Math.max(
insets?.bottom - Platform.select({ ios: 4, default: 0 }), 5)
const { style } = this.props
const tabBarStyle = this.getTabBarStyle()
const needAnimate = getTabConfig('needAnimate')
const showTabBar = tabVisible !== false && !isKeyboardShown
if (!needAnimate) {
// eslint-disable-next-line multiline-ternary
return (!showTabBar ? null
: (
<View
style={[
styles.tabBar,
{
height: this.getDefaultTabBarHeight() + paddingBottom,
paddingBottom,
paddingHorizontal: Math.max(insets.left, insets.right)
},
style,
{
backgroundColor: tabBarStyle.backgroundColor,
borderTopColor: tabBarStyle.borderTopColor
}
]}
>
{this.renderContent()}
</View>)
)
} else {
return (
<Animated.View
style={[
styles.tabBar,
showTabBar ? {
height: this.getDefaultTabBarHeight() + paddingBottom,
paddingBottom,
paddingHorizontal: Math.max(insets.left, insets.right)
} : {},
{
transform: [
{
translateY: visible.interpolate({
inputRange: [0, 1],
outputRange: [
layout.height + paddingBottom + StyleSheet.hairlineWidth,
0
]
})
}
],
position: showTabBar ? 'absolute' : (null as any)
},
style,
{
backgroundColor: tabBarStyle.backgroundColor,
borderTopColor: tabBarStyle.borderTopColor
}
]}
pointerEvents={!tabVisible ? 'none' : 'auto'}
>
{this.renderContent()}
</Animated.View>
)
}
}
}
export default withSafeAreaInsets(TabBar) | the_stack |
import { IEngine, Report, Rule, RuleDetails, RuleResult, eRuleConfidence, RuleContext, NlsMap, HelpMap, RuleContextHierarchy } from "../api/IEngine";
import { DOMWalker } from "../dom/DOMWalker";
import { Context, PartInfo, AttrInfo } from "./Context";
import { Config } from "../config/Config";
import { IMapResult, IMapper } from "../api/IMapper";
import { DOMMapper } from "../dom/DOMMapper";
import { DOMUtil } from "../dom/DOMUtil";
import { ARIAMapper } from "../..";
export interface CacheDocument extends Document {
aceCache: { [key: string]: any }
}
export interface CacheElement extends Element {
aceCache: { [key: string]: any }
}
class WrappedRule {
ns: string;
idx?: number;
constructor (public rule: Rule, public parsedInfo : Context) {
this.ns = this.parsedInfo.contextInfo[this.parsedInfo.contextInfo.length-1].namespace;
Config.DEBUG && console.log("Added Rule:", rule.id, JSON.stringify(this.parsedInfo));
}
/**
* This function is responsible converting the node into a snippet which can be added to report.
*
* Note: This function will take the node and extract the node name and the attributes and build the snippet based on this.
*
* TODO: Future, maybe we can extract more then just single line, add more info or even add closing tags etc...
*
* @param {HTMLElement} node - The html element to convert into element snippet with node name and attributes only.
*
* @return {String} nodeSnippet - return the element snippet of the element that was provided which only contains,
* nodename and attributes. i.e. <table id=\"layout_table1\" role=\"presentation\">
*
* @memberOf this
*/
static convertNodeToSnippet(node : Element) {
// Variable Decleration
var nodeSnippet = '';
// Extract the node name and add it to the node snippet
nodeSnippet += '<' + node.nodeName.toLowerCase();
// Extract all the node attributes as an array
var nodeAttributes = node.attributes;
// In the case there are attributes on this node
if (nodeAttributes !== null && typeof nodeAttributes !== 'undefined') {
// Loop over all theses attributes and add the name and value to the nodeSnippet which will be returned
for (var i = nodeAttributes.length - 1; i >= 0; i--) {
if (nodeAttributes[i].name === "data-namewalk") continue;
// Add the attribute name and value.
nodeSnippet += ' ' + nodeAttributes[i].name + '="' + nodeAttributes[i].value + '"';
}
}
// Close the node
nodeSnippet += '>';
// Return the node snippet
return nodeSnippet;
}
run(engine: Engine, context: RuleContext, options?: {}, contextHierarchies?: RuleContextHierarchy) : RuleDetails[] {
const startTime = new Date().getTime();
let results: RuleResult | RuleResult[];
try {
results = this.rule.run(context, options, contextHierarchies);
} catch (e) {
const err: Error = e;
console.error("RULE EXCEPTION:",this.rule.id, context.dom.rolePath, err.stack);
throw e;
}
const endTime = new Date().getTime();
if (!results) results = [];
if (!(results instanceof Array)) {
results = [results];
}
let retVal : RuleDetails[] = [];
for (const result of results) {
const message = engine.getMessage(this.rule.id, result.reasonId, result.messageArgs);
const path = {};
for (const ns in context) {
path[ns] = context[ns].rolePath
}
const ruleId = this.rule.id.replace(/^(.*)\$\$\d+$/, "$1");
retVal.push({
ruleId: ruleId,
value: result.value,
node: context["dom"].node,
path: path,
ruleTime: endTime-startTime,
reasonId: result.reasonId,
message: message,
messageArgs: result.messageArgs,
apiArgs: result.apiArgs,
bounds: context["dom"].bounds,
snippet: WrappedRule.convertNodeToSnippet(context["dom"].node as Element)
})
}
return retVal;
}
}
export class Engine implements IEngine {
mappers : { [namespace: string] : IMapper } = {};
ruleMap : { [id: string]: Rule } = {};
wrappedRuleMap : { [id: string]: WrappedRule } = {};
nlsMap : NlsMap = {}
helpMap : HelpMap = {}
private inclRules: {
[nsRole: string]: WrappedRule[]
} = {}
private exclRules: {
[nsRole: string]: WrappedRule[]
} = {}
constructor() {
// Need a DOM Mapper as a minimum
this.addMapper(new DOMMapper());
}
private static clearCaches(cacheRoot : Node) : void {
delete (cacheRoot.ownerDocument as CacheDocument).aceCache;
let nw = new DOMWalker(cacheRoot);
do {
delete (nw.node as CacheElement).aceCache;
nw.node.ownerDocument && delete (nw.node.ownerDocument as CacheDocument).aceCache;
} while (nw.nextNode());
}
run(root: Document | Node, options?: {}): Promise<Report> {
if (root === null) {
return Promise.reject("null document");
}
if (root.nodeType === 9 /* Node.DOCUMENT_NODE */) {
root = (root as Document).documentElement;
}
root.ownerDocument && ((root.ownerDocument as any).PT_CHECK_HIDDEN_CONTENT = false);
Engine.clearCaches(root);
const walker = new DOMWalker(root);
const retVal : Report = {
results: [],
numExecuted: 0,
ruleTime: 0,
totalTime: 0
}
const start = new Date().getTime();
// Reset the role mappers
for (const namespace in this.mappers) {
this.mappers[namespace].reset(root);
}
// Initialize the context detector
do {
// Get the context information from the rule mappers
const contextHierarchies : RuleContextHierarchy = {}
for (const namespace in this.mappers) {
if (!walker.bEndTag) {
contextHierarchies[namespace] = this.mappers[namespace].openScope(walker.node);
// if (namespace === "dom" && walker.node.nodeType === 1 /* Node.ELEMENT_NODE */) {
// const elem = walker.node as Element;
// let id;
// if (elem.hasAttribute("id") && (id = elem.getAttribute("id").trim()).length > 0) {
// if (root.ownerDocument.getElementById(id) === elem) {
// contextHierarchies["dom"][contextHierarchies["dom"].length-1].rolePath = "//*[@id='"+id+"']";
// }
// }
// }
} else {
contextHierarchies[namespace] = this.mappers[namespace].closeScope(walker.node);
}
}
if (walker.node.nodeType !== 11
&& (DOMUtil.isNodeVisible(walker.node)
|| walker.node.nodeName.toLowerCase() === "style"
|| walker.node.nodeName.toLowerCase() === "datalist"
|| walker.node.nodeName.toLowerCase() === "param"
|| !DOMUtil.getAncestor(walker.node, ["body"])
)
) {
let context : RuleContext = {};
for (const ns in contextHierarchies) {
const nsHier = contextHierarchies[ns];
const lastHier = nsHier[nsHier.length-1];
context[ns] = lastHier;
}
let matchingRules = this.getMatchingRules(contextHierarchies);
let depMatch = {}
for (const matchingRule of matchingRules) {
let fulfillsDependencies = true;
for (const dep of matchingRule.rule.dependencies || []) {
if (!depMatch[dep]) fulfillsDependencies = false;
}
if (fulfillsDependencies) {
let results : RuleDetails[] = [];
try {
results = matchingRule.run(this, context, options, contextHierarchies);
} catch (err) {
// Wrapper shows error in console. Skip this rule as N/A
// We don't want to kill the engine
}
// If out of scope, it fulfills the dependency
if (results.length === 0) {
depMatch[matchingRule.rule.id] = true;
}
for (const result of results) {
retVal.results.push(result);
retVal.ruleTime += result.ruleTime;
retVal.numExecuted++;
if (result.value[1] === eRuleConfidence.PASS) {
depMatch[result.ruleId] = true;
}
}
}
}
}
} while (walker.nextNode());
retVal.totalTime = new Date().getTime()-start;
return Promise.resolve(retVal);
}
enableRules(ruleIds: string[]) {
for (const ruleId in this.ruleMap) {
this.ruleMap[ruleId].enabled = false;
}
for (const ruleId of ruleIds || []) {
if (!(ruleId in this.ruleMap)) {
console.warn("WARNING: Rule Id",ruleId,"could not be enabled.");
} else {
this.ruleMap[ruleId].enabled = true;
}
}
}
getRule(ruleId: string): Rule {
return this.ruleMap[ruleId];
}
getRulesIds() : string[] {
let retVal = [];
for (const ruleId in this.ruleMap) {
retVal.push(ruleId);
}
return retVal;
}
addRules(rules: Rule[]) {
for (const rule of rules) {
this.addRule(rule);
}
}
addRule(rule: Rule) {
let ctxs :Context[] = Context.parse(rule.context);
let idx = 0;
const ruleId = rule.id;
if (ruleId in this.ruleMap) {
console.log("WARNING: Rule",ruleId,"already added to engine. Ignoring...");
return;
}
this.ruleMap[ruleId] = rule;
for (const ctx of ctxs) {
let wrapId = ruleId;
if (idx >= 1) {
wrapId = ruleId+"$$"+idx;
}
++idx;
let wrappedRule = new WrappedRule(rule,ctx);
this.wrappedRuleMap[wrapId] = wrappedRule;
let parts = wrappedRule.parsedInfo.contextInfo;
let lastPart = parts[parts.length-1];
let triggerRole = lastPart.namespace+":"+lastPart.role;
if (lastPart.inclusive) {
this.inclRules[triggerRole] = this.inclRules[triggerRole] || [];
this.inclRules[triggerRole].push(wrappedRule);
} else {
this.exclRules[triggerRole] = this.exclRules[triggerRole] || [];
this.exclRules[triggerRole].push(wrappedRule);
}
}
}
addNlsMap(map: NlsMap) {
for (const key in map) {
this.nlsMap[key] = map[key];
}
}
addHelpMap(map: HelpMap) {
for (const key in map) {
this.helpMap[key] = map[key];
}
}
getMessage(ruleId: string, ruleIdx: number | string, msgArgs?: string[]): string {
let splitter = ruleId.indexOf("$$");
if (splitter >= 0) {
ruleId = ruleId.substring(0,splitter);
}
if (!(ruleId in this.nlsMap)) return ruleId;
let messageTemplate = this.nlsMap[ruleId][ruleIdx || 0];
if (!messageTemplate) return ruleId+"_"+ruleIdx;
return messageTemplate.replace(/\{(\d+)\}/g,
(matchedStr, matchedNum, matchedIndex) => msgArgs[matchedNum]
);
}
getHelp(ruleId: string, ruleIdx: number | string): string {
let splitter = ruleId.indexOf("$$");
if (splitter >= 0) {
ruleId = ruleId.substring(0,splitter);
}
if (!(ruleId in this.helpMap)) return ruleId;
ruleIdx = ruleIdx || 0;
let helpStr = null;
if (ruleIdx in this.helpMap[ruleId]) {
helpStr = this.helpMap[ruleId][ruleIdx || 0];
} else {
helpStr = this.helpMap[ruleId][0];
}
if (!helpStr) return ruleId+"_"+ruleIdx;
return helpStr;
}
addMapper(mapper: IMapper) {
this.mappers[mapper.getNamespace()] = mapper;
}
private static match(ruleParts: PartInfo[],
contextHier: RuleContextHierarchy) : boolean
{
let partIdx = ruleParts.length-1;
let hierIdx = contextHier["dom"].length-1;
// First check the end of the hierarchy
if (!ruleParts[partIdx].matches(contextHier, hierIdx)) {
return false;
} else {
--partIdx;
--hierIdx;
}
while (hierIdx >= 0 && partIdx >= 0) {
const part = ruleParts[partIdx];
const matchesPart = ruleParts[partIdx].matches(contextHier, hierIdx);
if (part.connector === ">") {
if (!matchesPart) {
// Direct parent check and doesn't match
return false;
} else {
// Direct parent check and does match
--partIdx;
--hierIdx;
}
} else if (part.connector === " ") {
if (part.inclusive) {
// inclusive ancestor match
if (matchesPart) {
--partIdx;
}
// If doesn't match, just move up the role hierarchy
--hierIdx;
} else if (!matchesPart) {
// exclusive ancestor match and current matches
return false;
} else {
// exclusive ancestor match and current doesn't match - check for other ancestors
let parentMatch = false;
for (let searchIdx = hierIdx-1; !parentMatch && searchIdx >= 0; --searchIdx) {
parentMatch = !ruleParts[partIdx].matches(contextHier, searchIdx);
}
if (parentMatch) return false;
else --partIdx;
}
} else {
throw new Error("Context connector "+part.connector+" is not supported");
}
}
return partIdx === -1;
}
private getMatchingRules(ctxHier : RuleContextHierarchy) : WrappedRule[] {
let dupeCheck = {};
let matches : WrappedRule[] = [];
function addMatches(rules: WrappedRule[]) {
for (const rule of rules) {
if (rule.rule.enabled && Engine.match(rule.parsedInfo.contextInfo, ctxHier)) {
if (!(rule.rule.id in dupeCheck)) {
matches.push(rule);
dupeCheck[rule.rule.id] = true;
}
}
}
}
for (const ns in ctxHier) {
let role = ns+":"+ctxHier[ns][ctxHier[ns].length-1].role;
if (role in this.inclRules) {
addMatches(this.inclRules[role]);
}
for (const xRole in this.exclRules) {
if (xRole !== role) {
addMatches(this.exclRules[xRole]);
}
}
if (role !== ns+":none") {
if (role.startsWith(ns+":/")) {
if (ns+":/*" in this.inclRules) {
addMatches(this.inclRules[ns+":/*"])
}
} else {
if (ns+":*" in this.inclRules) {
addMatches(this.inclRules[ns+":*"])
}
}
}
}
// Sort for dependencies
for (let idx=0; idx < matches.length; ++idx) {
matches[idx].idx = idx;
}
matches.sort((a,b) => {
// a before b: -1
// a after b: 1
// equiv: 0
const ruleA : Rule = a.rule;
const ruleB : Rule = b.rule;
if (ruleA.dependencies && !ruleB.dependencies) {
return 1;
} else if (!ruleA.dependencies && ruleB.dependencies) {
return -1;
} else if (ruleA.dependencies && ruleB.dependencies) {
if (ruleA.dependencies.includes(ruleB.id)) {
return 1;
} else if (ruleB.dependencies.includes(ruleA.id)) {
return -1;
}
}
return a.idx-b.idx;
})
return matches;
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Allows creation and management of a Google Cloud Platform project.
*
* Projects created with this resource must be associated with an Organization.
* See the [Organization documentation](https://cloud.google.com/resource-manager/docs/quickstarts) for more details.
*
* The user or service account that is running this provider when creating a `gcp.organizations.Project`
* resource must have `roles/resourcemanager.projectCreator` on the specified organization. See the
* [Access Control for Organizations Using IAM](https://cloud.google.com/resource-manager/docs/access-control-org)
* doc for more information.
*
* > This resource reads the specified billing account on every provider apply and plan operation so you must have permissions on the specified billing account.
*
* To get more information about projects, see:
*
* * [API documentation](https://cloud.google.com/resource-manager/reference/rest/v1/projects)
* * How-to Guides
* * [Creating and managing projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects)
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const myProject = new gcp.organizations.Project("my_project", {
* orgId: "1234567",
* projectId: "your-project-id",
* });
* ```
*
* To create a project under a specific folder
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const department1 = new gcp.organizations.Folder("department1", {
* displayName: "Department 1",
* parent: "organizations/1234567",
* });
* const myProject_in_a_folder = new gcp.organizations.Project("myProject-in-a-folder", {
* projectId: "your-project-id",
* folderId: department1.name,
* });
* ```
*
* ## Import
*
* Projects can be imported using the `project_id`, e.g.
*
* ```sh
* $ pulumi import gcp:organizations/project:Project my_project your-project-id
* ```
*/
export class Project extends pulumi.CustomResource {
/**
* Get an existing Project 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?: ProjectState, opts?: pulumi.CustomResourceOptions): Project {
return new Project(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:organizations/project:Project';
/**
* Returns true if the given object is an instance of Project. 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 Project {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Project.__pulumiType;
}
/**
* Create the 'default' network automatically. Default `true`.
* If set to `false`, the default network will be deleted. Note that, for quota purposes, you
* will still need to have 1 network slot available to create the project successfully, even if
* you set `autoCreateNetwork` to `false`, since the network will exist momentarily.
*/
public readonly autoCreateNetwork!: pulumi.Output<boolean | undefined>;
/**
* The alphanumeric ID of the billing account this project
* belongs to. The user or service account performing this operation with the provider
* must have at mininum Billing Account User privileges (`roles/billing.user`) on the billing account.
* See [Google Cloud Billing API Access Control](https://cloud.google.com/billing/docs/how-to/billing-access)
* for more details.
*/
public readonly billingAccount!: pulumi.Output<string | undefined>;
/**
* The numeric ID of the folder this project should be
* created under. Only one of `orgId` or `folderId` may be
* specified. If the `folderId` is specified, then the project is
* created under the specified folder. Changing this forces the
* project to be migrated to the newly specified folder.
*/
public readonly folderId!: pulumi.Output<string | undefined>;
/**
* A set of key/value label pairs to assign to the project.
*/
public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* The display name of the project.
*/
public readonly name!: pulumi.Output<string>;
/**
* The numeric identifier of the project.
*/
public /*out*/ readonly number!: pulumi.Output<string>;
/**
* The numeric ID of the organization this project belongs to.
* Changing this forces a new project to be created. Only one of
* `orgId` or `folderId` may be specified. If the `orgId` is
* specified then the project is created at the top level. Changing
* this forces the project to be migrated to the newly specified
* organization.
*/
public readonly orgId!: pulumi.Output<string | undefined>;
/**
* The project ID. Changing this forces a new project to be created.
*/
public readonly projectId!: pulumi.Output<string>;
/**
* If true, the resource can be deleted
* without deleting the Project via the Google API.
*/
public readonly skipDelete!: pulumi.Output<boolean>;
/**
* Create a Project 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: ProjectArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: ProjectArgs | ProjectState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as ProjectState | undefined;
inputs["autoCreateNetwork"] = state ? state.autoCreateNetwork : undefined;
inputs["billingAccount"] = state ? state.billingAccount : undefined;
inputs["folderId"] = state ? state.folderId : undefined;
inputs["labels"] = state ? state.labels : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["number"] = state ? state.number : undefined;
inputs["orgId"] = state ? state.orgId : undefined;
inputs["projectId"] = state ? state.projectId : undefined;
inputs["skipDelete"] = state ? state.skipDelete : undefined;
} else {
const args = argsOrState as ProjectArgs | undefined;
if ((!args || args.projectId === undefined) && !opts.urn) {
throw new Error("Missing required property 'projectId'");
}
inputs["autoCreateNetwork"] = args ? args.autoCreateNetwork : undefined;
inputs["billingAccount"] = args ? args.billingAccount : undefined;
inputs["folderId"] = args ? args.folderId : undefined;
inputs["labels"] = args ? args.labels : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["orgId"] = args ? args.orgId : undefined;
inputs["projectId"] = args ? args.projectId : undefined;
inputs["skipDelete"] = args ? args.skipDelete : undefined;
inputs["number"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Project.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Project resources.
*/
export interface ProjectState {
/**
* Create the 'default' network automatically. Default `true`.
* If set to `false`, the default network will be deleted. Note that, for quota purposes, you
* will still need to have 1 network slot available to create the project successfully, even if
* you set `autoCreateNetwork` to `false`, since the network will exist momentarily.
*/
autoCreateNetwork?: pulumi.Input<boolean>;
/**
* The alphanumeric ID of the billing account this project
* belongs to. The user or service account performing this operation with the provider
* must have at mininum Billing Account User privileges (`roles/billing.user`) on the billing account.
* See [Google Cloud Billing API Access Control](https://cloud.google.com/billing/docs/how-to/billing-access)
* for more details.
*/
billingAccount?: pulumi.Input<string>;
/**
* The numeric ID of the folder this project should be
* created under. Only one of `orgId` or `folderId` may be
* specified. If the `folderId` is specified, then the project is
* created under the specified folder. Changing this forces the
* project to be migrated to the newly specified folder.
*/
folderId?: pulumi.Input<string>;
/**
* A set of key/value label pairs to assign to the project.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The display name of the project.
*/
name?: pulumi.Input<string>;
/**
* The numeric identifier of the project.
*/
number?: pulumi.Input<string>;
/**
* The numeric ID of the organization this project belongs to.
* Changing this forces a new project to be created. Only one of
* `orgId` or `folderId` may be specified. If the `orgId` is
* specified then the project is created at the top level. Changing
* this forces the project to be migrated to the newly specified
* organization.
*/
orgId?: pulumi.Input<string>;
/**
* The project ID. Changing this forces a new project to be created.
*/
projectId?: pulumi.Input<string>;
/**
* If true, the resource can be deleted
* without deleting the Project via the Google API.
*/
skipDelete?: pulumi.Input<boolean>;
}
/**
* The set of arguments for constructing a Project resource.
*/
export interface ProjectArgs {
/**
* Create the 'default' network automatically. Default `true`.
* If set to `false`, the default network will be deleted. Note that, for quota purposes, you
* will still need to have 1 network slot available to create the project successfully, even if
* you set `autoCreateNetwork` to `false`, since the network will exist momentarily.
*/
autoCreateNetwork?: pulumi.Input<boolean>;
/**
* The alphanumeric ID of the billing account this project
* belongs to. The user or service account performing this operation with the provider
* must have at mininum Billing Account User privileges (`roles/billing.user`) on the billing account.
* See [Google Cloud Billing API Access Control](https://cloud.google.com/billing/docs/how-to/billing-access)
* for more details.
*/
billingAccount?: pulumi.Input<string>;
/**
* The numeric ID of the folder this project should be
* created under. Only one of `orgId` or `folderId` may be
* specified. If the `folderId` is specified, then the project is
* created under the specified folder. Changing this forces the
* project to be migrated to the newly specified folder.
*/
folderId?: pulumi.Input<string>;
/**
* A set of key/value label pairs to assign to the project.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The display name of the project.
*/
name?: pulumi.Input<string>;
/**
* The numeric ID of the organization this project belongs to.
* Changing this forces a new project to be created. Only one of
* `orgId` or `folderId` may be specified. If the `orgId` is
* specified then the project is created at the top level. Changing
* this forces the project to be migrated to the newly specified
* organization.
*/
orgId?: pulumi.Input<string>;
/**
* The project ID. Changing this forces a new project to be created.
*/
projectId: pulumi.Input<string>;
/**
* If true, the resource can be deleted
* without deleting the Project via the Google API.
*/
skipDelete?: pulumi.Input<boolean>;
} | the_stack |
import { Converter, Validator, Validation, AsyncValidator } from '../ojvalidation-base';
import { DataProvider } from '../ojdataprovider';
import { editableValue, editableValueEventMap, editableValueSettableProperties } from '../ojeditablevalue';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojCombobox<V, SP extends ojComboboxSettableProperties<V, SV, RV>, SV = V, RV = V> extends editableValue<V, SP, SV, RV> {
onOjAnimateEnd: ((event: ojCombobox.ojAnimateEnd) => any) | null;
onOjAnimateStart: ((event: ojCombobox.ojAnimateStart) => any) | null;
addEventListener<T extends keyof ojComboboxEventMap<V, SP, SV, RV>>(type: T, listener: (this: HTMLElement, ev: ojComboboxEventMap<V, SP, SV, RV>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojComboboxSettableProperties<V, SV, RV>>(property: T): ojCombobox<V, SP, SV, RV>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojComboboxSettableProperties<V, SV, RV>>(property: T, value: ojComboboxSettableProperties<V, SV, RV>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojComboboxSettableProperties<V, SV, RV>>): void;
setProperties(properties: ojComboboxSettablePropertiesLenient<V, SV, RV>): void;
refresh(): void;
validate(): Promise<any>;
}
export namespace ojCombobox {
interface ojAnimateEnd extends CustomEvent<{
action: string;
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: string;
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type Optgroup = {
disabled?: boolean | undefined;
label: string;
children: Array<(Option | Optgroup)>;
};
// tslint:disable-next-line interface-over-type-literal
type Option = {
disabled?: boolean | undefined;
label?: string | undefined;
value: any;
};
// tslint:disable-next-line interface-over-type-literal
type OptionContext = {
component: Element;
parent: Element;
index: number;
depth: number;
leaf: boolean;
data: object;
parentElement: Element;
};
// tslint:disable-next-line interface-over-type-literal
type OptionsKeys = {
label?: string | undefined;
value?: string | undefined;
children?: string | undefined;
childKeys?: OptionsKeys | undefined;
};
}
export interface ojComboboxEventMap<V, SP extends ojComboboxSettableProperties<V, SV, RV>, SV = V, RV = V> extends editableValueEventMap<V, SP, SV, RV> {
'ojAnimateEnd': ojCombobox.ojAnimateEnd;
'ojAnimateStart': ojCombobox.ojAnimateStart;
}
export interface ojComboboxSettableProperties<V, SV = V, RV = V> extends editableValueSettableProperties<V, SV, RV> {
}
export interface ojComboboxSettablePropertiesLenient<V, SV, RV> extends Partial<ojComboboxSettableProperties<V, SV, RV>> {
[key: string]: any;
}
export interface ojComboboxMany<K, D> extends ojCombobox<any[] | null, ojComboboxManySettableProperties<K, D>, any[] | null, string> {
asyncValidators: Array<AsyncValidator<any[]>>;
converter: Converter<any> | Validation.RegisteredConverter | null;
minLength: number;
optionRenderer?: ((param0: ojCombobox.OptionContext) => Element) | null | undefined;
options: Array<ojCombobox.Option | ojCombobox.Optgroup> | DataProvider<K, D> | null;
optionsKeys: {
childKeys: {
label?: string | undefined;
value?: string | undefined;
children?: string | undefined;
childKeys?: ojCombobox.OptionsKeys | undefined;
};
children?: string | undefined;
label?: string | undefined;
value?: string | undefined;
};
pickerAttributes: {
style?: string | undefined;
class?: string | undefined;
};
placeholder: string | null;
readonly rawValue: string | null;
readOnly: boolean;
required: boolean;
validators: Array<Validator<any[]> | Validation.RegisteredValidator> | null;
value: any[] | null;
valueOptions: Array<{
value: any;
label?: string | undefined;
}> | null;
translations: {
filterFurther?: string | undefined;
noMatchesFound?: string | undefined;
required?: {
hint?: string | undefined;
messageDetail?: string | undefined;
messageSummary?: string | undefined;
} | undefined;
};
onAsyncValidatorsChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["asyncValidators"]>) => any) | null;
onConverterChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["converter"]>) => any) | null;
onMinLengthChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["minLength"]>) => any) | null;
onOptionRendererChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["optionRenderer"]>) => any) | null;
onOptionsChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["options"]>) => any) | null;
onOptionsKeysChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["optionsKeys"]>) => any) | null;
onPickerAttributesChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["pickerAttributes"]>) => any) | null;
onPlaceholderChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["placeholder"]>) => any) | null;
onRawValueChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["rawValue"]>) => any) | null;
onReadOnlyChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["readOnly"]>) => any) | null;
onRequiredChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["required"]>) => any) | null;
onValidatorsChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["validators"]>) => any) | null;
onValueChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["value"]>) => any) | null;
onValueOptionsChanged: ((event: JetElementCustomEvent<ojComboboxMany<K, D>["valueOptions"]>) => any) | null;
onOjAnimateEnd: ((event: ojComboboxMany.ojAnimateEnd) => any) | null;
onOjAnimateStart: ((event: ojComboboxMany.ojAnimateStart) => any) | null;
addEventListener<T extends keyof ojComboboxManyEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojComboboxManyEventMap<K, D>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojComboboxManySettableProperties<K, D>>(property: T): ojComboboxMany<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojComboboxManySettableProperties<K, D>>(property: T, value: ojComboboxManySettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojComboboxManySettableProperties<K, D>>): void;
setProperties(properties: ojComboboxManySettablePropertiesLenient<K, D>): void;
}
export namespace ojComboboxMany {
interface ojAnimateEnd extends CustomEvent<{
action: string;
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: string;
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
}
export interface ojComboboxManyEventMap<K, D> extends ojComboboxEventMap<any[] | null, ojComboboxManySettableProperties<K, D>, any[] | null, string> {
'ojAnimateEnd': ojComboboxMany.ojAnimateEnd;
'ojAnimateStart': ojComboboxMany.ojAnimateStart;
'asyncValidatorsChanged': JetElementCustomEvent<ojComboboxMany<K, D>["asyncValidators"]>;
'converterChanged': JetElementCustomEvent<ojComboboxMany<K, D>["converter"]>;
'minLengthChanged': JetElementCustomEvent<ojComboboxMany<K, D>["minLength"]>;
'optionRendererChanged': JetElementCustomEvent<ojComboboxMany<K, D>["optionRenderer"]>;
'optionsChanged': JetElementCustomEvent<ojComboboxMany<K, D>["options"]>;
'optionsKeysChanged': JetElementCustomEvent<ojComboboxMany<K, D>["optionsKeys"]>;
'pickerAttributesChanged': JetElementCustomEvent<ojComboboxMany<K, D>["pickerAttributes"]>;
'placeholderChanged': JetElementCustomEvent<ojComboboxMany<K, D>["placeholder"]>;
'rawValueChanged': JetElementCustomEvent<ojComboboxMany<K, D>["rawValue"]>;
'readOnlyChanged': JetElementCustomEvent<ojComboboxMany<K, D>["readOnly"]>;
'requiredChanged': JetElementCustomEvent<ojComboboxMany<K, D>["required"]>;
'validatorsChanged': JetElementCustomEvent<ojComboboxMany<K, D>["validators"]>;
'valueChanged': JetElementCustomEvent<ojComboboxMany<K, D>["value"]>;
'valueOptionsChanged': JetElementCustomEvent<ojComboboxMany<K, D>["valueOptions"]>;
}
export interface ojComboboxManySettableProperties<K, D> extends ojComboboxSettableProperties<any[] | null, any[] | null, string> {
asyncValidators: Array<AsyncValidator<any[]>>;
converter: Converter<any> | Validation.RegisteredConverter | null;
minLength: number;
optionRenderer?: ((param0: ojCombobox.OptionContext) => Element) | null | undefined;
options: Array<ojCombobox.Option | ojCombobox.Optgroup> | DataProvider<K, D> | null;
optionsKeys: {
childKeys: {
label?: string | undefined;
value?: string | undefined;
children?: string | undefined;
childKeys?: ojCombobox.OptionsKeys | undefined;
};
children?: string | undefined;
label?: string | undefined;
value?: string | undefined;
};
pickerAttributes: {
style?: string | undefined;
class?: string | undefined;
};
placeholder: string | null;
readonly rawValue: string | null;
readOnly: boolean;
required: boolean;
validators: Array<Validator<any[]> | Validation.RegisteredValidator> | null;
value: any[] | null;
valueOptions: Array<{
value: any;
label?: string | undefined;
}> | null;
translations: {
filterFurther?: string | undefined;
noMatchesFound?: string | undefined;
required?: {
hint?: string | undefined;
messageDetail?: string | undefined;
messageSummary?: string | undefined;
} | undefined;
};
}
export interface ojComboboxManySettablePropertiesLenient<K, D> extends Partial<ojComboboxManySettableProperties<K, D>> {
[key: string]: any;
}
export interface ojComboboxOne<K, D> extends ojCombobox<any, ojComboboxOneSettableProperties<K, D>, any, string> {
asyncValidators: Array<AsyncValidator<any>>;
converter: Converter<any> | Validation.RegisteredConverter | null;
filterOnOpen: 'none' | 'rawValue';
minLength: number;
optionRenderer?: ((param0: ojCombobox.OptionContext) => Element) | null | undefined;
options: Array<ojCombobox.Option | ojCombobox.Optgroup> | DataProvider<K, D> | null;
optionsKeys: {
childKeys: {
label?: string | undefined;
value?: string | undefined;
children?: string | undefined;
childKeys?: ojCombobox.OptionsKeys | undefined;
};
children?: string | undefined;
label?: string | undefined;
value?: string | undefined;
};
pickerAttributes: {
style?: string | undefined;
class?: string | undefined;
};
placeholder: string | null;
readonly rawValue: string | null;
readOnly: boolean;
required: boolean;
validators: Array<Validator<any> | Validation.RegisteredValidator> | null;
value: any;
valueOption: {
value: any;
label?: string | undefined;
};
translations: {
filterFurther?: string | undefined;
noMatchesFound?: string | undefined;
required?: {
hint?: string | undefined;
messageDetail?: string | undefined;
messageSummary?: string | undefined;
} | undefined;
};
onAsyncValidatorsChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["asyncValidators"]>) => any) | null;
onConverterChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["converter"]>) => any) | null;
onFilterOnOpenChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["filterOnOpen"]>) => any) | null;
onMinLengthChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["minLength"]>) => any) | null;
onOptionRendererChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["optionRenderer"]>) => any) | null;
onOptionsChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["options"]>) => any) | null;
onOptionsKeysChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["optionsKeys"]>) => any) | null;
onPickerAttributesChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["pickerAttributes"]>) => any) | null;
onPlaceholderChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["placeholder"]>) => any) | null;
onRawValueChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["rawValue"]>) => any) | null;
onReadOnlyChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["readOnly"]>) => any) | null;
onRequiredChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["required"]>) => any) | null;
onValidatorsChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["validators"]>) => any) | null;
onValueChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["value"]>) => any) | null;
onValueOptionChanged: ((event: JetElementCustomEvent<ojComboboxOne<K, D>["valueOption"]>) => any) | null;
onOjAnimateEnd: ((event: ojComboboxOne.ojAnimateEnd) => any) | null;
onOjAnimateStart: ((event: ojComboboxOne.ojAnimateStart) => any) | null;
onOjValueUpdated: ((event: ojComboboxOne.ojValueUpdated) => any) | null;
addEventListener<T extends keyof ojComboboxOneEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojComboboxOneEventMap<K, D>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojComboboxOneSettableProperties<K, D>>(property: T): ojComboboxOne<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojComboboxOneSettableProperties<K, D>>(property: T, value: ojComboboxOneSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojComboboxOneSettableProperties<K, D>>): void;
setProperties(properties: ojComboboxOneSettablePropertiesLenient<K, D>): void;
}
export namespace ojComboboxOne {
interface ojAnimateEnd extends CustomEvent<{
action: string;
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: string;
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
interface ojValueUpdated extends CustomEvent<{
value: any;
previousValue: any;
[propName: string]: any;
}> {
}
}
export interface ojComboboxOneEventMap<K, D> extends ojComboboxEventMap<any, ojComboboxOneSettableProperties<K, D>, any, string> {
'ojAnimateEnd': ojComboboxOne.ojAnimateEnd;
'ojAnimateStart': ojComboboxOne.ojAnimateStart;
'ojValueUpdated': ojComboboxOne.ojValueUpdated;
'asyncValidatorsChanged': JetElementCustomEvent<ojComboboxOne<K, D>["asyncValidators"]>;
'converterChanged': JetElementCustomEvent<ojComboboxOne<K, D>["converter"]>;
'filterOnOpenChanged': JetElementCustomEvent<ojComboboxOne<K, D>["filterOnOpen"]>;
'minLengthChanged': JetElementCustomEvent<ojComboboxOne<K, D>["minLength"]>;
'optionRendererChanged': JetElementCustomEvent<ojComboboxOne<K, D>["optionRenderer"]>;
'optionsChanged': JetElementCustomEvent<ojComboboxOne<K, D>["options"]>;
'optionsKeysChanged': JetElementCustomEvent<ojComboboxOne<K, D>["optionsKeys"]>;
'pickerAttributesChanged': JetElementCustomEvent<ojComboboxOne<K, D>["pickerAttributes"]>;
'placeholderChanged': JetElementCustomEvent<ojComboboxOne<K, D>["placeholder"]>;
'rawValueChanged': JetElementCustomEvent<ojComboboxOne<K, D>["rawValue"]>;
'readOnlyChanged': JetElementCustomEvent<ojComboboxOne<K, D>["readOnly"]>;
'requiredChanged': JetElementCustomEvent<ojComboboxOne<K, D>["required"]>;
'validatorsChanged': JetElementCustomEvent<ojComboboxOne<K, D>["validators"]>;
'valueChanged': JetElementCustomEvent<ojComboboxOne<K, D>["value"]>;
'valueOptionChanged': JetElementCustomEvent<ojComboboxOne<K, D>["valueOption"]>;
}
export interface ojComboboxOneSettableProperties<K, D> extends ojComboboxSettableProperties<any, any, string> {
asyncValidators: Array<AsyncValidator<any>>;
converter: Converter<any> | Validation.RegisteredConverter | null;
filterOnOpen: 'none' | 'rawValue';
minLength: number;
optionRenderer?: ((param0: ojCombobox.OptionContext) => Element) | null | undefined;
options: Array<ojCombobox.Option | ojCombobox.Optgroup> | DataProvider<K, D> | null;
optionsKeys: {
childKeys: {
label?: string | undefined;
value?: string | undefined;
children?: string | undefined;
childKeys?: ojCombobox.OptionsKeys | undefined;
};
children?: string | undefined;
label?: string | undefined;
value?: string | undefined;
};
pickerAttributes: {
style?: string | undefined;
class?: string | undefined;
};
placeholder: string | null;
readonly rawValue: string | null;
readOnly: boolean;
required: boolean;
validators: Array<Validator<any> | Validation.RegisteredValidator> | null;
value: any;
valueOption: {
value: any;
label?: string | undefined;
};
translations: {
filterFurther?: string | undefined;
noMatchesFound?: string | undefined;
required?: {
hint?: string | undefined;
messageDetail?: string | undefined;
messageSummary?: string | undefined;
} | undefined;
};
}
export interface ojComboboxOneSettablePropertiesLenient<K, D> extends Partial<ojComboboxOneSettableProperties<K, D>> {
[key: string]: any;
}
export interface ojSelect<V, SP extends ojSelectSettableProperties<V, SV>, SV = V> extends editableValue<V, SP, SV> {
onOjAnimateEnd: ((event: ojSelect.ojAnimateEnd) => any) | null;
onOjAnimateStart: ((event: ojSelect.ojAnimateStart) => any) | null;
addEventListener<T extends keyof ojSelectEventMap<V, SP, SV>>(type: T, listener: (this: HTMLElement, ev: ojSelectEventMap<V, SP, SV>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojSelectSettableProperties<V, SV>>(property: T): ojSelect<V, SP, SV>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojSelectSettableProperties<V, SV>>(property: T, value: ojSelectSettableProperties<V, SV>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSelectSettableProperties<V, SV>>): void;
setProperties(properties: ojSelectSettablePropertiesLenient<V, SV>): void;
refresh(): void;
validate(): Promise<any>;
}
export namespace ojSelect {
interface ojAnimateEnd extends CustomEvent<{
action: string;
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: string;
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type Optgroup = {
disabled?: boolean | undefined;
label: string;
children: Array<(Option | Optgroup)>;
};
// tslint:disable-next-line interface-over-type-literal
type Option = {
disabled?: boolean | undefined;
label?: string | undefined;
value: any;
};
// tslint:disable-next-line interface-over-type-literal
type OptionContext = {
component: Element;
parent: Element;
index: number;
depth: number;
leaf: boolean;
data: object;
parentElement: Element;
};
// tslint:disable-next-line interface-over-type-literal
type OptionsKeys = {
label?: string | undefined;
value?: string | undefined;
children?: string | undefined;
childKeys?: OptionsKeys | undefined;
};
}
export interface ojSelectEventMap<V, SP extends ojSelectSettableProperties<V, SV>, SV = V> extends editableValueEventMap<V, SP, SV> {
'ojAnimateEnd': ojSelect.ojAnimateEnd;
'ojAnimateStart': ojSelect.ojAnimateStart;
}
export interface ojSelectSettableProperties<V, SV = V> extends editableValueSettableProperties<V, SV> {
}
export interface ojSelectSettablePropertiesLenient<V, SV> extends Partial<ojSelectSettableProperties<V, SV>> {
[key: string]: any;
}
export interface ojSelectMany<K, D> extends ojSelect<any[] | null, ojSelectManySettableProperties<K, D>> {
minimumResultsForSearch: number;
optionRenderer?: ((param0: ojSelect.OptionContext) => Element) | null | undefined;
options: Array<ojSelect.Option | ojSelect.Optgroup> | DataProvider<K, D> | null;
optionsKeys: {
childKeys?: {
label?: string | undefined;
value?: string | undefined;
children?: string | undefined;
childKeys?: ojSelect.OptionsKeys | undefined;
} | undefined;
children?: string | undefined;
label?: string | undefined;
value?: string | undefined;
};
pickerAttributes: {
style?: string | undefined;
class?: string | undefined;
};
placeholder: string | null;
readOnly: boolean;
renderMode: 'jet' | 'native';
required: boolean;
value: any[] | null;
valueOptions: Array<{
value: any;
label?: string | undefined;
}> | null;
translations: {
filterFurther?: string | undefined;
moreMatchesFound?: string | undefined;
noMatchesFound?: string | undefined;
oneMatchesFound?: string | undefined;
required?: {
hint?: string | undefined;
messageDetail?: string | undefined;
messageSummary?: string | undefined;
} | undefined;
searchField?: string | undefined;
};
onMinimumResultsForSearchChanged: ((event: JetElementCustomEvent<ojSelectMany<K, D>["minimumResultsForSearch"]>) => any) | null;
onOptionRendererChanged: ((event: JetElementCustomEvent<ojSelectMany<K, D>["optionRenderer"]>) => any) | null;
onOptionsChanged: ((event: JetElementCustomEvent<ojSelectMany<K, D>["options"]>) => any) | null;
onOptionsKeysChanged: ((event: JetElementCustomEvent<ojSelectMany<K, D>["optionsKeys"]>) => any) | null;
onPickerAttributesChanged: ((event: JetElementCustomEvent<ojSelectMany<K, D>["pickerAttributes"]>) => any) | null;
onPlaceholderChanged: ((event: JetElementCustomEvent<ojSelectMany<K, D>["placeholder"]>) => any) | null;
onReadOnlyChanged: ((event: JetElementCustomEvent<ojSelectMany<K, D>["readOnly"]>) => any) | null;
onRenderModeChanged: ((event: JetElementCustomEvent<ojSelectMany<K, D>["renderMode"]>) => any) | null;
onRequiredChanged: ((event: JetElementCustomEvent<ojSelectMany<K, D>["required"]>) => any) | null;
onValueChanged: ((event: JetElementCustomEvent<ojSelectMany<K, D>["value"]>) => any) | null;
onValueOptionsChanged: ((event: JetElementCustomEvent<ojSelectMany<K, D>["valueOptions"]>) => any) | null;
onOjAnimateEnd: ((event: ojSelectMany.ojAnimateEnd) => any) | null;
onOjAnimateStart: ((event: ojSelectMany.ojAnimateStart) => any) | null;
addEventListener<T extends keyof ojSelectManyEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojSelectManyEventMap<K, D>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojSelectManySettableProperties<K, D>>(property: T): ojSelectMany<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojSelectManySettableProperties<K, D>>(property: T, value: ojSelectManySettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSelectManySettableProperties<K, D>>): void;
setProperties(properties: ojSelectManySettablePropertiesLenient<K, D>): void;
}
export namespace ojSelectMany {
interface ojAnimateEnd extends CustomEvent<{
action: string;
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: string;
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
}
export interface ojSelectManyEventMap<K, D> extends ojSelectEventMap<any[] | null, ojSelectManySettableProperties<K, D>> {
'ojAnimateEnd': ojSelectMany.ojAnimateEnd;
'ojAnimateStart': ojSelectMany.ojAnimateStart;
'minimumResultsForSearchChanged': JetElementCustomEvent<ojSelectMany<K, D>["minimumResultsForSearch"]>;
'optionRendererChanged': JetElementCustomEvent<ojSelectMany<K, D>["optionRenderer"]>;
'optionsChanged': JetElementCustomEvent<ojSelectMany<K, D>["options"]>;
'optionsKeysChanged': JetElementCustomEvent<ojSelectMany<K, D>["optionsKeys"]>;
'pickerAttributesChanged': JetElementCustomEvent<ojSelectMany<K, D>["pickerAttributes"]>;
'placeholderChanged': JetElementCustomEvent<ojSelectMany<K, D>["placeholder"]>;
'readOnlyChanged': JetElementCustomEvent<ojSelectMany<K, D>["readOnly"]>;
'renderModeChanged': JetElementCustomEvent<ojSelectMany<K, D>["renderMode"]>;
'requiredChanged': JetElementCustomEvent<ojSelectMany<K, D>["required"]>;
'valueChanged': JetElementCustomEvent<ojSelectMany<K, D>["value"]>;
'valueOptionsChanged': JetElementCustomEvent<ojSelectMany<K, D>["valueOptions"]>;
}
export interface ojSelectManySettableProperties<K, D> extends ojSelectSettableProperties<any[] | null> {
minimumResultsForSearch: number;
optionRenderer?: ((param0: ojSelect.OptionContext) => Element) | null | undefined;
options: Array<ojSelect.Option | ojSelect.Optgroup> | DataProvider<K, D> | null;
optionsKeys: {
childKeys?: {
label?: string | undefined;
value?: string | undefined;
children?: string | undefined;
childKeys?: ojSelect.OptionsKeys | undefined;
} | undefined;
children?: string | undefined;
label?: string | undefined;
value?: string | undefined;
};
pickerAttributes: {
style?: string | undefined;
class?: string | undefined;
};
placeholder: string | null;
readOnly: boolean;
renderMode: 'jet' | 'native';
required: boolean;
value: any[] | null;
valueOptions: Array<{
value: any;
label?: string | undefined;
}> | null;
translations: {
filterFurther?: string | undefined;
moreMatchesFound?: string | undefined;
noMatchesFound?: string | undefined;
oneMatchesFound?: string | undefined;
required?: {
hint?: string | undefined;
messageDetail?: string | undefined;
messageSummary?: string | undefined;
} | undefined;
searchField?: string | undefined;
};
}
export interface ojSelectManySettablePropertiesLenient<K, D> extends Partial<ojSelectManySettableProperties<K, D>> {
[key: string]: any;
}
export interface ojSelectOne<K, D> extends ojSelect<any, ojSelectOneSettableProperties<K, D>> {
minimumResultsForSearch: number;
optionRenderer?: ((param0: ojSelect.OptionContext) => Element) | null | undefined;
options: Array<ojSelect.Option | ojSelect.Optgroup> | DataProvider<K, D> | null;
optionsKeys: {
childKeys?: {
label?: string | undefined;
value?: string | undefined;
children?: string | undefined;
childKeys?: ojSelect.OptionsKeys | undefined;
} | undefined;
children?: string | undefined;
label?: string | undefined;
value?: string | undefined;
};
pickerAttributes: {
style?: string | undefined;
class?: string | undefined;
};
placeholder: string | null;
readOnly: boolean;
renderMode: 'jet' | 'native';
required: boolean;
value: any;
valueOption: {
value: any;
label?: string | undefined;
};
translations: {
filterFurther?: string | undefined;
moreMatchesFound?: string | undefined;
noMatchesFound?: string | undefined;
oneMatchesFound?: string | undefined;
required?: {
hint?: string | undefined;
messageDetail?: string | undefined;
messageSummary?: string | undefined;
} | undefined;
searchField?: string | undefined;
};
onMinimumResultsForSearchChanged: ((event: JetElementCustomEvent<ojSelectOne<K, D>["minimumResultsForSearch"]>) => any) | null;
onOptionRendererChanged: ((event: JetElementCustomEvent<ojSelectOne<K, D>["optionRenderer"]>) => any) | null;
onOptionsChanged: ((event: JetElementCustomEvent<ojSelectOne<K, D>["options"]>) => any) | null;
onOptionsKeysChanged: ((event: JetElementCustomEvent<ojSelectOne<K, D>["optionsKeys"]>) => any) | null;
onPickerAttributesChanged: ((event: JetElementCustomEvent<ojSelectOne<K, D>["pickerAttributes"]>) => any) | null;
onPlaceholderChanged: ((event: JetElementCustomEvent<ojSelectOne<K, D>["placeholder"]>) => any) | null;
onReadOnlyChanged: ((event: JetElementCustomEvent<ojSelectOne<K, D>["readOnly"]>) => any) | null;
onRenderModeChanged: ((event: JetElementCustomEvent<ojSelectOne<K, D>["renderMode"]>) => any) | null;
onRequiredChanged: ((event: JetElementCustomEvent<ojSelectOne<K, D>["required"]>) => any) | null;
onValueChanged: ((event: JetElementCustomEvent<ojSelectOne<K, D>["value"]>) => any) | null;
onValueOptionChanged: ((event: JetElementCustomEvent<ojSelectOne<K, D>["valueOption"]>) => any) | null;
onOjAnimateEnd: ((event: ojSelectOne.ojAnimateEnd) => any) | null;
onOjAnimateStart: ((event: ojSelectOne.ojAnimateStart) => any) | null;
addEventListener<T extends keyof ojSelectOneEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojSelectOneEventMap<K, D>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojSelectOneSettableProperties<K, D>>(property: T): ojSelectOne<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojSelectOneSettableProperties<K, D>>(property: T, value: ojSelectOneSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSelectOneSettableProperties<K, D>>): void;
setProperties(properties: ojSelectOneSettablePropertiesLenient<K, D>): void;
}
export namespace ojSelectOne {
interface ojAnimateEnd extends CustomEvent<{
action: string;
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: string;
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
}
export interface ojSelectOneEventMap<K, D> extends ojSelectEventMap<any, ojSelectOneSettableProperties<K, D>> {
'ojAnimateEnd': ojSelectOne.ojAnimateEnd;
'ojAnimateStart': ojSelectOne.ojAnimateStart;
'minimumResultsForSearchChanged': JetElementCustomEvent<ojSelectOne<K, D>["minimumResultsForSearch"]>;
'optionRendererChanged': JetElementCustomEvent<ojSelectOne<K, D>["optionRenderer"]>;
'optionsChanged': JetElementCustomEvent<ojSelectOne<K, D>["options"]>;
'optionsKeysChanged': JetElementCustomEvent<ojSelectOne<K, D>["optionsKeys"]>;
'pickerAttributesChanged': JetElementCustomEvent<ojSelectOne<K, D>["pickerAttributes"]>;
'placeholderChanged': JetElementCustomEvent<ojSelectOne<K, D>["placeholder"]>;
'readOnlyChanged': JetElementCustomEvent<ojSelectOne<K, D>["readOnly"]>;
'renderModeChanged': JetElementCustomEvent<ojSelectOne<K, D>["renderMode"]>;
'requiredChanged': JetElementCustomEvent<ojSelectOne<K, D>["required"]>;
'valueChanged': JetElementCustomEvent<ojSelectOne<K, D>["value"]>;
'valueOptionChanged': JetElementCustomEvent<ojSelectOne<K, D>["valueOption"]>;
}
export interface ojSelectOneSettableProperties<K, D> extends ojSelectSettableProperties<any> {
minimumResultsForSearch: number;
optionRenderer?: ((param0: ojSelect.OptionContext) => Element) | null | undefined;
options: Array<ojSelect.Option | ojSelect.Optgroup> | DataProvider<K, D> | null;
optionsKeys: {
childKeys?: {
label?: string | undefined;
value?: string | undefined;
children?: string | undefined;
childKeys?: ojSelect.OptionsKeys | undefined;
} | undefined;
children?: string | undefined;
label?: string | undefined;
value?: string | undefined;
};
pickerAttributes: {
style?: string | undefined;
class?: string | undefined;
};
placeholder: string | null;
readOnly: boolean;
renderMode: 'jet' | 'native';
required: boolean;
value: any;
valueOption: {
value: any;
label?: string | undefined;
};
translations: {
filterFurther?: string | undefined;
moreMatchesFound?: string | undefined;
noMatchesFound?: string | undefined;
oneMatchesFound?: string | undefined;
required?: {
hint?: string | undefined;
messageDetail?: string | undefined;
messageSummary?: string | undefined;
} | undefined;
searchField?: string | undefined;
};
}
export interface ojSelectOneSettablePropertiesLenient<K, D> extends Partial<ojSelectOneSettableProperties<K, D>> {
[key: string]: any;
}
export interface Optgroup {
children: Array<(Option | Optgroup)>;
disabled?: boolean | undefined;
label: string;
}
export interface Option {
disabled?: boolean | undefined;
label?: string | undefined;
value: object;
} | the_stack |
import * as ReactReconciler from "react-reconciler";
import * as scheduler from "scheduler";
import { isKnownView } from "../nativescript-vue-next/runtime/registry";
import { precacheFiberNode, updateFiberProps } from "./ComponentTree";
import { diffProperties, updateProperties, setInitialProperties } from "./ReactNativeScriptComponent";
import * as console from "../shared/Logger";
import {
HostContext,
Instance,
Type,
Props,
Container,
TextInstance,
HydratableInstance,
PublicInstance,
} from "../shared/HostConfigTypes";
import { NSVElement, NSVText, NSVRoot } from "../nativescript-vue-next/runtime/nodes";
type UpdatePayload = {
hostContext: HostContext;
updates: Array<any>;
};
type ChildSet = any;
type TimeoutHandle = number; // Actually strictly should be Node-style timeout
type NoTimeout = any;
const noTimeoutValue: NoTimeout = undefined;
// https://medium.com/@agent_hunt/hello-world-custom-react-renderer-9a95b7cd04bc
const hostConfig: ReactReconciler.HostConfig<
Type,
Props,
Container,
Instance,
TextInstance,
HydratableInstance,
PublicInstance,
HostContext,
UpdatePayload,
ChildSet,
TimeoutHandle,
NoTimeout
> = {
//https://github.com/sencha/ext-react/issues/306#issuecomment-521906095
scheduleDeferredCallback: scheduler.unstable_scheduleCallback,
cancelDeferredCallback: scheduler.unstable_cancelCallback,
// @ts-ignore not in typings
schedulePassiveEffects: scheduler.unstable_scheduleCallback,
cancelPassiveEffects: scheduler.unstable_cancelCallback,
// @ts-ignore not in typings
shouldYield: scheduler.unstable_shouldYield,
now: scheduler.unstable_now,
getPublicInstance(instance: Instance | TextInstance): PublicInstance {
// TODO (this was a complete guess).
return instance;
},
getRootHostContext(rootContainerInstance: Container): HostContext {
return {
isInAParentText: false,
isInAParentSpan: false,
isInAParentFormattedString: false,
isInADockLayout: false,
isInAGridLayout: false,
isInAnAbsoluteLayout: false,
isInAFlexboxLayout: false,
};
},
getChildHostContext(parentHostContext: HostContext, type: Type, rootContainerInstance: Container): HostContext {
/*
* Given the following, wrapped in a Page:
<RCTFlexboxLayout flexDirection={"row"}>
<RCTLabel text={"LABEL"}/>
<RCTButton text={"BUTTON"}/>
</RCTFlexboxLayout>
*
* 'type' evidently refers to the type of the child:
*
* When type 'flexboxLayout' passes into here, it will have parentHostContext.isInAFlexboxLayout: false.
* We return a HostContext with `"isInAFlexboxLayout": true`.
*
* When type 'label' or 'button' passes into here, they will then find that
* parentHostContext.isInAFlexboxLayout === true.
*/
// console.log(`[getChildHostContext] type: ${type}`);
const prevIsInAParentText: boolean = parentHostContext.isInAParentText;
const prevIsInAParentSpan: boolean = parentHostContext.isInAParentSpan;
const prevIsInAParentFormattedString: boolean = parentHostContext.isInAParentFormattedString;
const prevIsInADockLayout: boolean = parentHostContext.isInADockLayout;
const prevIsInAnAbsoluteLayout: boolean = parentHostContext.isInAnAbsoluteLayout;
const prevIsInAFlexboxLayout: boolean = parentHostContext.isInAFlexboxLayout;
/**
* TODO: as the Host Config only exposes the parent type, rather than the actual instance of the parent, we can't support adding text nodes as children
* based on instanceof. This means that any elements extending text primitives won't inherit the text primitives' behaviour.
*
* We could address this by enforcing a magic string at the front of the type, but it's not ideal.
*/
const isInAParentText: boolean =
type === "label" || type === "textView" || type === "textField" || type === "button";
/**
* We'll allow Span to support text nodes despite not extending TextBase.
* @see https://github.com/shirakaba/react-nativescript/issues/53#issuecomment-612834141
*/
const isInAParentSpan: boolean = type === "span";
const isInAParentFormattedString: boolean = type === "formattedString";
const isInADockLayout: boolean = type === "dockLayout";
const isInAGridLayout: boolean = type === "gridLayout";
const isInAnAbsoluteLayout: boolean = type === "absoluteLayout";
const isInAFlexboxLayout: boolean = type === "flexboxLayout";
/* We do have the option here in future to force ancestry based on a previous ancestor
* (e.g. if we want text styles to cascade to all ancestors). Layout props are only with
* respect to the immediate parent, however, so no need to do anything special for those.
*
* Here we avoid recreating an object that happens to deep-equal parentHostContext.
*/
if (
prevIsInAParentText === isInAParentText &&
prevIsInAParentSpan === isInAParentSpan &&
prevIsInAParentFormattedString === isInAParentFormattedString &&
prevIsInADockLayout === isInADockLayout &&
prevIsInADockLayout === isInAGridLayout &&
prevIsInAnAbsoluteLayout === isInAnAbsoluteLayout &&
prevIsInAFlexboxLayout === isInAFlexboxLayout
) {
return parentHostContext;
} else {
return {
isInAParentText,
isInAParentSpan,
isInAParentFormattedString,
isInADockLayout,
isInAGridLayout,
isInAnAbsoluteLayout,
isInAFlexboxLayout,
};
}
},
/**
* This function is called when we have made a in-memory render tree of all the views (Remember we are yet to attach it the the actual root dom node).
* Here we can do any preparation that needs to be done on the rootContainer before attaching the in memory render tree.
* For example: In the case of react-dom, it keeps track of all the currently focused elements, disabled events temporarily, etc.
* @param rootContainerInstance - root dom node you specify while calling render. This is most commonly <div id="root"></div>
*/
prepareForCommit(rootContainerInstance: Container): void {
// TODO
},
/**
* This function gets executed after the inmemory tree has been attached to the root dom element. Here we can do any post attach operations that needs to be done.
* For example: react-dom re-enabled events which were temporarily disabled in prepareForCommit and refocuses elements, etc.
* @param rootContainerInstance - root dom node you specify while calling render. This is most commonly <div id="root"></div>
*/
resetAfterCommit(rootContainerInstance: Container): void {
// TODO
},
// TODO: replace parts of this with updateDOMProperties() where applicable
createInstance(
type: Type,
props: Props,
rootContainerInstance: Container,
hostContext: HostContext,
internalInstanceHandle: ReactReconciler.OpaqueHandle
): Instance {
// if(type === "page" || type === "frame"){
// (() => {
// const { children, ...rest } = props;
// console.log(`[createInstance() 1a] type: ${type}. props:`, {
// ...rest,
// });
// })();
// console.log(`[createInstance() 1b] type: ${type}`);
// }
let view: Instance;
// const viewConstructor: InstanceCreator | null = typeof type === "string" ? elementMap[type] : null;
if (typeof type === "string" && isKnownView(type)) {
view = new NSVElement(type);
precacheFiberNode(internalInstanceHandle, view);
updateFiberProps(view, props);
} else {
if (typeof type === "undefined") {
throw new Error(`HostConfig received undefined type in createInstance.`);
}
console.log(
`Type not found in element registry, so must be custom instance; recursing until we get a type in the element registry.`
);
const componentFunction: React.Component<Props, {}> = new (type as any)(props);
const createdElement = componentFunction.render() as React.ReactElement<
Props,
React.JSXElementConstructor<any> | string
>;
return hostConfig.createInstance(
createdElement.type,
createdElement.props,
rootContainerInstance,
hostContext,
internalInstanceHandle
);
}
/* finalizeInitialChildren() > setInitialProperties() shall handle props, just as in React DOM. */
return view;
},
appendInitialChild(parentInstance: Instance, child: Instance | TextInstance): void {
// console.log(`[appendInitialChild()] ${parentInstance.nativeView} > ${(child as Instance).nativeView || `"` + (child as TextInstance).text + `"`}`);
hostConfig.appendChild(parentInstance, child);
},
/**
* Docs from: https://blog.atulr.com/react-custom-renderer-2/
* @param parentInstance - the DOM element after appendInitialChild()
* @param type - the type of Fiber, e.g. "div"
* @param props - the props to be passed to the host Element.
* @param rootContainerInstance - root dom node you specify while calling render. This is most commonly <div id="root"></div>
* @param hostContext - contains the context from the parent node enclosing this node. This is the return value from getChildHostContext of the parent node.
* @returns A boolean value which decides if commitMount() for this element needs to be called.
*/
finalizeInitialChildren(
parentInstance: Instance,
type: Type,
props: Props,
rootContainerInstance: Container,
hostContext: HostContext
): boolean {
// console.log(`finalizeInitialChildren() with parentInstance type: ${type}`, parentInstance);
setInitialProperties(parentInstance, type, props, rootContainerInstance, hostContext);
return false;
},
shouldSetTextContent(type: Type, props: Props): boolean {
return typeof props.children === "string" || typeof props.children === "number";
},
/**
* This function is used to deprioritize rendering of some subtrees. Mostly used in cases where the subtree is hidden or offscreen.
* @param type - the DOM type of the element, e.g. "div"
* @param props - the props to be passed to the Element.
*/
shouldDeprioritizeSubtree(type: Type, props: Props): boolean {
return !!props.hidden; // Purely based on React-DOM.
},
createTextInstance(
text: string,
rootContainerInstance: Container,
hostContext: HostContext,
internalInstanceHandle: ReactReconciler.OpaqueHandle
): TextInstance {
console.log(`[createTextInstance] with text: "${text}"`);
if (!hostContext.isInAParentText && !hostContext.isInAParentSpan) {
throw new Error(
`React NativeScript's Host Config only supports rendering text nodes as direct children of one of the primitives ["label", "textView", "textField", "button", "span"]. Please use the 'text' property for setting text on this element instead.`
);
}
const textNode = new NSVText(text);
/**
* I'm not too sure what precacheFiberNode does, but I think it sets a bunch of attributes on the node.
* As NSVText never implemented node.setAttribute() in the first place, this line of code (now commented
* out) could only ever have led to a crash before. So I'm now omitting it.
*
* In any case, I guess in normal usage, developers don't end up going down this path, maybe because of
* the above guard.
*/
// precacheFiberNode(internalInstanceHandle, textNode as Instance);
return textNode;
},
// scheduleDeferredCallback(callback: () => any, options?: { timeout: number }): any {
// // TODO: check whether default timeout should be 0.
// if (!options) options = { timeout: 0 };
// return setTimeout(callback, options.timeout);
// },
// cancelDeferredCallback(callbackID: any): void {
// clearTimeout(callbackID);
// },
setTimeout(handler: (...args: any[]) => void, timeout: number): TimeoutHandle | NoTimeout {
return setTimeout(handler, timeout);
},
clearTimeout(handle: TimeoutHandle | NoTimeout): void {
clearTimeout(handle);
},
noTimeout: noTimeoutValue,
// now: Date.now,
isPrimaryRenderer: true,
supportsMutation: true, // TODO
supportsPersistence: false,
supportsHydration: false,
/* Mutation (optional) */
appendChild(parentInstance: Instance, child: Instance | TextInstance): void {
// console.log(`[appendChild()] ${parentInstance} > ${child}`);
if (parentInstance === null) {
console.warn(
`[appendChild()] parent is null (this is a typical occurrence when rendering a child into a detached tree); shall no-op here: ${parentInstance} > ${child}`
);
return;
}
parentInstance.appendChild(child);
},
appendChildToContainer(container: Container, child: Instance | TextInstance): void {
if (container instanceof NSVRoot) {
console.log(`[appendChildToContainer()] deferring to appendChild(): ${container} > ${child}`);
container.setBaseRef(child);
return;
}
console.log(`[appendChildToContainer()] proceeding: ${container} > ${child}`);
container.appendChild(child);
},
commitTextUpdate(textInstance: TextInstance, oldText: string, newText: string): void {
console.log(`[commitTextUpdate()]`, textInstance);
textInstance.text = newText;
},
/**
* From: https://blog.atulr.com/react-custom-renderer-2/
* This function is called for every element that has set the return value of finalizeInitialChildren() to true. This method is called after all the steps are done (ie after resetAfterCommit), meaning the entire tree has been attached to the dom.
* This method is mainly used in react-dom for implementing autofocus. This method exists in react-dom only and not in react-native.
* @param instance
* @param type
* @param newProps
* @param internalInstanceHandle
*/
commitMount(
instance: Instance,
type: Type,
newProps: Props,
internalInstanceHandle: ReactReconciler.OpaqueHandle
): void {
console.log(`commitMount() with type: ${type}`, instance);
// (instance as View).focus();
},
/**
* From: https://blog.atulr.com/react-custom-renderer-3/
* Expanded on in: https://hackernoon.com/learn-you-some-custom-react-renderers-aed7164a4199
* @param instance - the current DOM instance of the Node.
* @param type - the type of fiber, e.g. "div".
* @param oldProps - props before this update.
* @param newProps - incoming props.
* @param rootContainerInstance - root dom node you specify while calling render. This is most commonly <div id="root"></div>
* @param hostContext - contains the context from the parent node enclosing this node. This is the return value from getChildHostContext of the parent node.
* @returns This function should return a payload object. Payload is a Javascript object that can contain information on what needs to be changed on this host element.
*/
prepareUpdate(
instance: Instance,
type: Type,
oldProps: Props,
newProps: Props,
rootContainerInstance: Container,
hostContext: HostContext
): null | UpdatePayload {
// console.log(`prepareUpdate() with type: ${type}`, instance);
// if ((global as any).__DEV__) {
// const hostContextDev: HostContextDev = hostContext as HostContextDev;
// if (
// typeof newProps.children !== typeof oldProps.children &&
// (typeof newProps.children === 'string' ||
// typeof newProps.children === 'number')
// ) {
// const str: string = '' + newProps.children;
// const ownAncestorInfo = updatedAncestorInfo(
// hostContextDev.ancestorInfo,
// type as string,
// );
// validateDOMNesting(null, str, ownAncestorInfo);
// }
// }
// (()=>{
// const { children, ...rest } = oldProps;
// console.log(`About to run diffProperties on ${instance}. oldProps:`, { ...rest });
// })();
// (()=>{
// const { children, ...rest } = newProps;
// console.log(`About to run diffProperties on ${instance}. newProps:`, { ...rest });
// })();
const diffed: null | UpdatePayload["updates"] = diffProperties(
instance,
type,
oldProps,
newProps,
rootContainerInstance
);
// console.log(`[prepareUpdate] for ${instance}, diffed:`, diffed);
return diffed === null
? null
: {
hostContext,
updates: diffed,
};
// return {}; // Simply return a non-null value to permit commitUpdate();
// return null;
},
commitUpdate(
instance: Instance,
updatePayload: UpdatePayload,
type: Type,
oldProps: Props,
newProps: Props,
internalInstanceHandle: ReactReconciler.OpaqueHandle
): void {
// console.log(`commitUpdate() with type: ${type}`, instance);
// Update the props handle so that we know which props are the ones with
// with current event handlers.
updateFiberProps(instance, newProps);
// Apply the diff to the DOM node.
updateProperties(instance, updatePayload.updates, type, oldProps, newProps, updatePayload.hostContext);
},
insertBefore(parentInstance: Instance, child: Instance | TextInstance, beforeChild: Instance | TextInstance): void {
console.log(`[HostConfig.insertBefore] ${parentInstance} > ${child} beforeChild ${beforeChild}`);
parentInstance.insertBefore(child, beforeChild);
},
/**
* From: https://blog.atulr.com/react-custom-renderer-3/
* This function is called whenever an element needs to insertedBefore the top most level component (Root component) itself.
* @param container - the root container node to which a the child node needs to be inserted.
* @param child - the dom node that needs to be inserted.
* @param beforeChild - the child node before which the new child node needs to be inserted.
*/
insertInContainerBefore(
container: Container,
child: Instance | TextInstance,
beforeChild: Instance | TextInstance
): void {
if (container instanceof NSVRoot) {
console.log(
`[insertInContainerBefore()] performing no-op for insertBefore(): ${container} > ${child} beforeChild ${beforeChild}`
);
container.setBaseRef(child); // Unsure what else to do here..!
return;
}
console.log(
`[insertInContainerBefore()] performing insertBefore(): ${container} > ${child} beforeChild ${beforeChild}`
);
container.insertBefore(child, beforeChild);
},
removeChild(parent: Instance, child: Instance | TextInstance): void {
if (parent === null) {
// TODO: consult React expert here!
console.warn(
`[removeChild()] parent is null (this is a typical occurrence when unmounting a Portal that was rendered into a null parent); shall no-op here, but totally unsure whether this leaks memory: ${parent} x ${child}`
);
return;
}
parent.removeChild(child);
},
removeChildFromContainer(container: Container, child: Instance | TextInstance): void {
if (container instanceof NSVRoot) {
container.setBaseRef(null);
return;
}
console.log(`[removeChildFromContainer()] performing removeChild(): ${container} > ${child}`);
container.removeChild(child);
},
resetTextContent(instance: Instance): void {
instance.text = "";
},
};
export const reactReconcilerInst = ReactReconciler<
Type,
Props,
Container,
Instance,
TextInstance,
HydratableInstance,
PublicInstance,
HostContext,
UpdatePayload,
ChildSet,
TimeoutHandle,
NoTimeout
>(hostConfig); | the_stack |
import { Component, Optional, Input, OnInit, OnDestroy } from '@angular/core';
import { Params } from '@angular/router';
import { CoreError } from '@classes/errors/error';
import { CoreCourseModuleMainActivityComponent } from '@features/course/classes/main-activity-component';
import { CoreCourseContentsPage } from '@features/course/pages/contents/contents';
import { CoreCourse } from '@features/course/services/course';
import { CoreTag, CoreTagItem } from '@features/tag/services/tag';
import { CoreUser } from '@features/user/services/user';
import { IonContent } from '@ionic/angular';
import { CoreGroup, CoreGroups } from '@services/groups';
import { CoreNavigator } from '@services/navigator';
import { CoreSites } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreTextUtils } from '@services/utils/text';
import { CoreUtils } from '@services/utils/utils';
import { Translate } from '@singletons';
import { CoreEventObserver, CoreEvents } from '@singletons/events';
import { Md5 } from 'ts-md5';
import { AddonModWikiPageDBRecord } from '../../services/database/wiki';
import { AddonModWikiModuleHandlerService } from '../../services/handlers/module';
import {
AddonModWiki,
AddonModWikiPageContents,
AddonModWikiProvider,
AddonModWikiSubwiki,
AddonModWikiSubwikiListData,
AddonModWikiSubwikiListGrouping,
AddonModWikiSubwikiListSubwiki,
AddonModWikiSubwikiPage,
AddonModWikiWiki,
} from '../../services/wiki';
import { AddonModWikiOffline } from '../../services/wiki-offline';
import {
AddonModWikiAutoSyncData,
AddonModWikiSync,
AddonModWikiSyncProvider,
AddonModWikiSyncWikiResult,
AddonModWikiSyncWikiSubwiki,
} from '../../services/wiki-sync';
import { AddonModWikiMapModalComponent, AddonModWikiMapModalReturn } from '../map/map';
import { AddonModWikiSubwikiPickerComponent } from '../subwiki-picker/subwiki-picker';
/**
* Component that displays a wiki entry page.
*/
@Component({
selector: 'addon-mod-wiki-index',
templateUrl: 'addon-mod-wiki-index.html',
styleUrls: ['index.scss'],
})
export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComponent implements OnInit, OnDestroy {
@Input() action?: string;
@Input() pageId?: number;
@Input() pageTitle?: string;
@Input() subwikiId?: number;
@Input() userId?: number;
@Input() groupId?: number;
component = AddonModWikiProvider.COMPONENT;
componentId?: number;
moduleName = 'wiki';
groupWiki = false;
wiki?: AddonModWikiWiki; // The wiki instance.
isMainPage = false; // Whether the user is viewing wiki's main page (just entered the wiki).
canEdit = false; // Whether user can edit the page.
pageStr = '';
pageWarning?: string; // Message telling that the page was discarded.
loadedSubwikis: AddonModWikiSubwiki[] = []; // The loaded subwikis.
pageIsOffline = false; // Whether the loaded page is an offline page.
pageContent?: string; // Page content to display.
tagsEnabled = false;
currentPageObj?: AddonModWikiPageContents | AddonModWikiPageDBRecord; // Object of the current loaded page.
tags: CoreTagItem[] = [];
subwikiData: AddonModWikiSubwikiListData = { // Data for the subwiki selector.
subwikiSelected: 0,
userSelected: 0,
groupSelected: 0,
subwikis: [],
count: 0,
};
protected syncEventName = AddonModWikiSyncProvider.AUTO_SYNCED;
protected currentSubwiki?: AddonModWikiSubwiki; // Current selected subwiki.
protected currentPage?: number; // Current loaded page ID.
protected subwikiPages?: (AddonModWikiSubwikiPage | AddonModWikiPageDBRecord)[]; // List of subwiki pages.
protected newPageObserver?: CoreEventObserver; // Observer to check for new pages.
protected manualSyncObserver?: CoreEventObserver; // An observer to watch for manual sync events.
protected ignoreManualSyncEvent = false; // Whether manual sync event should be ignored.
protected currentUserId?: number; // Current user ID.
protected currentPath!: string;
constructor(
protected content?: IonContent,
@Optional() courseContentsPage?: CoreCourseContentsPage,
) {
super('AddonModLessonIndexComponent', content, courseContentsPage);
}
/**
* @inheritdoc
*/
async ngOnInit(): Promise<void> {
super.ngOnInit();
this.pageStr = Translate.instant('addon.mod_wiki.wikipage');
this.tagsEnabled = CoreTag.areTagsAvailableInSite();
this.currentUserId = CoreSites.getCurrentSiteUserId();
this.isMainPage = !this.pageId && !this.pageTitle;
this.currentPage = this.pageId;
this.currentPath = CoreNavigator.getCurrentPath();
this.listenEvents();
try {
await this.loadContent(false, true);
} finally {
if (this.action == 'map') {
this.openMap();
}
}
if (!this.wiki) {
return;
}
if (!this.pageId) {
try {
await AddonModWiki.logView(this.wiki.id, this.wiki.name);
CoreCourse.checkModuleCompletion(this.courseId, this.module.completiondata);
} catch (error) {
// Ignore errors.
}
} else {
CoreUtils.ignoreErrors(AddonModWiki.logPageView(this.pageId, this.wiki.id, this.wiki.name));
}
}
/**
* Listen to events.
*/
protected listenEvents(): void {
// Listen for manual sync events.
this.manualSyncObserver = CoreEvents.on(AddonModWikiSyncProvider.MANUAL_SYNCED, (data) => {
if (!data || !this.wiki || data.wikiId != this.wiki.id) {
return;
}
if (this.ignoreManualSyncEvent) {
// Event needs to be ignored.
this.ignoreManualSyncEvent = false;
return;
}
if (this.currentSubwiki) {
this.checkPageCreatedOrDiscarded(data.subwikis[this.currentSubwiki.id]);
}
if (!this.pageWarning) {
this.showLoadingAndFetch(false, false);
}
}, this.siteId);
}
/**
* Check if the current page was created or discarded.
*
* @param data Data about created and deleted pages.
*/
protected checkPageCreatedOrDiscarded(data?: AddonModWikiSyncWikiSubwiki): void {
if (this.currentPage || !data) {
return;
}
// This is an offline page. Check if the page was created.
const page = data.created.find((page) => page.title == this.pageTitle);
if (page) {
// Page was created, set the ID so it's retrieved from server.
this.currentPage = page.pageId;
this.pageIsOffline = false;
} else {
// Page not found in created list, check if it was discarded.
const page = data.discarded.find((page) => page.title == this.pageTitle);
if (page) {
// Page discarded, show warning.
this.pageWarning = page.warning;
this.pageContent = '';
this.pageIsOffline = false;
this.hasOffline = false;
}
}
}
/**
* @inheritdoc
*/
protected async fetchContent(refresh: boolean = false, sync: boolean = false, showErrors: boolean = false): Promise<void> {
try {
// Get the wiki instance.
this.wiki = await AddonModWiki.getWiki(this.courseId, this.module.id);
if (this.pageContent === undefined) {
// Page not loaded yet, emit the data to update the page title.
this.dataRetrieved.emit(this.wiki);
}
AddonModWiki.wikiPageOpened(this.wiki.id, this.currentPath);
if (sync) {
// Try to synchronize the wiki.
await CoreUtils.ignoreErrors(this.syncActivity(showErrors));
}
if (this.pageWarning) {
// Page discarded, stop getting data.
return;
}
// Get module instance if it's empty.
if (!this.module.id) {
this.module = await CoreCourse.getModule(this.wiki.coursemodule, this.wiki.course, undefined, true);
}
this.description = this.wiki.intro || this.module.description;
this.externalUrl = this.module.url;
this.componentId = this.module.id;
await this.fetchSubwikis(this.wiki.id);
// Get the subwiki list data from the cache.
const subwikiList = AddonModWiki.getSubwikiList(this.wiki.id);
if (!subwikiList) {
// Not found in cache, create a new one.
// Get real groupmode, in case it's forced by the course.
const groupInfo = await CoreGroups.getActivityGroupInfo(this.wiki.coursemodule);
await this.createSubwikiList(groupInfo.groups);
} else {
this.subwikiData.count = subwikiList.count;
this.setSelectedWiki(this.subwikiId, this.userId, this.groupId);
// If nothing was selected using nav params, use the selected from cache.
if (!this.isAnySubwikiSelected()) {
this.setSelectedWiki(subwikiList.subwikiSelected, subwikiList.userSelected, subwikiList.groupSelected);
}
this.subwikiData.subwikis = subwikiList.subwikis;
}
if (!this.isAnySubwikiSelected() || this.subwikiData.count <= 0) {
throw new CoreError(Translate.instant('addon.mod_wiki.errornowikiavailable'));
}
await this.fetchWikiPage();
} catch (error) {
if (this.pageWarning) {
// Warning is already shown in screen, no need to show a modal.
return;
}
throw error;
} finally {
this.fillContextMenu(refresh);
}
}
/**
* Get wiki page contents.
*
* @param pageId Page to get.
* @return Promise resolved with the page data.
*/
protected async fetchPageContents(pageId: number): Promise<AddonModWikiPageContents>;
protected async fetchPageContents(): Promise<AddonModWikiPageDBRecord | undefined>;
protected async fetchPageContents(pageId?: number): Promise<AddonModWikiPageContents | AddonModWikiPageDBRecord | undefined>;
protected async fetchPageContents(pageId?: number): Promise<AddonModWikiPageContents | AddonModWikiPageDBRecord | undefined> {
if (pageId) {
// Online page.
this.pageIsOffline = false;
return AddonModWiki.getPageContents(pageId, { cmId: this.module.id });
}
// No page ID but we received a title. This means we're trying to load an offline page.
try {
const title = this.pageTitle || this.wiki!.firstpagetitle!;
const offlinePage = await AddonModWikiOffline.getNewPage(
title,
this.currentSubwiki!.id,
this.currentSubwiki!.wikiid,
this.currentSubwiki!.userid,
this.currentSubwiki!.groupid,
);
this.pageIsOffline = true;
if (!this.newPageObserver) {
// It's an offline page, listen for new pages event to detect if the user goes to Edit and submits the page.
this.newPageObserver = CoreEvents.on(AddonModWikiProvider.PAGE_CREATED_EVENT, async (data) => {
if (data.subwikiId != this.currentSubwiki?.id || data.pageTitle != title) {
return;
}
// The page has been submitted. Get the page from the server.
this.currentPage = data.pageId;
// Stop listening for new page events.
this.newPageObserver!.off();
this.newPageObserver = undefined;
await this.showLoadingAndFetch(true, false);
if (this.currentPage) {
CoreUtils.ignoreErrors(AddonModWiki.logPageView(this.currentPage, this.wiki!.id, this.wiki!.name));
}
}, CoreSites.getCurrentSiteId());
}
return offlinePage;
} catch {
// Page not found, ignore.
}
}
/**
* Fetch the list of pages of a subwiki.
*
* @param subwiki Subwiki.
*/
protected async fetchSubwikiPages(subwiki: AddonModWikiSubwiki): Promise<void> {
const subwikiPages = await AddonModWiki.getSubwikiPages(subwiki.wikiid, {
groupId: subwiki.groupid,
userId: subwiki.userid,
cmId: this.module.id,
});
// If no page specified, search first page.
if (!this.currentPage && !this.pageTitle) {
const firstPage = subwikiPages.find((page) => page.firstpage );
if (firstPage) {
this.currentPage = firstPage.id;
this.pageTitle = firstPage.title;
}
}
// Now get the offline pages.
const dbPages = await AddonModWikiOffline.getSubwikiNewPages(subwiki.id, subwiki.wikiid, subwiki.userid, subwiki.groupid);
// If no page specified, search page title in the offline pages.
if (!this.currentPage) {
const searchTitle = this.pageTitle ? this.pageTitle : this.wiki!.firstpagetitle;
const pageExists = dbPages.some((page) => page.title == searchTitle);
if (pageExists) {
this.pageTitle = searchTitle;
}
}
this.subwikiPages = AddonModWiki.sortPagesByTitle(
(<(AddonModWikiSubwikiPage | AddonModWikiPageDBRecord)[]> subwikiPages).concat(dbPages),
);
// Reject if no currentPage selected from the subwikis given (if no subwikis available, do not reject).
if (!this.currentPage && !this.pageTitle && this.subwikiPages.length > 0) {
throw new CoreError();
}
}
/**
* Get the subwikis.
*
* @param wikiId Wiki ID.
*/
protected async fetchSubwikis(wikiId: number): Promise<void> {
this.loadedSubwikis = await AddonModWiki.getSubwikis(wikiId, { cmId: this.module.id });
this.hasOffline = await AddonModWikiOffline.subwikisHaveOfflineData(this.loadedSubwikis);
}
/**
* Fetch the page to be shown.
*
* @return Promise resolved when done.
*/
protected async fetchWikiPage(): Promise<void> {
// Search the current Subwiki.
this.currentSubwiki = this.loadedSubwikis.find((subwiki) => this.isSubwikiSelected(subwiki));
if (!this.currentSubwiki) {
throw new CoreError();
}
this.setSelectedWiki(this.currentSubwiki.id, this.currentSubwiki.userid, this.currentSubwiki.groupid);
await this.fetchSubwikiPages(this.currentSubwiki);
// Check can edit before to have the value if there's no valid page.
this.canEdit = this.currentSubwiki.canedit;
const pageContents = await this.fetchPageContents(this.currentPage);
if (pageContents) {
this.dataRetrieved.emit(pageContents.title);
this.setSelectedWiki(pageContents.subwikiid, pageContents.userid, pageContents.groupid);
this.pageTitle = pageContents.title;
this.pageContent = this.replaceEditLinks(pageContents.cachedcontent);
this.canEdit = !!pageContents.caneditpage;
this.currentPageObj = pageContents;
this.tags = ('tags' in pageContents && pageContents.tags) || [];
}
}
/**
* Get path to the wiki home view. If cannot determine or it's current view, return undefined.
*
* @return The path of the home view
*/
protected getWikiHomeView(): string | undefined {
if (!this.wiki) {
return;
}
return AddonModWiki.getFirstWikiPageOpened(this.wiki.id, this.currentPath);
}
/**
* Open the view to create the first page of the wiki.
*/
protected goToCreateFirstPage(): void {
CoreNavigator.navigateToSitePath(
`${AddonModWikiModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/edit`,
{
params: {
pageTitle: this.wiki!.firstpagetitle,
wikiId: this.currentSubwiki?.wikiid,
userId: this.currentSubwiki?.userid,
groupId: this.currentSubwiki?.groupid,
},
},
);
}
/**
* Open the view to edit the current page.
*/
goToEditPage(): void {
if (!this.canEdit) {
return;
}
if (this.currentPageObj) {
// Current page exists, go to edit it.
const pageParams: Params = {
pageTitle: this.currentPageObj.title,
subwikiId: this.currentPageObj.subwikiid,
};
if ('id' in this.currentPageObj) {
pageParams.pageId = this.currentPageObj.id;
}
if (this.currentSubwiki) {
pageParams.wikiId = this.currentSubwiki.wikiid;
pageParams.userId = this.currentSubwiki.userid;
pageParams.groupId = this.currentSubwiki.groupid;
}
CoreNavigator.navigateToSitePath(
`${AddonModWikiModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/edit`,
{ params: pageParams },
);
} else if (this.currentSubwiki) {
// No page loaded, the wiki doesn't have first page.
this.goToCreateFirstPage();
}
}
/**
* Go to the view to create a new page.
*/
goToNewPage(): void {
if (!this.canEdit) {
return;
}
if (this.currentPageObj) {
// Current page exists, go to edit it.
const pageParams: Params = {
subwikiId: this.currentPageObj.subwikiid,
};
if (this.currentSubwiki) {
pageParams.wikiId = this.currentSubwiki.wikiid;
pageParams.userId = this.currentSubwiki.userid;
pageParams.groupId = this.currentSubwiki.groupid;
}
CoreNavigator.navigateToSitePath(
`${AddonModWikiModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/edit`,
{ params: pageParams },
);
} else if (this.currentSubwiki) {
// No page loaded, the wiki doesn't have first page.
this.goToCreateFirstPage();
}
}
/**
* Go to view a certain page.
*
* @param page Page to view.
*/
protected async goToPage(page: AddonModWikiSubwikiPage | AddonModWikiPageDBRecord): Promise<void> {
if (!('id' in page)) {
// It's an offline page. Check if we are already in the same offline page.
if (this.currentPage || !this.pageTitle || page.title != this.pageTitle) {
this.openPageOrSubwiki({
pageTitle: page.title,
subwikiId: page.subwikiid,
});
}
} else if (this.currentPage != page.id) {
// Add a new State.
const pageContents = await this.fetchPageContents(page.id);
this.openPageOrSubwiki({
pageTitle: pageContents.title,
pageId: pageContents.id,
subwikiId: page.subwikiid,
});
}
}
/**
* Open a page or a subwiki in the current wiki.
*
* @param options Options
* @return Promise.
*/
protected async openPageOrSubwiki(options: AddonModWikiOpenPageOptions): Promise<void> {
const hash = <string> Md5.hashAsciiStr(JSON.stringify({
...options,
timestamp: Date.now(),
}));
CoreNavigator.navigateToSitePath(
`${AddonModWikiModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/page/${hash}`,
{
params: {
module: this.module,
...options,
},
},
);
}
/**
* Show the map.
*/
async openMap(): Promise<void> {
// Create the toc modal.
const modalData = await CoreDomUtils.openSideModal<AddonModWikiMapModalReturn>({
component: AddonModWikiMapModalComponent,
componentProps: {
pages: this.subwikiPages,
homeView: this.getWikiHomeView(),
moduleId: this.module.id,
courseId: this.courseId,
selectedTitle: this.currentPageObj && this.currentPageObj.title,
},
});
if (modalData) {
if (modalData.home) {
// Go back to the initial page of the wiki.
CoreNavigator.navigateToSitePath(modalData.home, { animationDirection: 'back' });
} else if (modalData.page) {
this.goToPage(modalData.page);
}
}
}
/**
* Go to the page to view a certain subwiki.
*
* @param subwikiId Subwiki ID.
* @param userId User ID of the subwiki.
* @param groupId Group ID of the subwiki.
* @param canEdit Whether the subwiki can be edited.
*/
goToSubwiki(subwikiId: number, userId: number, groupId: number, canEdit: boolean): void {
// Check if the subwiki is disabled.
if (subwikiId <= 0 && !canEdit) {
return;
}
if (subwikiId != this.currentSubwiki!.id || userId != this.currentSubwiki!.userid ||
groupId != this.currentSubwiki!.groupid) {
this.openPageOrSubwiki({
subwikiId: subwikiId,
userId: userId,
groupId: groupId,
});
}
}
/**
* Checks if there is any subwiki selected.
*
* @return Whether there is any subwiki selected.
*/
protected isAnySubwikiSelected(): boolean {
return this.subwikiData.subwikiSelected > 0 || this.subwikiData.userSelected > 0 || this.subwikiData.groupSelected > 0;
}
/**
* Checks if the given subwiki is the one picked on the subwiki picker.
*
* @param subwiki Subwiki to check.
* @return Whether it's the selected subwiki.
*/
protected isSubwikiSelected(subwiki: AddonModWikiSubwiki): boolean {
if (subwiki.id > 0 && this.subwikiData.subwikiSelected > 0) {
return subwiki.id == this.subwikiData.subwikiSelected;
}
return subwiki.userid == this.subwikiData.userSelected && subwiki.groupid == this.subwikiData.groupSelected;
}
/**
* Replace edit links to have full url.
*
* @param content Content to treat.
* @return Treated content.
*/
protected replaceEditLinks(content: string): string {
content = content.trim();
if (content.length > 0) {
const editUrl = CoreTextUtils.concatenatePaths(CoreSites.getCurrentSite()!.getURL(), '/mod/wiki/edit.php');
content = content.replace(/href="edit\.php/g, 'href="' + editUrl);
}
return content;
}
/**
* Sets the selected subwiki for the subwiki picker.
*
* @param subwikiId Subwiki ID to select.
* @param userId User ID of the subwiki to select.
* @param groupId Group ID of the subwiki to select.
*/
protected setSelectedWiki(subwikiId: number | undefined, userId: number | undefined, groupId: number | undefined): void {
this.subwikiData.subwikiSelected = AddonModWikiOffline.convertToPositiveNumber(subwikiId);
this.subwikiData.userSelected = AddonModWikiOffline.convertToPositiveNumber(userId);
this.subwikiData.groupSelected = AddonModWikiOffline.convertToPositiveNumber(groupId);
}
/**
* Checks if sync has succeed from result sync data.
*
* @param result Data returned on the sync function.
* @return If suceed or not.
*/
protected hasSyncSucceed(result: AddonModWikiSyncWikiResult): boolean {
if (result.updated) {
// Trigger event.
this.ignoreManualSyncEvent = true;
CoreEvents.trigger(AddonModWikiSyncProvider.MANUAL_SYNCED, {
...result,
wikiId: this.wiki!.id,
});
}
if (this.currentSubwiki) {
this.checkPageCreatedOrDiscarded(result.subwikis[this.currentSubwiki.id]);
}
return result.updated;
}
/**
* User entered the page that contains the component.
*/
ionViewDidEnter(): void {
super.ionViewDidEnter();
const editedPageData = AddonModWiki.consumeEditedPageData();
if (!editedPageData) {
return;
}
// User has just edited a page. Check if it's the current page.
if (this.pageId && editedPageData.pageId === this.pageId) {
this.showLoadingAndRefresh(true, false);
return;
}
const sameSubwiki = this.currentSubwiki &&
((this.currentSubwiki.id && this.currentSubwiki.id === editedPageData.subwikiId) ||
(this.currentSubwiki.userid === editedPageData.userId && this.currentSubwiki.groupid === editedPageData.groupId));
if (sameSubwiki && editedPageData.pageTitle === this.pageTitle) {
this.showLoadingAndRefresh(true, false);
return;
}
// Not same page or we cannot tell. Open the page.
this.openPageOrSubwiki({
pageId: editedPageData.pageId,
pageTitle: editedPageData.pageTitle,
subwikiId: editedPageData.subwikiId,
userId: editedPageData.wikiId,
groupId: editedPageData.groupId,
});
if (editedPageData.pageId && (!this.pageContent || this.pageContent.indexOf('/mod/wiki/create.php') != -1)) {
// Refresh current page anyway because the new page could have been created using the create link.
this.showLoadingAndRefresh(true, false);
}
}
/**
* @inheritdoc
*/
protected async invalidateContent(): Promise<void> {
const promises: Promise<void>[] = [];
promises.push(AddonModWiki.invalidateWikiData(this.courseId));
if (this.wiki) {
promises.push(AddonModWiki.invalidateSubwikis(this.wiki.id));
promises.push(CoreGroups.invalidateActivityAllowedGroups(this.wiki.coursemodule));
promises.push(CoreGroups.invalidateActivityGroupMode(this.wiki.coursemodule));
}
if (this.currentSubwiki) {
promises.push(AddonModWiki.invalidateSubwikiPages(this.currentSubwiki.wikiid));
promises.push(AddonModWiki.invalidateSubwikiFiles(this.currentSubwiki.wikiid));
}
if (this.currentPage) {
promises.push(AddonModWiki.invalidatePage(this.currentPage));
}
await Promise.all(promises);
}
/**
* @inheritdoc
*/
protected isRefreshSyncNeeded(syncEventData: AddonModWikiAutoSyncData): boolean {
if (this.currentSubwiki && syncEventData.subwikiId == this.currentSubwiki.id &&
syncEventData.wikiId == this.currentSubwiki.wikiid && syncEventData.userId == this.currentSubwiki.userid &&
syncEventData.groupId == this.currentSubwiki.groupid) {
if (this.isCurrentView && syncEventData.warnings && syncEventData.warnings.length) {
// Show warnings.
CoreDomUtils.showErrorModal(syncEventData.warnings[0]);
}
// Check if current page was created or discarded.
this.checkPageCreatedOrDiscarded(syncEventData);
}
return !this.pageWarning;
}
/**
* Show the TOC.
*
* @param event Event.
*/
async showSubwikiPicker(event: MouseEvent): Promise<void> {
const popoverData = await CoreDomUtils.openPopover<AddonModWikiSubwiki>({
component: AddonModWikiSubwikiPickerComponent,
componentProps: {
subwikis: this.subwikiData.subwikis,
currentSubwiki: this.currentSubwiki,
},
event,
});
if (popoverData) {
this.goToSubwiki(popoverData.id, popoverData.userid, popoverData.groupid, popoverData.canedit);
}
}
/**
* Performs the sync of the activity.
*
* @return Promise resolved when done.
*/
protected sync(): Promise<AddonModWikiSyncWikiResult> {
return AddonModWikiSync.syncWiki(this.wiki!.id, this.courseId, this.wiki!.coursemodule);
}
/**
* Component being destroyed.
*/
ngOnDestroy(): void {
super.ngOnDestroy();
this.manualSyncObserver?.off();
this.newPageObserver?.off();
if (this.wiki) {
AddonModWiki.wikiPageClosed(this.wiki.id, this.currentPath);
}
}
/**
* Create the subwiki list for the selector and store it in the cache.
*
* @param userGroups Groups.
* @return Promise resolved when done.
*/
protected async createSubwikiList(userGroups?: CoreGroup[]): Promise<void> {
const subwikiList: AddonModWikiSubwikiListSubwiki[] = [];
let allParticipants = false;
let showMyGroupsLabel = false;
let multiLevelList = false;
this.subwikiData.subwikis = [];
this.setSelectedWiki(this.subwikiId, this.userId, this.groupId);
this.subwikiData.count = 0;
// Add the subwikis to the subwikiList.
await Promise.all(this.loadedSubwikis.map(async (subwiki) => {
let groupLabel = '';
if (subwiki.groupid == 0 && subwiki.userid == 0) {
// Add 'All participants' subwiki if needed at the start.
if (!allParticipants) {
subwikiList.unshift({
name: Translate.instant('core.allparticipants'),
id: subwiki.id,
userid: subwiki.userid,
groupid: subwiki.groupid,
groupLabel: '',
canedit: subwiki.canedit,
});
allParticipants = true;
}
} else {
if (subwiki.groupid != 0 && userGroups && userGroups.length > 0) {
// Get groupLabel if it has groupId.
const group = userGroups.find(group => group.id == subwiki.groupid);
groupLabel = group?.name || '';
} else {
groupLabel = Translate.instant('addon.mod_wiki.notingroup');
}
if (subwiki.userid != 0) {
if (!multiLevelList && subwiki.groupid != 0) {
multiLevelList = true;
}
// Get user if it has userId.
const user = await CoreUser.getProfile(subwiki.userid, this.courseId, true);
subwikiList.push({
name: user.fullname,
id: subwiki.id,
userid: subwiki.userid,
groupid: subwiki.groupid,
groupLabel: groupLabel,
canedit: subwiki.canedit,
});
} else {
subwikiList.push({
name: groupLabel,
id: subwiki.id,
userid: subwiki.userid,
groupid: subwiki.groupid,
groupLabel: groupLabel,
canedit: subwiki.canedit,
});
showMyGroupsLabel = true;
}
}
}));
this.fillSubwikiData(subwikiList, showMyGroupsLabel, multiLevelList);
}
/**
* Fill the subwiki data.
*
* @param subwikiList List of subwikis.
* @param showMyGroupsLabel Whether subwikis should be grouped in "My groups" and "Other groups".
* @param multiLevelList Whether it's a multi level list.
*/
protected fillSubwikiData(
subwikiList: AddonModWikiSubwikiListSubwiki[],
showMyGroupsLabel: boolean,
multiLevelList: boolean,
): void {
subwikiList.sort((a, b) => a.groupid - b.groupid);
this.groupWiki = showMyGroupsLabel;
this.subwikiData.count = subwikiList.length;
// If no subwiki is received as view param, select always the most appropiate.
if ((!this.subwikiId || (!this.userId && !this.groupId)) && !this.isAnySubwikiSelected() && subwikiList.length > 0) {
let firstCanEdit: number | undefined;
let candidateNoFirstPage: number | undefined;
let candidateFirstPage: number | undefined;
for (const i in subwikiList) {
const subwiki = subwikiList[i];
if (subwiki.canedit) {
let candidateSubwikiId: number | undefined;
if (subwiki.userid > 0) {
// Check if it's the current user.
if (this.currentUserId == subwiki.userid) {
candidateSubwikiId = subwiki.id;
}
} else if (subwiki.groupid > 0) {
// Check if it's a current user' group.
if (showMyGroupsLabel) {
candidateSubwikiId = subwiki.id;
}
} else if (subwiki.id > 0) {
candidateSubwikiId = subwiki.id;
}
if (typeof candidateSubwikiId != 'undefined') {
if (candidateSubwikiId > 0) {
// Subwiki found and created, no need to keep looking.
candidateFirstPage = Number(i);
break;
} else if (typeof candidateNoFirstPage == 'undefined') {
candidateNoFirstPage = Number(i);
}
} else if (typeof firstCanEdit == 'undefined') {
firstCanEdit = Number(i);
}
}
}
let subWikiToTake: number;
if (typeof candidateFirstPage != 'undefined') {
// Take the candidate that already has the first page created.
subWikiToTake = candidateFirstPage;
} else if (typeof candidateNoFirstPage != 'undefined') {
// No first page created, take the first candidate.
subWikiToTake = candidateNoFirstPage;
} else if (typeof firstCanEdit != 'undefined') {
// None selected, take the first the user can edit.
subWikiToTake = firstCanEdit;
} else {
// Otherwise take the very first.
subWikiToTake = 0;
}
const subwiki = subwikiList[subWikiToTake];
if (typeof subwiki != 'undefined') {
this.setSelectedWiki(subwiki.id, subwiki.userid, subwiki.groupid);
}
}
if (multiLevelList) {
// As we loop over each subwiki, add it to the current group
let groupValue = -1;
let grouping: AddonModWikiSubwikiListGrouping;
subwikiList.forEach((subwiki) => {
// Should we create a new grouping?
if (subwiki.groupid !== groupValue) {
grouping = { label: subwiki.groupLabel, subwikis: [] };
groupValue = subwiki.groupid;
this.subwikiData.subwikis.push(grouping);
}
// Add the subwiki to the currently active grouping.
grouping.subwikis.push(subwiki);
});
} else if (showMyGroupsLabel) {
const noGrouping: AddonModWikiSubwikiListGrouping = { label: '', subwikis: [] };
const myGroupsGrouping: AddonModWikiSubwikiListGrouping = { label: Translate.instant('core.mygroups'), subwikis: [] };
const otherGroupsGrouping: AddonModWikiSubwikiListGrouping = {
label: Translate.instant('core.othergroups'),
subwikis: [],
};
// As we loop over each subwiki, add it to the current group
subwikiList.forEach((subwiki) => {
// Add the subwiki to the currently active grouping.
if (typeof subwiki.canedit == 'undefined') {
noGrouping.subwikis.push(subwiki);
} else if (subwiki.canedit) {
myGroupsGrouping.subwikis.push(subwiki);
} else {
otherGroupsGrouping.subwikis.push(subwiki);
}
});
// Add each grouping to the subwikis
if (noGrouping.subwikis.length > 0) {
this.subwikiData.subwikis.push(noGrouping);
}
if (myGroupsGrouping.subwikis.length > 0) {
this.subwikiData.subwikis.push(myGroupsGrouping);
}
if (otherGroupsGrouping.subwikis.length > 0) {
this.subwikiData.subwikis.push(otherGroupsGrouping);
}
} else {
this.subwikiData.subwikis.push({ label: '', subwikis: subwikiList });
}
AddonModWiki.setSubwikiList(
this.wiki!.id,
this.subwikiData.subwikis,
this.subwikiData.count,
this.subwikiData.subwikiSelected,
this.subwikiData.userSelected,
this.subwikiData.groupSelected,
);
}
}
type AddonModWikiOpenPageOptions = {
subwikiId?: number;
pageTitle?: string;
pageId?: number;
userId?: number;
groupId?: number;
}; | the_stack |
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { Directive, Input } from '@angular/core';
import { FormsModule } from '@angular/forms';
import * as sinon from 'sinon';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs/Rx';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { IssueIdentityComponent } from './issue-identity.component';
import { AlertService } from '../../basic-modals/alert.service';
import { ClientService } from '../../services/client.service';
import { BusinessNetworkConnection } from 'composer-client';
import { Resource } from 'composer-common';
@Directive({
selector: '[ngbTypeahead]'
})
class MockTypeaheadDirective {
@Input()
public ngbTypeahead: any;
@Input()
public resultTemplate: any;
}
describe('IssueIdentityComponent', () => {
let component: IssueIdentityComponent;
let fixture: ComponentFixture<IssueIdentityComponent>;
let mockClientService;
let mockBusinessNetworkConnection;
let mockAlertService;
let mockActiveModal;
beforeEach(() => {
mockBusinessNetworkConnection = sinon.createStubInstance(BusinessNetworkConnection);
mockActiveModal = sinon.createStubInstance(NgbActiveModal);
let mockBehaviourSubject = sinon.createStubInstance(BehaviorSubject);
mockBehaviourSubject.next = sinon.stub();
mockAlertService = sinon.createStubInstance(AlertService);
mockAlertService.errorStatus$ = mockBehaviourSubject;
mockAlertService.busyStatus$ = mockBehaviourSubject;
mockAlertService.successStatus$ = mockBehaviourSubject;
mockClientService = sinon.createStubInstance(ClientService);
TestBed.configureTestingModule({
// TODO mock imports?
imports: [FormsModule],
declarations: [
IssueIdentityComponent,
MockTypeaheadDirective
],
providers: [
{provide: NgbActiveModal, useValue: mockActiveModal},
{provide: AlertService, useValue: mockAlertService},
{provide: ClientService, useValue: mockClientService}
]
})
.compileComponents();
fixture = TestBed.createComponent(IssueIdentityComponent);
component = fixture.componentInstance;
});
it('should be created', () => {
expect(component).should.be.ok;
});
describe('#ngOnInit', () => {
it('should loadParticpants on init', fakeAsync(() => {
let mockLoadParticipants = sinon.stub(component, 'loadParticipants');
// Run method
component['ngOnInit']();
tick();
mockLoadParticipants.should.have.been.called;
}));
});
describe('#loadParticipants', () => {
it('should create a sorted list of participantFQIs', fakeAsync(() => {
let mockParticipant1 = sinon.createStubInstance(Resource);
mockParticipant1.getFullyQualifiedIdentifier.returns('org.animals.Penguin#Emperor');
mockParticipant1.getIdentifier.returns('Emperor');
mockParticipant1.getType.returns('org.animals.Penguin');
let mockParticipant2 = sinon.createStubInstance(Resource);
mockParticipant2.getFullyQualifiedIdentifier.returns('org.animals.Penguin#King');
mockParticipant2.getIdentifier.returns('King');
mockParticipant2.getType.returns('org.animals.Penguin');
let mockParticipant3 = sinon.createStubInstance(Resource);
mockParticipant3.getFullyQualifiedIdentifier.returns('org.animals.Penguin#Macaroni');
mockParticipant3.getIdentifier.returns('Macaroni');
mockParticipant3.getType.returns('org.animals.Penguin');
component['participants'].set('Emperor', mockParticipant1);
component['participants'].set('King', mockParticipant2);
component['participants'].set('Macaroni', mockParticipant2);
component['loadParticipants']();
let expected = ['Emperor', 'King', 'Macaroni'];
component['participantFQIs'].should.deep.equal(expected);
}));
});
describe('#search', () => {
it('should provide search ahead for blank text', fakeAsync(() => {
// add FQIs to test against
component['participantFQIs'] = ['goat', 'giraffe', 'elephant'];
// mock teXt
let text$ = new Observable<string>((observer) => {
// pushing values
observer.next('');
// complete stream
observer.complete();
});
// run method
let result = component['search'](text$);
// perform test inside promise
result.toPromise().then((output) => {
// we should have goat, girrafe, but no elephant
let expected = [];
output.should.deep.equal(expected);
});
}));
it('should provide search ahead for existing ids that match', fakeAsync(() => {
// add FQIs to test against
component['participantFQIs'] = ['goat', 'giraffe', 'elephant'];
// mock teXt
let text$ = new Observable<string>((observer) => {
// pushing values
observer.next('g');
// complete stream
observer.complete();
});
// run method
let result = component['search'](text$);
// perform test inside promise
result.toPromise().then((output) => {
// we should have goat, girrafe, but no elephant
let expected = ['goat', 'giraffe'];
output.should.deep.equal(expected);
});
}));
});
describe('#issueIdentity', () => {
it('should generate and return an identity using internally held state information with partially qualified name', fakeAsync(() => {
mockClientService.issueIdentity.returns(Promise.resolve({
participant: 'uniqueName',
userID: 'userId',
options: {issuer: false, affiliation: undefined}
}));
component['participantFQI'] = 'uniqueName';
component['userID'] = 'userId';
component['issueIdentity']();
tick();
// What was it called with
mockClientService.issueIdentity.should.have.been.calledWith('userId', 'resource:uniqueName', {issuer: false, affiliation: undefined});
// Did we return the expected result to the modal on close
let expected = {
participant: 'uniqueName',
userID: 'userId',
options: {issuer: false, affiliation: undefined}
};
mockActiveModal.close.should.be.calledWith(expected);
}));
it('should generate and return an identity using internally held state information with fully qualified name', fakeAsync(() => {
mockClientService.issueIdentity.returns(Promise.resolve({
participant: 'uniqueName',
userID: 'userId',
options: {issuer: false, affiliation: undefined}
}));
component['participantFQI'] = 'resource:uniqueName';
component['userID'] = 'userId';
component['issueIdentity']();
tick();
// What was it called with
mockClientService.issueIdentity.should.have.been.calledWith('userId', 'resource:uniqueName', {issuer: false, affiliation: undefined});
// Did we return the expected result to the modal on close
let expected = {
participant: 'uniqueName',
userID: 'userId',
options: {issuer: false, affiliation: undefined}
};
mockActiveModal.close.should.be.calledWith(expected);
}));
it('should dismiss modal and pass error on failure', fakeAsync(() => {
mockClientService.issueIdentity.returns(Promise.reject('some error'));
component['participantFQI'] = 'uniqueName';
component['issueIdentity']();
tick();
// Check we error
mockActiveModal.dismiss.should.be.calledWith('some error');
}));
});
describe('#isValidParticipant', () => {
it('should set valid if empty string', () => {
component['participantFQI'] = '';
component['isParticipant'] = false;
component.isValidParticipant();
component['isParticipant'].should.be.true;
});
it('should set valid if particpant exists when prepended with `resource:`', () => {
let p1 = new Resource('resource1');
let p2 = new Resource('resource2');
component['participants'].set('bob', p1);
component['participants'].set('sally', p2);
component['participantFQI'] = 'resource:bob';
component['isParticipant'] = false;
component.isValidParticipant();
component['isParticipant'].should.be.true;
});
it('should set valid if particpant exists when not prepended with `resource:`', () => {
let p1 = new Resource('resource1');
let p2 = new Resource('resource2');
component['participants'].set('bob', p1);
component['participants'].set('sally', p2);
component['participantFQI'] = 'sally';
component['isParticipant'] = false;
component.isValidParticipant();
component['isParticipant'].should.be.true;
});
it('should set invalid if not empty string and participant does not exist', () => {
component['participantFQI'] = 'not-person';
let mockGet = sinon.stub(component, 'getParticipant');
mockGet.returns(false);
component['isParticipant'] = true;
component.isValidParticipant();
component['isParticipant'].should.be.false;
});
});
describe('#getParticipant', () => {
it('should get the specified participant', () => {
let mockParticipant1 = sinon.createStubInstance(Resource);
mockParticipant1.getFullyQualifiedIdentifier.returns('org.doge.Doge#DOGE_1');
mockParticipant1.getIdentifier.returns('DOGE_1');
mockParticipant1.getType.returns('org.doge.Doge');
let mockParticipant2 = sinon.createStubInstance(Resource);
mockParticipant2.getFullyQualifiedIdentifier.returns('org.doge.Doge#DOGE_2');
mockParticipant2.getIdentifier.returns('DOGE_2');
mockParticipant2.getType.returns('org.doge.Doge');
let mockParticipant3 = sinon.createStubInstance(Resource);
mockParticipant3.getFullyQualifiedIdentifier.returns('org.doge.Doge#DOGE_3');
mockParticipant3.getIdentifier.returns('DOGE_3');
mockParticipant3.getType.returns('org.doge.Doge');
component['participants'].set('DOGE_1', mockParticipant1);
component['participants'].set('DOGE_2', mockParticipant2);
let participant = component['getParticipant']('DOGE_2');
participant.getIdentifier().should.equal('DOGE_2');
participant.getType().should.equal('org.doge.Doge');
});
});
}); | the_stack |
import {SUM_OPS} from 'vega-lite/build/src/aggregate';
import * as CHANNEL from 'vega-lite/build/src/channel';
import {NONPOSITION_CHANNELS, supportMark} from 'vega-lite/build/src/channel';
import * as MARK from 'vega-lite/build/src/mark';
import {Mark} from 'vega-lite/build/src/mark';
import {ScaleType} from 'vega-lite/build/src/scale';
import * as TYPE from 'vega-lite/build/src/type';
import {QueryConfig} from '../config';
import {SpecQueryModel} from '../model';
import {getEncodingNestedProp, isEncodingNestedProp, isEncodingProperty, Property} from '../property';
import {PropIndex} from '../propindex';
import {
EncodingQuery,
FieldQuery,
isAutoCountQuery,
isDimension,
isDisabledAutoCountQuery,
isEnabledAutoCountQuery,
isFieldQuery,
isMeasure,
isValueQuery,
ScaleQuery,
scaleType,
} from '../query/encoding';
import {ExpandedType} from '../query/expandedtype';
import {Schema} from '../schema';
import {contains, every, some} from '../util';
import {isWildcard, Wildcard} from '../wildcard';
import {AbstractConstraint, AbstractConstraintModel} from './base';
const NONPOSITION_CHANNELS_INDEX = NONPOSITION_CHANNELS.reduce((m, channel) => {
m[channel] = true;
return m;
}, {});
export interface SpecConstraintChecker {
(specM: SpecQueryModel, schema: Schema, opt: QueryConfig): boolean;
}
export class SpecConstraintModel extends AbstractConstraintModel {
constructor(specConstraint: SpecConstraint) {
super(specConstraint);
}
public hasAllRequiredPropertiesSpecific(specM: SpecQueryModel): boolean {
return every(this.constraint.properties, (prop) => {
if (prop === Property.MARK) {
return !isWildcard(specM.getMark());
}
// TODO: transform
if (isEncodingNestedProp(prop)) {
const parent = prop.parent;
const child = prop.child;
return every(specM.getEncodings(), (encQ) => {
if (!encQ[parent]) {
return true;
}
return !isWildcard(encQ[parent][child]);
});
}
if (!isEncodingProperty(prop)) {
throw new Error('UNIMPLEMENTED');
}
return every(specM.getEncodings(), (encQ) => {
if (!encQ[prop]) {
return true;
}
return !isWildcard(encQ[prop]);
});
});
}
public satisfy(specM: SpecQueryModel, schema: Schema, opt: QueryConfig) {
// TODO: Re-order logic to optimize the "allowWildcardForProperties" check
if (!this.constraint.allowWildcardForProperties) {
if (!this.hasAllRequiredPropertiesSpecific(specM)) {
return true;
}
}
return (this.constraint as SpecConstraint).satisfy(specM, schema, opt);
}
}
export interface SpecConstraint extends AbstractConstraint {
/** Method for checking if the spec query satisfies this constraint. */
satisfy: SpecConstraintChecker;
}
export const SPEC_CONSTRAINTS: SpecConstraintModel[] = [
{
name: 'noRepeatedChannel',
description: 'Each encoding channel should only be used once.',
properties: [Property.CHANNEL],
allowWildcardForProperties: true,
strict: true,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
const usedChannel = {};
// channel for all encodings should be valid
return every(specM.getEncodings(), (encQ) => {
if (!isWildcard(encQ.channel)) {
// If channel is specified, it should no be used already
if (usedChannel[encQ.channel]) {
return false;
}
usedChannel[encQ.channel] = true;
return true;
}
return true; // unspecified channel is valid
});
},
},
{
name: 'alwaysIncludeZeroInScaleWithBarMark',
description: 'Do not recommend bar mark if scale does not start at zero',
properties: [
Property.MARK,
Property.SCALE,
getEncodingNestedProp('scale', 'zero'),
Property.CHANNEL,
Property.TYPE,
],
allowWildcardForProperties: false,
strict: true,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
const mark = specM.getMark();
const encodings = specM.getEncodings();
if (mark === MARK.BAR) {
for (const encQ of encodings) {
if (
isFieldQuery(encQ) &&
(encQ.channel === CHANNEL.X || encQ.channel === CHANNEL.Y) &&
encQ.type === TYPE.QUANTITATIVE &&
encQ.scale &&
(encQ.scale as ScaleQuery).zero === false
) {
// TODO: zero shouldn't be manually specified
return false;
}
}
}
return true;
},
},
{
name: 'autoAddCount',
description:
'Automatically adding count only for plots with only ordinal, binned quantitative, or temporal with timeunit fields.',
properties: [Property.BIN, Property.TIMEUNIT, Property.TYPE, Property.AUTOCOUNT],
allowWildcardForProperties: true,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
const hasAutoCount = some(specM.getEncodings(), (encQ: EncodingQuery) => isEnabledAutoCountQuery(encQ));
if (hasAutoCount) {
// Auto count should only be applied if all fields are nominal, ordinal, temporal with timeUnit, binned quantitative, or autoCount
return every(specM.getEncodings(), (encQ: EncodingQuery) => {
if (isValueQuery(encQ)) {
return true;
}
if (isAutoCountQuery(encQ)) {
return true;
}
switch (encQ.type) {
case TYPE.QUANTITATIVE:
return !!encQ.bin;
case TYPE.TEMPORAL:
return !!encQ.timeUnit;
case TYPE.ORDINAL:
case ExpandedType.KEY:
case TYPE.NOMINAL:
return true;
}
/* istanbul ignore next */
throw new Error('Unsupported Type');
});
} else {
const autoCountEncIndex = specM.wildcardIndex.encodingIndicesByProperty.get('autoCount') || [];
const neverHaveAutoCount = every(autoCountEncIndex, (index: number) => {
const encQ = specM.getEncodingQueryByIndex(index);
return isAutoCountQuery(encQ) && !isWildcard(encQ.autoCount);
});
if (neverHaveAutoCount) {
// If the query surely does not have autoCount
// then one of the field should be
// (1) unbinned quantitative
// (2) temporal without time unit
// (3) nominal or ordinal field
// or at least have potential to be (still ambiguous).
return some(specM.getEncodings(), (encQ: EncodingQuery) => {
if ((isFieldQuery(encQ) || isAutoCountQuery(encQ)) && encQ.type === TYPE.QUANTITATIVE) {
if (isDisabledAutoCountQuery(encQ)) {
return false;
} else {
return isFieldQuery(encQ) && (!encQ.bin || isWildcard(encQ.bin));
}
} else if (isFieldQuery(encQ) && encQ.type === TYPE.TEMPORAL) {
return !encQ.timeUnit || isWildcard(encQ.timeUnit);
}
return false; // nominal or ordinal
});
}
}
return true; // no auto count, no constraint
},
},
{
name: 'channelPermittedByMarkType',
description: 'Each encoding channel should be supported by the mark type',
properties: [Property.CHANNEL, Property.MARK],
allowWildcardForProperties: true, // only require mark
strict: true,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
const mark = specM.getMark();
// if mark is unspecified, no need to check
if (isWildcard(mark)) return true;
// TODO: can optimize this to detect only what's the changed property if needed.
return every(specM.getEncodings(), (encQ) => {
// channel unspecified, no need to check
if (isWildcard(encQ.channel)) return true;
if (encQ.channel === 'row' || encQ.channel === 'column' || encQ.channel === 'facet') return true;
return !!supportMark(encQ.channel, mark as Mark);
});
},
},
{
name: 'hasAllRequiredChannelsForMark',
description: 'All required channels for the specified mark should be specified',
properties: [Property.CHANNEL, Property.MARK],
allowWildcardForProperties: false,
strict: true,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
const mark = specM.getMark();
switch (mark) {
case MARK.AREA:
case MARK.LINE:
return specM.channelUsed(CHANNEL.X) && specM.channelUsed(CHANNEL.Y);
case MARK.TEXT:
return specM.channelUsed(CHANNEL.TEXT);
case MARK.BAR:
case MARK.CIRCLE:
case MARK.SQUARE:
case MARK.TICK:
case MARK.RULE:
case MARK.RECT:
return specM.channelUsed(CHANNEL.X) || specM.channelUsed(CHANNEL.Y);
case MARK.POINT:
// This allows generating a point plot if channel was not a wildcard.
return (
!specM.wildcardIndex.hasProperty(Property.CHANNEL) ||
specM.channelUsed(CHANNEL.X) ||
specM.channelUsed(CHANNEL.Y)
);
}
/* istanbul ignore next */
throw new Error(`hasAllRequiredChannelsForMark not implemented for mark${JSON.stringify(mark)}`);
},
},
{
name: 'omitAggregate',
description: 'Omit aggregate plots.',
properties: [Property.AGGREGATE, Property.AUTOCOUNT],
allowWildcardForProperties: true,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
if (specM.isAggregate()) {
return false;
}
return true;
},
},
{
name: 'omitAggregatePlotWithDimensionOnlyOnFacet',
description: 'Omit aggregate plots with dimensions only on facets as that leads to inefficient use of space.',
properties: [Property.CHANNEL, Property.AGGREGATE, Property.AUTOCOUNT],
allowWildcardForProperties: false,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, opt: QueryConfig) => {
if (specM.isAggregate()) {
let hasNonFacetDim = false;
let hasDim = false;
let hasEnumeratedFacetDim = false;
specM.specQuery.encodings.forEach((encQ, index) => {
if (isValueQuery(encQ) || isDisabledAutoCountQuery(encQ)) return; // skip unused field
// FieldQuery & !encQ.aggregate
if (isFieldQuery(encQ) && !encQ.aggregate) {
// isDimension
hasDim = true;
if (contains([CHANNEL.ROW, CHANNEL.COLUMN], encQ.channel)) {
if (specM.wildcardIndex.hasEncodingProperty(index, Property.CHANNEL)) {
hasEnumeratedFacetDim = true;
}
} else {
hasNonFacetDim = true;
}
}
});
if (hasDim && !hasNonFacetDim) {
if (hasEnumeratedFacetDim || opt.constraintManuallySpecifiedValue) {
return false;
}
}
}
return true;
},
},
{
name: 'omitAggregatePlotWithoutDimension',
description: 'Aggregate plots without dimension should be omitted',
properties: [Property.AGGREGATE, Property.AUTOCOUNT, Property.BIN, Property.TIMEUNIT, Property.TYPE],
allowWildcardForProperties: false,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
if (specM.isAggregate()) {
// TODO relax
return some(specM.getEncodings(), (encQ: EncodingQuery) => {
if (isDimension(encQ) || (isFieldQuery(encQ) && encQ.type === 'temporal')) {
return true;
}
return false;
});
}
return true;
},
},
{
// TODO: we can be smarter and check if bar has occlusion based on profiling statistics
name: 'omitBarLineAreaWithOcclusion',
description: "Don't use bar, line or area to visualize raw plot as they often lead to occlusion.",
properties: [Property.MARK, Property.AGGREGATE, Property.AUTOCOUNT],
allowWildcardForProperties: false,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
if (contains([MARK.BAR, MARK.LINE, MARK.AREA], specM.getMark())) {
return specM.isAggregate();
}
return true;
},
},
{
name: 'omitBarTickWithSize',
description: 'Do not map field to size channel with bar and tick mark',
properties: [Property.CHANNEL, Property.MARK],
allowWildcardForProperties: true,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, opt: QueryConfig) => {
const mark = specM.getMark();
if (contains([MARK.TICK, MARK.BAR], mark)) {
if (specM.channelEncodingField(CHANNEL.SIZE)) {
if (opt.constraintManuallySpecifiedValue) {
// If size is used and we constraintManuallySpecifiedValue,
// then the spec violates this constraint.
return false;
} else {
// Otherwise have to search for the size channel and check if it is enumerated
const encodings = specM.specQuery.encodings;
for (let i = 0; i < encodings.length; i++) {
const encQ = encodings[i];
if (encQ.channel === CHANNEL.SIZE) {
if (specM.wildcardIndex.hasEncodingProperty(i, Property.CHANNEL)) {
// If enumerated, then this is bad
return false;
} else {
// If it's manually specified, no need to continue searching, just return.
return true;
}
}
}
}
}
}
return true; // skip
},
},
{
name: 'omitBarAreaForLogScale',
description: "Do not use bar and area mark for x and y's log scale",
properties: [
Property.MARK,
Property.CHANNEL,
Property.SCALE,
getEncodingNestedProp('scale', 'type'),
Property.TYPE,
],
allowWildcardForProperties: false,
strict: true,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
const mark = specM.getMark();
const encodings = specM.getEncodings();
// TODO: mark or scale type should be enumerated
if (mark === MARK.AREA || mark === MARK.BAR) {
for (const encQ of encodings) {
if (isFieldQuery(encQ) && (encQ.channel === CHANNEL.X || encQ.channel === CHANNEL.Y) && encQ.scale) {
const sType = scaleType(encQ);
if (sType === ScaleType.LOG) {
return false;
}
}
}
}
return true;
},
},
{
name: 'omitMultipleNonPositionalChannels',
description:
'Unless manually specified, do not use multiple non-positional encoding channel to avoid over-encoding.',
properties: [Property.CHANNEL],
allowWildcardForProperties: true,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, opt: QueryConfig) => {
// have to use specM.specQuery.encodings insetad of specM.getEncodings()
// since specM.getEncodings() remove encQ with autoCount===false from the array
// and thus might shift the index
const encodings = specM.specQuery.encodings;
let nonPositionChannelCount = 0;
let hasEnumeratedNonPositionChannel = false;
for (let i = 0; i < encodings.length; i++) {
const encQ = encodings[i];
if (isValueQuery(encQ) || isDisabledAutoCountQuery(encQ)) {
continue; // ignore skipped encoding
}
const channel = encQ.channel;
if (!isWildcard(channel)) {
if (NONPOSITION_CHANNELS_INDEX[`${channel}`]) {
nonPositionChannelCount += 1;
if (specM.wildcardIndex.hasEncodingProperty(i, Property.CHANNEL)) {
hasEnumeratedNonPositionChannel = true;
}
if (
nonPositionChannelCount > 1 &&
(hasEnumeratedNonPositionChannel || opt.constraintManuallySpecifiedValue)
) {
return false;
}
}
}
}
return true;
},
},
{
name: 'omitNonPositionalOrFacetOverPositionalChannels',
description: 'Do not use non-positional channels unless all positional channels are used',
properties: [Property.CHANNEL],
allowWildcardForProperties: false,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, opt: QueryConfig) => {
const encodings = specM.specQuery.encodings;
let hasNonPositionalChannelOrFacet = false;
let hasEnumeratedNonPositionOrFacetChannel = false;
let hasX = false;
let hasY = false;
for (let i = 0; i < encodings.length; i++) {
const encQ = encodings[i];
if (isValueQuery(encQ) || isDisabledAutoCountQuery(encQ)) {
continue; // ignore skipped encoding
}
const channel = encQ.channel;
if (channel === CHANNEL.X) {
hasX = true;
} else if (channel === CHANNEL.Y) {
hasY = true;
} else if (!isWildcard(channel)) {
// All non positional channel / Facet
hasNonPositionalChannelOrFacet = true;
if (specM.wildcardIndex.hasEncodingProperty(i, Property.CHANNEL)) {
hasEnumeratedNonPositionOrFacetChannel = true;
}
}
}
if (
hasEnumeratedNonPositionOrFacetChannel ||
(opt.constraintManuallySpecifiedValue && hasNonPositionalChannelOrFacet)
) {
return hasX && hasY;
}
return true;
},
},
{
name: 'omitRaw',
description: 'Omit raw plots.',
properties: [Property.AGGREGATE, Property.AUTOCOUNT],
allowWildcardForProperties: false,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
if (!specM.isAggregate()) {
return false;
}
return true;
},
},
{
name: 'omitRawContinuousFieldForAggregatePlot',
description:
'Aggregate plot should not use raw continuous field as group by values. ' +
'(Quantitative should be binned. Temporal should have time unit.)',
properties: [Property.AGGREGATE, Property.AUTOCOUNT, Property.TIMEUNIT, Property.BIN, Property.TYPE],
allowWildcardForProperties: true,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, opt: QueryConfig) => {
if (specM.isAggregate()) {
const encodings = specM.specQuery.encodings;
for (let i = 0; i < encodings.length; i++) {
const encQ = encodings[i];
if (isValueQuery(encQ) || isDisabledAutoCountQuery(encQ)) continue; // skip unused encoding
// TODO: aggregate for ordinal and temporal
if (isFieldQuery(encQ) && encQ.type === TYPE.TEMPORAL) {
// Temporal fields should have timeUnit or is still a wildcard
if (
!encQ.timeUnit &&
(specM.wildcardIndex.hasEncodingProperty(i, Property.TIMEUNIT) || opt.constraintManuallySpecifiedValue)
) {
return false;
}
}
if (encQ.type === TYPE.QUANTITATIVE) {
if (isFieldQuery(encQ) && !encQ.bin && !encQ.aggregate) {
// If Raw Q
if (
specM.wildcardIndex.hasEncodingProperty(i, Property.BIN) ||
specM.wildcardIndex.hasEncodingProperty(i, Property.AGGREGATE) ||
specM.wildcardIndex.hasEncodingProperty(i, Property.AUTOCOUNT)
) {
// and it's raw from enumeration
return false;
}
if (opt.constraintManuallySpecifiedValue) {
// or if we constraintManuallySpecifiedValue
return false;
}
}
}
}
}
return true;
},
},
{
name: 'omitRawDetail',
description: 'Do not use detail channel with raw plot.',
properties: [Property.CHANNEL, Property.AGGREGATE, Property.AUTOCOUNT],
allowWildcardForProperties: false,
strict: true,
satisfy: (specM: SpecQueryModel, _: Schema, opt: QueryConfig) => {
if (specM.isAggregate()) {
return true;
}
return every(specM.specQuery.encodings, (encQ, index) => {
if (isValueQuery(encQ) || isDisabledAutoCountQuery(encQ)) return true; // ignore autoCount field
if (encQ.channel === CHANNEL.DETAIL) {
// Detail channel for raw plot is not good, except when its enumerated
// or when it's manually specified but we constraintManuallySpecifiedValue.
if (
specM.wildcardIndex.hasEncodingProperty(index, Property.CHANNEL) ||
opt.constraintManuallySpecifiedValue
) {
return false;
}
}
return true;
});
},
},
{
name: 'omitRepeatedField',
description: 'Each field should be mapped to only one channel',
properties: [Property.FIELD],
allowWildcardForProperties: true,
strict: false, // over-encoding is sometimes good, but let's turn it off by default
satisfy: (specM: SpecQueryModel, _: Schema, opt: QueryConfig) => {
const fieldUsed = {};
const fieldEnumerated = {};
const encodings = specM.specQuery.encodings;
for (let i = 0; i < encodings.length; i++) {
const encQ = encodings[i];
if (isValueQuery(encQ) || isAutoCountQuery(encQ)) continue;
let field;
if (encQ.field && !isWildcard(encQ.field)) {
field = encQ.field as string;
}
if (isAutoCountQuery(encQ) && !isWildcard(encQ.autoCount)) {
field = 'count_*';
}
if (field) {
if (specM.wildcardIndex.hasEncodingProperty(i, Property.FIELD)) {
fieldEnumerated[field] = true;
}
// When the field is specified previously,
// if it is enumerated (either previously or in this encQ)
// or if the opt.constraintManuallySpecifiedValue is true,
// then it violates the constraint.
if (fieldUsed[field]) {
if (fieldEnumerated[field] || opt.constraintManuallySpecifiedValue) {
return false;
}
}
fieldUsed[field] = true;
}
}
return true;
},
},
// TODO: omitShapeWithBin
{
name: 'omitVerticalDotPlot',
description: 'Do not output vertical dot plot.',
properties: [Property.CHANNEL],
allowWildcardForProperties: true,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
const encodings = specM.getEncodings();
if (encodings.length === 1 && encodings[0].channel === CHANNEL.Y) {
return false;
}
return true;
},
},
// EXPENSIVE CONSTRAINTS -- check them later!
{
name: 'hasAppropriateGraphicTypeForMark',
description: 'Has appropriate graphic type for mark',
properties: [
Property.CHANNEL,
Property.MARK,
Property.TYPE,
Property.TIMEUNIT,
Property.BIN,
Property.AGGREGATE,
Property.AUTOCOUNT,
],
allowWildcardForProperties: false,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
const mark = specM.getMark();
switch (mark) {
case MARK.AREA:
case MARK.LINE:
if (specM.isAggregate()) {
// TODO: refactor based on profiling statistics
const xEncQ = specM.getEncodingQueryByChannel(CHANNEL.X);
const yEncQ = specM.getEncodingQueryByChannel(CHANNEL.Y);
const xIsMeasure = isMeasure(xEncQ);
const yIsMeasure = isMeasure(yEncQ);
// for aggregate line / area, we need at least one group-by axis and one measure axis.
return (
xEncQ &&
yEncQ &&
xIsMeasure !== yIsMeasure &&
// and the dimension axis should not be nominal
// TODO: make this clause optional
!(isFieldQuery(xEncQ) && !xIsMeasure && contains(['nominal', 'key'], xEncQ.type)) &&
!(isFieldQuery(yEncQ) && !yIsMeasure && contains(['nominal', 'key'], yEncQ.type))
);
// TODO: allow connected scatterplot
}
return true;
case MARK.TEXT:
// FIXME correctly when we add text
return true;
case MARK.BAR:
case MARK.TICK:
// Bar and tick should not use size.
if (specM.channelEncodingField(CHANNEL.SIZE)) {
return false;
} else {
// Tick and Bar should have one and only one measure
const xEncQ = specM.getEncodingQueryByChannel(CHANNEL.X);
const yEncQ = specM.getEncodingQueryByChannel(CHANNEL.Y);
const xIsMeasure = isMeasure(xEncQ);
const yIsMeasure = isMeasure(yEncQ);
if (xIsMeasure !== yIsMeasure) {
return true;
}
return false;
}
case MARK.RECT:
// Until CompassQL supports layering, it only makes sense for
// rect to encode DxD or 1xD (otherwise just use bar).
// Furthermore, color should only be used in a 'heatmap' fashion
// (with a measure field).
const xEncQ = specM.getEncodingQueryByChannel(CHANNEL.X);
const yEncQ = specM.getEncodingQueryByChannel(CHANNEL.Y);
const xIsDimension = isDimension(xEncQ);
const yIsDimension = isDimension(yEncQ);
const colorEncQ = specM.getEncodingQueryByChannel(CHANNEL.COLOR);
const colorIsQuantitative = isMeasure(colorEncQ);
const colorIsOrdinal = isFieldQuery(colorEncQ) ? colorEncQ.type === TYPE.ORDINAL : false;
const correctChannels =
(xIsDimension && yIsDimension) ||
(xIsDimension && !specM.channelUsed(CHANNEL.Y)) ||
(yIsDimension && !specM.channelUsed(CHANNEL.X));
const correctColor = !colorEncQ || (colorEncQ && (colorIsQuantitative || colorIsOrdinal));
return correctChannels && correctColor;
case MARK.CIRCLE:
case MARK.POINT:
case MARK.SQUARE:
case MARK.RULE:
return true;
}
/* istanbul ignore next */
throw new Error(`hasAllRequiredChannelsForMark not implemented for mark${mark}`);
},
},
{
name: 'omitInvalidStackSpec',
description: 'If stack is specified, must follow Vega-Lite stack rules',
properties: [
Property.STACK,
Property.FIELD,
Property.CHANNEL,
Property.MARK,
Property.AGGREGATE,
Property.AUTOCOUNT,
Property.SCALE,
getEncodingNestedProp('scale', 'type'),
Property.TYPE,
],
allowWildcardForProperties: false,
strict: true,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
if (!specM.wildcardIndex.hasProperty(Property.STACK)) {
return true;
}
const stackProps = specM.getVlStack();
if (stackProps === null && specM.getStackOffset() !== null) {
return false;
}
if (stackProps.fieldChannel !== specM.getStackChannel()) {
return false;
}
return true;
},
},
{
name: 'omitNonSumStack',
description: 'Stack specifications that use non-summative aggregates should be omitted (even implicit ones)',
properties: [
Property.CHANNEL,
Property.MARK,
Property.AGGREGATE,
Property.AUTOCOUNT,
Property.SCALE,
getEncodingNestedProp('scale', 'type'),
Property.TYPE,
],
allowWildcardForProperties: false,
strict: true,
satisfy: (specM: SpecQueryModel, _: Schema, __: QueryConfig) => {
const specStack = specM.getVlStack();
if (specStack != null) {
const stackParentEncQ = specM.getEncodingQueryByChannel(specStack.fieldChannel) as FieldQuery;
if (!contains(SUM_OPS, stackParentEncQ.aggregate)) {
return false;
}
}
return true;
},
},
{
name: 'omitTableWithOcclusionIfAutoAddCount',
description:
'Plots without aggregation or autocount where x and y are both discrete should be omitted if autoAddCount is enabled as they often lead to occlusion',
properties: [
Property.CHANNEL,
Property.TYPE,
Property.TIMEUNIT,
Property.BIN,
Property.AGGREGATE,
Property.AUTOCOUNT,
],
allowWildcardForProperties: false,
strict: false,
satisfy: (specM: SpecQueryModel, _: Schema, opt: QueryConfig) => {
if (opt.autoAddCount) {
const xEncQ = specM.getEncodingQueryByChannel('x');
const yEncQ = specM.getEncodingQueryByChannel('y');
if ((!isFieldQuery(xEncQ) || isDimension(xEncQ)) && (!isFieldQuery(yEncQ) || isDimension(yEncQ))) {
if (!specM.isAggregate()) {
return false;
} else {
return every(specM.getEncodings(), (encQ) => {
const channel = encQ.channel;
if (
channel !== CHANNEL.X &&
channel !== CHANNEL.Y &&
channel !== CHANNEL.ROW &&
channel !== CHANNEL.COLUMN
) {
// Non-position fields should not be unaggreated fields
if (isFieldQuery(encQ) && !encQ.aggregate) {
return false;
}
}
return true;
});
}
}
}
return true;
},
},
].map((sc) => new SpecConstraintModel(sc));
// For testing
export const SPEC_CONSTRAINT_INDEX: {[name: string]: SpecConstraintModel} = SPEC_CONSTRAINTS.reduce(
(m: any, c: SpecConstraintModel) => {
m[c.name()] = c;
return m;
},
{}
);
const SPEC_CONSTRAINTS_BY_PROPERTY = SPEC_CONSTRAINTS.reduce((index, c) => {
for (const prop of c.properties()) {
// Initialize array and use it
index.set(prop, index.get(prop) || []);
index.get(prop).push(c);
}
return index;
}, new PropIndex<SpecConstraintModel[]>());
/**
* Check all encoding constraints for a particular property and index tuple
*/
export function checkSpec(
prop: Property,
wildcard: Wildcard<any>,
specM: SpecQueryModel,
schema: Schema,
opt: QueryConfig
): string {
// Check encoding constraint
const specConstraints = SPEC_CONSTRAINTS_BY_PROPERTY.get(prop) || [];
for (const c of specConstraints) {
// Check if the constraint is enabled
if (c.strict() || !!opt[c.name()]) {
// For strict constraint, or enabled non-strict, check the constraints
const satisfy = c.satisfy(specM, schema, opt);
if (!satisfy) {
const violatedConstraint = `(spec) ${c.name()}`;
/* istanbul ignore if */
if (opt.verbose) {
console.log(`${violatedConstraint} failed with ${specM.toShorthand()} for ${wildcard.name}`);
}
return violatedConstraint;
}
}
}
return null;
} | the_stack |
import React, { useCallback, useEffect, useMemo } from 'react';
import { useDispatch } from 'react-redux';
import debounce from 'lodash.debounce';
import {
translate as $t,
UNKNOWN_OPERATION_TYPE,
NONE_CATEGORY_ID,
startOfDay,
endOfDay,
useKresusState,
assert,
} from '../../helpers';
import { get, actions } from '../../store';
import URL from '../../urls';
import ClearableInput, { ClearableInputRef } from '../ui/clearable-input';
import DatePicker from '../ui/date-picker';
import FuzzyOrNativeSelect from '../ui/fuzzy-or-native-select';
import MultipleSelect from '../ui/multiple-select';
import MinMaxInput, { MinMaxInputRef } from '../ui/min-max-input';
import './search.css';
import { matchPath, useHistory } from 'react-router-dom';
// Debouncing for input events (ms).
const INPUT_DEBOUNCING = 150;
const ANY_TYPE_ID = '';
function typeNotFoundMessage() {
return $t('client.operations.no_type_found');
}
const SearchTypeSelect = (props: { id: string }) => {
const defaultValue = useKresusState(state => get.searchFields(state).type);
const types = useKresusState(state => get.types(state));
const dispatch = useDispatch();
const handleOperationType = useCallback(
newValue => {
const value = newValue !== null ? newValue : ANY_TYPE_ID;
actions.setSearchFields(dispatch, { type: value });
},
[dispatch]
);
const options = useMemo(() => {
const unknownType = types.find(type => type.name === UNKNOWN_OPERATION_TYPE);
assert(typeof unknownType !== 'undefined', 'none type exists');
// Types are not sorted.
const allTypes = [unknownType].concat(
types.filter(type => type.name !== UNKNOWN_OPERATION_TYPE)
);
return [
{
value: ANY_TYPE_ID,
label: $t('client.search.any_type'),
},
].concat(
allTypes.map(type => ({
value: type.name,
label: $t(`client.${type.name}`),
}))
);
}, [types]);
return (
<FuzzyOrNativeSelect
clearable={true}
noOptionsMessage={typeNotFoundMessage}
onChange={handleOperationType}
options={options}
value={defaultValue}
id={props.id}
/>
);
};
function categoryNotFoundMessage() {
return $t('client.operations.no_category_found');
}
const SearchCategorySelect = (props: { id: string }) => {
const values = useKresusState(state => get.searchFields(state).categoryIds);
const categories = useKresusState(state => get.categories(state));
const dispatch = useDispatch();
const handleChange = useCallback(
(newValue: (string | number)[]) => {
assert(
newValue.every(x => typeof x === 'number'),
'only numbers'
);
const value = newValue as number[];
actions.setSearchFields(dispatch, { categoryIds: value });
},
[dispatch]
);
const options = useMemo(() => {
const noneCategory = categories.find(cat => cat.id === NONE_CATEGORY_ID);
assert(typeof noneCategory !== 'undefined', 'none category exists');
const otherCategories = categories.filter(cat => cat.id !== NONE_CATEGORY_ID);
return [
{
value: noneCategory.id,
label: noneCategory.label,
},
].concat(otherCategories.map(cat => ({ value: cat.id, label: cat.label })));
}, [categories]);
return (
<MultipleSelect
noOptionsMessage={categoryNotFoundMessage}
onChange={handleChange}
options={options}
values={values}
placeholder={$t('client.search.category_placeholder', values.length)}
id={props.id}
/>
);
};
const MinDatePicker = (props: { id: string }) => {
const value = useKresusState(state => get.searchFields(state).dateLow);
const maxDate = useKresusState(state => get.searchFields(state).dateHigh || undefined);
const dispatch = useDispatch();
const onSelect = useCallback(
(rawDateLow: Date | null) => {
let dateLow = null;
if (rawDateLow) {
dateLow = startOfDay(new Date(rawDateLow));
}
actions.setSearchFields(dispatch, { dateLow });
},
[dispatch]
);
return <DatePicker id={props.id} value={value} maxDate={maxDate} onSelect={onSelect} />;
};
const MaxDatePicker = (props: { id: string }) => {
const value = useKresusState(state => get.searchFields(state).dateHigh);
const minDate = useKresusState(state => get.searchFields(state).dateLow || undefined);
const dispatch = useDispatch();
const onSelect = useCallback(
(rawDateHigh: Date | null) => {
let dateHigh = null;
if (rawDateHigh) {
dateHigh = endOfDay(new Date(rawDateHigh));
}
actions.setSearchFields(dispatch, { dateHigh });
},
[dispatch]
);
return <DatePicker id={props.id} value={value} minDate={minDate} onSelect={onSelect} />;
};
const SearchComponent = (props: { minAmount: number; maxAmount: number }) => {
const history = useHistory();
const displaySearchDetails = useKresusState(state => get.displaySearchDetails(state));
const searchFields = useKresusState(state => get.searchFields(state));
const dispatch = useDispatch();
const setKeywords = useCallback(
(keywordsString: string) => {
const trimmed = keywordsString.trim();
let keywords: string[];
if (trimmed.length) {
keywords = trimmed.split(' ').map((w: string) => w.toLowerCase());
} else {
keywords = [];
}
actions.setSearchFields(dispatch, { keywords });
},
[dispatch]
);
const setAmountLowHigh = useCallback(
(low: number | null, high: number | null) => {
actions.setSearchFields(dispatch, {
amountLow: low,
amountHigh: high,
});
},
[dispatch]
);
const resetAll = useCallback(
(showDetails: boolean) => {
actions.resetSearch(dispatch);
actions.toggleSearchDetails(dispatch, showDetails);
},
[dispatch]
);
const refKeywordsInput = React.createRef<ClearableInputRef>();
const refMinMaxInput = React.createRef<MinMaxInputRef>();
// eslint-disable-next-line react-hooks/exhaustive-deps
const handleKeyword = useCallback(
debounce(
(value: string) => {
setKeywords(value);
},
INPUT_DEBOUNCING,
{ trailing: true }
),
[setKeywords]
);
const handleClearSearch = useCallback(
event => {
event.preventDefault();
const keywords = refKeywordsInput.current;
assert(keywords !== null, 'keywords ref set');
keywords.clear();
const minMax = refMinMaxInput.current;
assert(minMax !== null, 'min max ref set');
minMax.clear();
},
[refKeywordsInput, refMinMaxInput]
);
const handleClearSearchNoClose = useCallback(
event => {
handleClearSearch(event);
resetAll(true);
},
[handleClearSearch, resetAll]
);
const handleClearSearchAndClose = useCallback(
event => {
handleClearSearch(event);
resetAll(false);
},
[handleClearSearch, resetAll]
);
// eslint-disable-next-line react-hooks/exhaustive-deps
const handleMinMaxChange = useCallback(
debounce((low: number | null, high: number | null) => {
// Don't trigger a false rerender if the values haven't changed.
if (searchFields.amountLow !== low || searchFields.amountHigh !== high) {
setAmountLowHigh(low, high);
}
}, INPUT_DEBOUNCING),
[searchFields, setAmountLowHigh]
);
useEffect(() => {
return () => {
// On unmount, reset the search, unless we're going to a
// transaction's detail page. We already know what the next path
// will be, because this effect is triggered asynchronously, after
// we've requested to leave the current route/component.
const nextPath = history.location.pathname;
if (matchPath(nextPath, URL.transactions.pattern) === null) {
resetAll(false);
}
};
}, [resetAll, history]);
return (
<form className="search" hidden={!displaySearchDetails}>
<div className="search-keywords">
<label htmlFor="keywords">{$t('client.search.keywords')}</label>
<ClearableInput
ref={refKeywordsInput}
onChange={handleKeyword}
value={searchFields.keywords.join(' ')}
id="keywords"
/>
</div>
<div className="search-categories-types">
<label htmlFor="search-type">{$t('client.search.type')}</label>
<SearchTypeSelect id="search-type" />
<label htmlFor="search-category">{$t('client.search.category')}</label>
<SearchCategorySelect id="search-category" />
</div>
<div className="search-amounts">
<label>{$t('client.search.amount')}</label>
<MinMaxInput
low={searchFields.amountLow}
high={searchFields.amountHigh}
min={props.minAmount}
max={props.maxAmount}
onChange={handleMinMaxChange}
ref={refMinMaxInput}
/>
</div>
<div className="search-dates">
<label htmlFor="date-low">{$t('client.search.date_low')}</label>
<MinDatePicker id="date-low" />
<label htmlFor="date-high">{$t('client.search.date_high')}</label>
<MaxDatePicker id="date-high" />
</div>
<p className="search-buttons">
<button className="btn warning" type="button" onClick={handleClearSearchNoClose}>
{$t('client.search.clear')}
</button>
<button className="btn warning" type="button" onClick={handleClearSearchAndClose}>
{$t('client.search.clearAndClose')}
</button>
</p>
</form>
);
};
export default SearchComponent; | the_stack |
import { IGalleryApi } from "azure-devops-node-api/GalleryApi";
import { PublishSettings } from "./interfaces";
import _ = require("lodash");
import colors = require("colors");
import errHandler = require("../../../lib/errorhandler");
import fs = require("fs");
import GalleryInterfaces = require("azure-devops-node-api/interfaces/GalleryInterfaces");
import trace = require("../../../lib/trace");
import xml2js = require("xml2js");
import zip = require("jszip");
import { delay } from "../../../lib/promiseUtils";
export interface CoreExtInfo {
id: string;
publisher: string;
version: string;
published?: boolean;
isPublicExtension?: boolean;
}
export class GalleryBase {
public static validationPending = "__validation_pending";
public static validated = "__validated";
private vsixInfoPromise: Promise<CoreExtInfo>;
/**
* Constructor
* @param PublishSettings
*/
constructor(protected settings: PublishSettings, protected galleryClient: IGalleryApi, extInfo?: CoreExtInfo) {
if (extInfo) {
this.vsixInfoPromise = Promise.resolve(extInfo);
}
// if (!settings.galleryUrl || !/^https?:\/\//.test(settings.galleryUrl)) {
// throw "Invalid or missing gallery URL.";
// }
// if (!settings.token || !/^[A-z0-9]{52}$/.test(settings.token)) {
// throw "Invalid or missing personal access token.";
// }
}
protected getExtInfo(): Promise<CoreExtInfo> {
if (!this.vsixInfoPromise) {
this.vsixInfoPromise = GalleryBase.getExtInfo({
extensionId: this.settings.extensionId,
publisher: this.settings.publisher,
vsixPath: this.settings.vsixPath,
});
}
return this.vsixInfoPromise;
}
public static getExtInfo(info: { extensionId?: string; publisher?: string; vsixPath?: string }): Promise<CoreExtInfo> {
let promise: Promise<CoreExtInfo>;
if (info.extensionId && info.publisher) {
promise = Promise.resolve<CoreExtInfo>({ id: info.extensionId, publisher: info.publisher, version: null });
} else {
promise = new Promise<zip>((resolve, reject) => {
fs.readFile(info.vsixPath, async function(err, data) {
if (err) reject(err);
trace.debug("Read vsix as zip... Size (bytes): %s", data.length.toString());
try {
const archive = new zip();
await archive.loadAsync(data);
resolve(archive);
} catch (err) {
reject(err);
}
});
})
.then(zip => {
trace.debug("Files in the zip: %s", Object.keys(zip.files).join(", "));
const vsixManifestFileNames = Object.keys(zip.files).filter(key => _.endsWith(key, "vsixmanifest"));
if (vsixManifestFileNames.length > 0) {
return new Promise(async (resolve, reject) => {
xml2js.parseString(await zip.files[vsixManifestFileNames[0]].async("text"), (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
} else {
throw new Error("Could not locate vsix manifest!");
}
})
.then(vsixManifestAsJson => {
const extensionId: string =
info.extensionId || _.get(vsixManifestAsJson, "PackageManifest.Metadata[0].Identity[0].$.Id");
const extensionPublisher: string =
info.publisher || _.get(vsixManifestAsJson, "PackageManifest.Metadata[0].Identity[0].$.Publisher");
const extensionVersion: string = _.get(
vsixManifestAsJson,
"PackageManifest.Metadata[0].Identity[0].$.Version",
);
const isPublicExtension: boolean =
_.get(vsixManifestAsJson, "PackageManifest.Metadata[0].GalleryFlags[0]", []).indexOf("Public") >= 0;
if (extensionId && extensionPublisher) {
return {
id: extensionId,
publisher: extensionPublisher,
version: extensionVersion,
isPublicExtension: isPublicExtension,
};
} else {
throw new Error(
"Could not locate both the extension id and publisher in vsix manfiest! Ensure your manifest includes both a namespace and a publisher property, or specify the necessary --publisher and/or --extension options.",
);
}
});
}
return promise;
}
public getValidationStatus(version?: string): Promise<string> {
return this.getExtInfo().then(extInfo => {
return this.galleryClient
.getExtension(
null,
extInfo.publisher,
extInfo.id,
extInfo.version,
GalleryInterfaces.ExtensionQueryFlags.IncludeVersions,
)
.then(ext => {
return this.extToValidationStatus(ext, version);
});
});
}
public extToValidationStatus(extension: GalleryInterfaces.PublishedExtension, version?: string): string {
if (!extension || extension.versions.length === 0) {
throw new Error("Extension not published.");
}
let extVersion = extension.versions[0];
if (version) {
extVersion = this.getVersionedExtension(extension, version);
}
if (!extVersion) {
throw new Error("Could not find extension version " + version);
}
// If there is a validationResultMessage, validation failed and this is the error
// If the validated flag is missing and there is no validationResultMessage, validation is pending
// If the validated flag is present and there is no validationResultMessage, the extension is validated.
if (extVersion.validationResultMessage) {
return extVersion.validationResultMessage;
} else if ((extVersion.flags & GalleryInterfaces.ExtensionVersionFlags.Validated) === 0) {
return PackagePublisher.validationPending;
} else {
return PackagePublisher.validated;
}
}
private getVersionedExtension(
extension: GalleryInterfaces.PublishedExtension,
version: string,
): GalleryInterfaces.ExtensionVersion {
const matches = extension.versions.filter(ev => ev.version === version);
if (matches.length > 0) {
return matches[0];
} else {
return null;
}
}
public getExtensionInfo(): Promise<GalleryInterfaces.PublishedExtension> {
return this.getExtInfo().then<GalleryInterfaces.PublishedExtension>(extInfo => {
return this.galleryClient
.getExtension(
null,
extInfo.publisher,
extInfo.id,
null,
GalleryInterfaces.ExtensionQueryFlags.IncludeVersions |
GalleryInterfaces.ExtensionQueryFlags.IncludeFiles |
GalleryInterfaces.ExtensionQueryFlags.IncludeCategoryAndTags |
GalleryInterfaces.ExtensionQueryFlags.IncludeSharedAccounts,
)
.then(extension => {
return extension;
})
.catch(errHandler.httpErr);
});
}
}
/**
* Class that handles creating and deleting publishers
*/
export class PublisherManager extends GalleryBase {
/**
* Constructor
* @param PublishSettings
*/
constructor(protected settings: PublishSettings, protected galleryClient: IGalleryApi) {
super(settings, galleryClient);
}
/**
* Create a a publisher with the given name, displayName, and description
* @param string Publisher's unique name
* @param string Publisher's display name
* @param string Publisher description
* @return Q.Promise that is resolved when publisher is created
*/
public createPublisher(name: string, displayName: string, description: string): Promise<any> {
return this.galleryClient
.createPublisher(<GalleryInterfaces.Publisher>{
publisherName: name,
displayName: displayName,
longDescription: description,
shortDescription: description,
})
.catch(errHandler.httpErr);
}
/**
* Delete the publisher with the given name
* @param string Publisher's unique name
* @return Q.promise that is resolved when publisher is deleted
*/
public deletePublisher(name: string): Promise<any> {
return this.galleryClient.deletePublisher(name).catch(errHandler.httpErr);
}
}
export class SharingManager extends GalleryBase {
private id: Promise<string>;
private publisher: Promise<string>;
public shareWith(accounts: string[]): Promise<any> {
return this.getExtInfo().then(extInfo => {
return Promise.all(
accounts.map(account => {
trace.info("Sharing extension with %s.", account);
return SharingManager.shareExtension(this.galleryClient, extInfo.publisher, extInfo.id, account).catch(errHandler.httpErr);
// return this.galleryClient.shareExtension(extInfo.publisher, extInfo.id, account).catch(errHandler.httpErr);
}),
);
});
}
public unshareWith(accounts: string[]): Promise<any> {
return this.getExtInfo().then(extInfo => {
return Promise.all(
accounts.map(account => {
return this.galleryClient.unshareExtension(extInfo.publisher, extInfo.id, account).catch(errHandler.httpErr);
}),
);
});
}
public unshareWithAll(): Promise<any> {
return this.getSharedWithAccounts().then(accounts => {
return this.unshareWith(accounts);
});
}
public getSharedWithAccounts() {
return this.getExtensionInfo().then(ext => {
return ext.sharedWith.map(acct => acct.name);
});
}
/******** TEMPORARY UNTIL REST CLIENT UPDATED ********/
public static async shareExtension(
client: IGalleryApi,
publisherName: string,
extensionName: string,
accountName: string
): Promise<void> {
return new Promise<void>(async (resolve, reject) => {
let routeValues: any = {
publisherName: publisherName,
extensionName: extensionName,
accountName: accountName
};
try {
let verData = await client.vsoClient.getVersioningData(
"6.1-preview.1",
"gallery",
"a1e66d8f-f5de-4d16-8309-91a4e015ee46",
routeValues);
let url: string = verData.requestUrl;
let options = client.createRequestOptions('application/json',
verData.apiVersion);
const res = await client.rest.create<void>(url, null, options);
let ret = client.formatResponse(res.result,
null,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/******** /TEMPORARY UNTIL REST CLIENT UPDATED ********/
}
export class PackagePublisher extends GalleryBase {
private static fastValidationInterval = 2000;
private static fastValidationRetries = 120;
private static fullValidationInterval = 15000;
private static fullValidationRetries = 80;
private checkVsixPublished(): Promise<CoreExtInfo> {
return this.getExtInfo().then(extInfo => {
return this.galleryClient
.getExtension(null, extInfo.publisher, extInfo.id)
.then(ext => {
if (ext) {
extInfo.published = true;
return extInfo;
}
return extInfo;
})
.catch<CoreExtInfo>(() => extInfo);
});
}
/**
* Publish the VSIX extension given by vsixPath
* @param string path to a VSIX extension to publish
* @return Q.Promise that is resolved when publish is complete
*/
public publish(): Promise<GalleryInterfaces.PublishedExtension> {
const extPackage: GalleryInterfaces.ExtensionPackage = {
extensionManifest: fs.readFileSync(this.settings.vsixPath, "base64"),
};
trace.debug("Publishing %s", this.settings.vsixPath);
// Check if the app is already published. If so, call the update endpoint. Otherwise, create.
trace.info("Checking if this extension is already published");
return this.getExtInfo().then(extInfo => {
const quitValidation = this.settings.noWaitValidation
? "You passed --no-wait-validation, so TFX is exiting."
: "You can choose to exit (Ctrl-C) if you don't want to wait.";
const noWaitHelp = this.settings.noWaitValidation
? ""
: "If you don't want TFX to wait for validation, use the --no-wait-validation parameter. ";
const extensionValidationTime = extInfo.isPublicExtension
? "Based on the package size, this can take up to 20 mins."
: "This should take only a few seconds, but in some cases may take a bit longer.";
const validationMessage = `\n== Extension Validation In Progress ==\n${extensionValidationTime} ${quitValidation} To get the validation status, you may run the command below. ${noWaitHelp}This extension will be available after validation is successful.\n\n${colors.yellow(
`tfx extension isvalid --publisher ${extInfo.publisher} --extension-id ${extInfo.id} --version ${
extInfo.version
} --service-url ${this.settings.galleryUrl} --token <your PAT>`,
)}`;
return this.createOrUpdateExtension(extPackage).then(ext => {
if (this.settings.noWaitValidation) {
trace.info(validationMessage);
return ext;
} else {
trace.info(validationMessage);
const versions = ext.versions;
versions.sort((a, b) => b.lastUpdated.getTime() - a.lastUpdated.getTime());
const validationInterval = extInfo.isPublicExtension
? PackagePublisher.fullValidationInterval
: PackagePublisher.fastValidationInterval;
const validationRetries = extInfo.isPublicExtension
? PackagePublisher.fullValidationRetries
: PackagePublisher.fastValidationRetries;
const hangTightMessageRetryCount = extInfo.isPublicExtension ? -1 : 25;
return this.waitForValidation(
1000,
validationInterval,
validationRetries,
hangTightMessageRetryCount,
extInfo.publisher,
extInfo.id,
versions[0].version,
).then(result => {
if (result === PackagePublisher.validated) {
return ext;
} else {
throw new Error(
"Extension validation failed. Please address the following issues and retry publishing.\n" +
result,
);
}
});
}
});
});
}
private createOrUpdateExtension(
extPackage: GalleryInterfaces.ExtensionPackage,
): Promise<GalleryInterfaces.PublishedExtension> {
return this.checkVsixPublished().then(extInfo => {
let publishPromise;
if (extInfo && extInfo.published) {
trace.info("It is, %s the extension", colors.cyan("update").toString());
publishPromise = this
.updateExtension(extPackage as any, extInfo.publisher, extInfo.id, false)
.catch(errHandler.httpErr);
} else {
trace.info("It isn't, %s a new extension.", colors.cyan("create").toString());
publishPromise = this.updateExtension(extPackage as any, extInfo.publisher, extInfo.id, true).catch(errHandler.httpErr);
}
return publishPromise.then(() => {
return this.galleryClient.getExtension(
null,
extInfo.publisher,
extInfo.id,
null,
GalleryInterfaces.ExtensionQueryFlags.IncludeVersions,
);
});
});
}
/******** TEMPORARY UNTIL REST CLIENT UPDATED ********/
private async updateExtension(
content: any,
publisherName: string,
extensionName: string,
create: boolean,
): Promise<GalleryInterfaces.PublishedExtension> {
let routeValues: any = {
publisherName: publisherName,
extensionName: extensionName
};
const queryValues: any = {
bypassScopeCheck: undefined
};
const verData = await this.galleryClient.vsoClient.getVersioningData(
"6.1-preview.2",
"gallery",
"e11ea35a-16fe-4b80-ab11-c4cab88a0966",
routeValues,
queryValues
);
const url = verData.requestUrl;
const options = this.galleryClient.createRequestOptions("application/json", verData.apiVersion);
options.additionalHeaders = { "Content-Type": "application/json" };
const response = await (create ? this.galleryClient.rest.create(url, content, options) : this.galleryClient.rest.replace(url, content, options));
return this.galleryClient.formatResponse(response.result, GalleryInterfaces.TypeInfo.PublishedExtension, false);
}
/******** /TEMPORARY UNTIL REST CLIENT UPDATED ********/
public waitForValidation(
interval: number,
maxInterval: number,
retries: number,
showPatienceMessageAt: number,
publisher: string,
extensionId: string,
version?: string,
): Promise<string> {
if (retries === 0) {
const validationTimedOutMessage = `Validation is taking much longer than usual. TFX is exiting. To get the validation status, you may run the command below. This extension will be available after validation is successful.\n\n${colors.yellow(
`tfx extension isvalid --publisher ${publisher} --extension-id ${extensionId} --version ${version} --service-url ${
this.settings.galleryUrl
} --token <your PAT>`,
)}`;
throw new Error(validationTimedOutMessage);
} else if (retries === showPatienceMessageAt) {
trace.info("This is taking longer than usual. Hang tight...");
}
trace.debug("Polling for validation (%s retries remaining).", retries.toString());
return delay(this.getValidationStatus(version), interval).then(status => {
trace.debug("--Retrieved validation status: %s", status);
if (status === PackagePublisher.validationPending) {
// exponentially increase interval until we reach max interval
return this.waitForValidation(
Math.min(interval * 2, maxInterval),
maxInterval,
retries - 1,
showPatienceMessageAt,
publisher,
extensionId,
version,
);
} else {
return status;
}
});
}
} | the_stack |
import { makeRandomToken } from "../shared/main";
// This file is injected as a regular script in all pages and overrides
// `.addEventListener` (and friends) so we can detect click listeners.
// This is a bit fiddly because we try to cover our tracks as good as possible.
// Basically everything in this file has to be inside the `export default`
// function, since `.toString()` is called on it in ElementManager. This also
// means that `import`s generally cannot be used in this file. All of the below
// constants are `.replace()`:ed in by ElementManager, but they are defined in
// this file so that TypeScript knows about them.
// NOTE: If you add a new constant, you have to update the `constants` object in
// ElementManager.ts as well!
// To make things even more complicated, in Firefox the `export default`
// function is actually executed rather than inserted as an inline script. This
// is to work around Firefox’s CSP limiations. As a bonus, Firefox can
// communicate with this file directly (via the `communicator` parameter) rather
// than via very clever usage of DOM events. This works in Firefox due to
// `.wrappedJSObject`, `exportFunction` and `XPCNativeWrapper`.
// All types of events that likely makes an element clickable. All code and
// comments that deal with this only refer to "click", though, to keep things
// simple.
export const CLICKABLE_EVENT_NAMES = ["click", "mousedown"];
export const CLICKABLE_EVENT_PROPS: Array<string> = CLICKABLE_EVENT_NAMES.map(
(eventName) => `on${eventName}`
);
// Common prefix for events. It’s important to create a name unique from
// previous versions of the extension, in case this script hangs around after an
// update (it’s not possible to do cleanups before disabling an extension in
// Firefox). We don’t want the old version to interfere with the new one. This
// uses `BUILD_ID` rather than `makeRandomToken()` so that all frames share
// the same event name. Clickable elements created in this frame but inserted
// into another frame need to dispatch an event in their parent window rather
// than this one. However, since the prefix is static it will be possible for
// malicious sites to send these events. Luckily, that doesn’t hurt much. All
// the page could do is cause false positives or disable detection of click
// events altogether.
const prefix = `__${META_SLUG}WebExt_${BUILD_ID}_`;
// Events that don’t need to think about the iframe edge case described above
// can use this more secure prefix, with a practically unguessable part in it.
const secretPrefix = `__${META_SLUG}WebExt_${makeRandomToken()}_`;
export const CLICKABLE_CHANGED_EVENT = `${prefix}ClickableChanged`;
export const OPEN_SHADOW_ROOT_CREATED_EVENT = `${prefix}OpenShadowRootCreated`;
export const CLOSED_SHADOW_ROOT_CREATED_1_EVENT = `${prefix}ClosedShadowRootCreated1`;
export const CLOSED_SHADOW_ROOT_CREATED_2_EVENT = `${prefix}ClosedShadowRootCreated2`;
export const QUEUE_EVENT = `${secretPrefix}Queue`;
// If an element is not inserted into the page, events fired on it won’t reach
// ElementManager’s window event listeners. Instead, such elements are
// temporarily inserted into a secret element. This event is used to register
// the secret element in ElementManager.
export const REGISTER_SECRET_ELEMENT_EVENT = `${secretPrefix}RegisterSecretElement`;
// Events sent from ElementManager to this file.
export const FLUSH_EVENT = `${secretPrefix}Flush`;
export const RESET_EVENT = `${secretPrefix}Reset`;
export type FromInjected =
| { type: "ClickableChanged"; target: EventTarget; clickable: boolean }
| { type: "Queue"; hasQueue: boolean }
| { type: "ShadowRootCreated"; shadowRoot: ShadowRoot };
export default (communicator?: {
onInjectedMessage: (message: FromInjected) => unknown;
addEventListener: (
eventName: string,
listenter: () => unknown,
_?: true
) => unknown;
}): void => {
// Refers to the page `window` both in Firefox and other browsers.
const win = BROWSER === "firefox" ? window.wrappedJSObject ?? window : window;
// These arrays are replaced in by ElementManager; only refer to them once.
const clickableEventNames = CLICKABLE_EVENT_NAMES;
const clickableEventProps = CLICKABLE_EVENT_PROPS;
// When this was written, <https://jsfiddle.net/> overrides `Event` (which was
// used before switching to `CustomEvent`) with a buggy implementation that
// throws an error. To work around that, make sure that the page can't
// interfere with the crucial parts by saving copies of important things.
// Remember that this runs _before_ any page scripts.
const CustomEvent2 = CustomEvent;
const HTMLElement2 = HTMLElement;
const ShadowRoot2 = ShadowRoot;
// Don't use the usual `log` function here, too keep this file small.
const { error: consoleLogError, log: consoleLog } = console;
const createElement = document.createElement.bind(document);
/* eslint-disable @typescript-eslint/unbound-method */
const { appendChild, removeChild, getRootNode } = Node.prototype;
const { replaceWith } = Element.prototype;
const { addEventListener, dispatchEvent } = EventTarget.prototype;
const { apply } = Reflect;
const { get: mapGet } = Map.prototype;
/* eslint-enable @typescript-eslint/unbound-method */
function logError(...args: Array<unknown>): void {
consoleLogError(`[${META_SLUG}]`, ...args);
}
type AnyFunction = (...args: Array<never>) => void;
type Deadline = { timeRemaining: () => number };
const infiniteDeadline: Deadline = {
timeRemaining: () => Infinity,
};
class HookManager {
fnMap = new Map<AnyFunction, AnyFunction>();
resetFns: Array<AnyFunction> = [];
reset(): void {
// Reset all overridden methods.
for (const resetFn of this.resetFns) {
resetFn();
}
this.fnMap.clear();
this.resetFns = [];
}
// Hook into whenever `obj[name]()` (such as
// `EventTarget.prototype["addEventListener"]`) is called, by calling
// `hook`. This is done by overriding the method, but in a way that makes it
// really difficult to detect that the method has been overridden. There are
// two reasons for covering our tracks:
//
// 1. We don’t want to break websites. For example, naively overriding
// `addEventListener` breaks CKEditor: <https://jsfiddle.net/tv5x6zuj/>
// See also: <https://github.com/philc/vimium/issues/2900> (and its
// linked issues and PRs).
// 2. We don’t want developers to see strange things in the console when
// they debug stuff.
//
// `hook` is run _after_ the original function. If you need to do something
// _before_ the original function is called, use a `prehook`.
hookInto<T, U>(
passedObj: unknown,
name: string,
hook?: (
data: { returnValue: U; prehookData: T | undefined },
thisArg: unknown,
...args: Array<never>
) => unknown,
prehook?: (thisArg: unknown, ...args: Array<never>) => T | undefined
): void {
const obj = passedObj as Record<string, unknown>;
const descriptor = Reflect.getOwnPropertyDescriptor(
obj,
name
) as PropertyDescriptor;
const prop = "value" in descriptor ? "value" : "set";
const originalFn = descriptor[prop] as AnyFunction;
const { fnMap } = this;
// `f = { [name]: function(){} }[name]` is a way of creating a dynamically
// named function (where `f.name === name`).
const fn =
hook === undefined
? {
[originalFn.name](...args: Array<never>): unknown {
// In the cases where no hook is provided we just want to make sure
// that the method (such as `toString`) is called with the
// _original_ function, not the overriding function.
return apply(
originalFn,
apply(mapGet, fnMap, [this]) ?? this,
args
);
},
}[originalFn.name]
: {
[originalFn.name](...args: Array<never>): unknown {
let wrappedArgs = args;
if (BROWSER === "firefox") {
wrappedArgs = args.map((arg) => XPCNativeWrapper(arg));
}
let prehookData = undefined;
if (prehook !== undefined) {
try {
prehookData = prehook(this, ...wrappedArgs);
} catch (errorAny) {
const error = errorAny as Error;
logHookError(error, obj, name);
}
}
// Since Firefox does not support running cleanups when an
// extension is disabled/updated (<bugzil.la/1223425>), hooks
// from the previous version will still be around (until the
// page is reloaded). `apply(originalFn, this, args)` fails with
// "can't access dead object" for the old hooks will fail, so
// ignore that error and abort those hooks.
let returnValue = undefined;
if (BROWSER === "firefox") {
try {
returnValue = XPCNativeWrapper(
apply(originalFn, this, args)
) as U;
} catch (errorAny) {
const error = errorAny as Error | null | undefined;
if (
error !== null &&
error !== undefined &&
error.name === "TypeError" &&
error.message === "can't access dead object"
) {
return undefined;
}
throw error as Error;
}
} else {
returnValue = apply(originalFn, this, args) as U;
}
// In case there's a mistake in `hook` it shouldn't cause the entire
// overridden method to fail and potentially break the whole page.
try {
// Remember that `hook` can be called with _anything,_ because the
// user can pass invalid arguments and use `.call`.
const result = hook(
{ returnValue, prehookData },
this,
...wrappedArgs
);
if (
typeof result === "object" &&
result !== null &&
typeof (result as Record<string, unknown>).then ===
"function"
) {
(result as PromiseLike<unknown>).then(
undefined,
(error: Error) => {
logHookError(error, obj, name);
}
);
}
} catch (errorAny) {
const error = errorAny as Error;
logHookError(error, obj, name);
}
return returnValue;
},
}[originalFn.name];
// Make sure that `.length` is correct. This has to be done _after_
// `exportFunction`.
const setLength = (target: unknown): void => {
Reflect.defineProperty(target as Record<string, unknown>, "length", {
...Reflect.getOwnPropertyDescriptor(Function.prototype, "length"),
value: originalFn.length,
});
};
// Save the overriding and original functions so we can map overriding to
// original in the case with no `hook` above.
fnMap.set(fn, originalFn);
let newDescriptor = { ...descriptor, [prop]: fn };
if (BROWSER === "firefox") {
if (prop === "value") {
exportFunction(fn, obj, { defineAs: name });
setLength(obj[name]);
this.resetFns.push(() => {
exportFunction(originalFn, obj, { defineAs: name });
});
return;
}
newDescriptor = Object.assign(new win.Object(), descriptor, {
set: exportFunction(fn, new win.Object(), { defineAs: name }),
});
}
setLength(newDescriptor[prop]);
// Finally override the method with the created function.
Reflect.defineProperty(obj, name, newDescriptor);
this.resetFns.push(() => {
Reflect.defineProperty(obj, name, descriptor);
});
}
// Make sure that `Function.prototype.toString.call(element.addEventListener)`
// returns "[native code]". This is used by lodash's `_.isNative`.
// `.toLocaleString` is automatically taken care of when patching `.toString`.
conceal(): void {
// This isn’t needed in Firefox, thanks to `exportFunction`.
if (BROWSER !== "firefox") {
this.hookInto(win.Function.prototype, "toString");
}
}
}
function logHookError(error: Error, obj: unknown, name: string): void {
logError(`Failed to run hook for ${name} on`, obj, error);
}
type OptionsByListener = Map<unknown, OptionsSet>;
type OptionsSet = Set<string>;
// Changes to event listeners.
type QueueItem = QueueItemMethod | QueueItemProp;
// `.onclick` and similar.
type QueueItemProp = {
type: "prop";
hadListener: boolean;
element: HTMLElement;
};
// `.addEventListener` and `.removeEventListener`.
type QueueItemMethod = {
type: "method";
added: boolean;
element: HTMLElement;
eventName: string;
listener: unknown;
options: unknown;
};
// Elements waiting to be sent to ElementManager.ts (in Chrome only).
type SendQueueItem = {
added: boolean;
element: HTMLElement;
};
class ClickListenerTracker {
clickListenersByElement = new Map<HTMLElement, OptionsByListener>();
queue: Queue<QueueItem> = makeEmptyQueue();
sendQueue: Queue<SendQueueItem> = makeEmptyQueue();
idleCallbackId: IdleCallbackID | undefined = undefined;
reset(): void {
if (this.idleCallbackId !== undefined) {
cancelIdleCallback(this.idleCallbackId);
}
this.clickListenersByElement = new Map<HTMLElement, OptionsByListener>();
this.queue = makeEmptyQueue();
this.sendQueue = makeEmptyQueue();
this.idleCallbackId = undefined;
}
queueItem(item: QueueItem): void {
const numItems = this.queue.items.push(item);
this.requestIdleCallback();
if (numItems === 1 && this.sendQueue.items.length === 0) {
if (communicator !== undefined) {
communicator.onInjectedMessage({ type: "Queue", hasQueue: true });
} else {
sendWindowEvent(QUEUE_EVENT, true);
}
}
}
requestIdleCallback(): void {
if (this.idleCallbackId === undefined) {
this.idleCallbackId = requestIdleCallback((deadline) => {
this.idleCallbackId = undefined;
this.flushQueue(deadline);
});
}
}
flushQueue(deadline: Deadline): void {
const hadQueue =
this.queue.items.length > 0 || this.sendQueue.items.length > 0;
this._flushQueue(deadline);
const hasQueue =
this.queue.items.length > 0 || this.sendQueue.items.length > 0;
if (hadQueue && !hasQueue) {
if (communicator !== undefined) {
communicator.onInjectedMessage({ type: "Queue", hasQueue: false });
} else {
sendWindowEvent(QUEUE_EVENT, false);
}
}
}
_flushQueue(deadline: Deadline): void {
const done = this.flushSendQueue(deadline);
if (!done || this.queue.items.length === 0) {
return;
}
// Track elements that got their first listener, or lost their last one.
// The data structure simplifies additions and removals: If first adding
// an element and then removing it, it’s the same as never having added or
// removed the element at all (and vice versa).
const addedRemoved = new AddedRemoved<HTMLElement>();
const startQueueIndex = this.queue.index;
let timesUp = false;
for (; this.queue.index < this.queue.items.length; this.queue.index++) {
if (
this.queue.index > startQueueIndex &&
deadline.timeRemaining() <= 0
) {
timesUp = true;
break;
}
const item = this.queue.items[this.queue.index];
// `.onclick` or similar changed.
if (item.type === "prop") {
const { hadListener, element } = item;
// If the element has click listeners added via `.addEventListener`
// changing `.onclick` can't affect whether the element has at least
// one click listener.
if (!this.clickListenersByElement.has(element)) {
const hasListener = hasClickListenerProp(element);
if (!hadListener && hasListener) {
addedRemoved.add(element);
} else if (hadListener && !hasListener) {
addedRemoved.remove(element);
}
}
}
// `.addEventListener`
else if (item.added) {
const gotFirst = this.add(item);
if (gotFirst) {
addedRemoved.add(item.element);
}
}
// `.removeEventListener`
else {
const lostLast = this.remove(item);
if (lostLast) {
addedRemoved.remove(item.element);
}
}
}
if (!timesUp) {
this.queue = makeEmptyQueue();
}
const { added, removed } = addedRemoved;
for (const element of added) {
this.sendQueue.items.push({ added: true, element });
}
for (const element of removed) {
this.sendQueue.items.push({ added: false, element });
}
if (timesUp) {
this.requestIdleCallback();
} else {
this.flushSendQueue(deadline);
}
}
flushSendQueue(deadline: Deadline): boolean {
const startQueueIndex = this.sendQueue.index;
for (
;
this.sendQueue.index < this.sendQueue.items.length;
this.sendQueue.index++
) {
if (
this.sendQueue.index > startQueueIndex &&
deadline.timeRemaining() <= 0
) {
this.requestIdleCallback();
return false;
}
const item = this.sendQueue.items[this.sendQueue.index];
if (communicator !== undefined) {
communicator.onInjectedMessage({
type: "ClickableChanged",
target: item.element,
clickable: item.added,
});
} else {
sendElementEvent(CLICKABLE_CHANGED_EVENT, item.element, item.added);
}
}
this.sendQueue = makeEmptyQueue();
return true;
}
add({ element, eventName, listener, options }: QueueItemMethod): boolean {
const optionsString = stringifyOptions(eventName, options);
const optionsByListener = this.clickListenersByElement.get(element);
// No previous click listeners.
if (optionsByListener === undefined) {
this.clickListenersByElement.set(
element,
new Map([[listener, new Set([optionsString])]])
);
if (!hasClickListenerProp(element)) {
// The element went from no click listeners to one.
return true;
}
return false;
}
const optionsSet = optionsByListener.get(listener);
// New listener function.
if (optionsSet === undefined) {
optionsByListener.set(listener, new Set([optionsString]));
return false;
}
// Already seen listener function, but new options and/or event type.
if (!optionsSet.has(optionsString)) {
optionsSet.add(optionsString);
return false;
}
// Duplicate listener. Nothing to do.
return false;
}
remove({
element,
eventName,
listener,
options,
}: QueueItemMethod): boolean {
const optionsString = stringifyOptions(eventName, options);
const optionsByListener = this.clickListenersByElement.get(element);
// The element has no click listeners.
if (optionsByListener === undefined) {
// If the element was created and given a listener in another frame and
// then was inserted in another frame, the element might actually have
// had a listener after all that was now removed. In Chrome this is
// tracked correctly, but in Firefox we need to "lie" here and say that
// the last listener was removed in case it was.
return BROWSER === "firefox";
}
const optionsSet = optionsByListener.get(listener);
// The element has click listeners, but not with `listener` as a callback.
if (optionsSet === undefined) {
return false;
}
// The element has `listener` as a click callback, but with different
// options and/or event type.
if (!optionsSet.has(optionsString)) {
return false;
}
// Match! Remove the current options.
optionsSet.delete(optionsString);
// If that was the last options for `listener`, remove `listener`.
if (optionsSet.size === 0) {
optionsByListener.delete(listener);
// If that was the last `listener` for `element`, remove `element`.
if (optionsByListener.size === 0) {
this.clickListenersByElement.delete(element);
if (!hasClickListenerProp(element)) {
// The element went from one click listener to none.
return true;
}
}
}
return false;
}
}
type Queue<T> = {
items: Array<T>;
index: number;
};
function makeEmptyQueue<T>(): Queue<T> {
return {
items: [],
index: 0,
};
}
class AddedRemoved<T> {
added = new Set<T>();
removed = new Set<T>();
add(item: T): void {
if (this.removed.has(item)) {
this.removed.delete(item);
} else {
this.added.add(item);
}
}
remove(item: T): void {
if (this.added.has(item)) {
this.added.delete(item);
} else {
this.removed.add(item);
}
}
}
function stringifyOptions(eventName: string, options: unknown): string {
const normalized =
typeof options === "object" && options !== null
? (options as Record<string, unknown>)
: { capture: Boolean(options) };
// Only the value of the `capture` option (regardless of how it was set) matters:
// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener#matching_event_listeners_for_removal
const capture = Boolean(normalized.capture).toString();
return `${eventName}:${capture}`;
}
function hasClickListenerProp(element: HTMLElement): boolean {
return clickableEventProps.some(
(prop) => typeof element[prop as keyof HTMLElement] === "function"
);
}
function sendWindowEvent(eventName: string, detail: unknown): void {
apply(dispatchEvent, window, [new CustomEvent2(eventName, { detail })]);
}
function makeSecretElement(): HTMLElement {
// Content scripts running at `document_start` actually execute _before_
// `document.head` exists! `document.documentElement` seems to be completely
// empty when this runs (in new tabs). Just to be extra safe, use a `<head>`
// element as the secret element. `<head>` is invisible (`display: none;`)
// and a valid child of `<html>`. I’m worried injecting some other element
// could cause the browser to paint that, resulting in a flash of unstyled
// content.
// A super edge case is when `document.documentElement` is missing. It’s
// possible to do for example `document.documentElement.remove()` and later
// `document.append(newRoot)`.
const [root, secretElement] =
document.documentElement === null
? [document, createElement("html")]
: [document.documentElement, createElement("head")];
if (communicator === undefined) {
apply(appendChild, root, [secretElement]);
apply(dispatchEvent, secretElement, [
new CustomEvent2(REGISTER_SECRET_ELEMENT_EVENT),
]);
apply(removeChild, root, [secretElement]);
}
return secretElement;
}
// In Firefox, it is also possible to use `sendWindowEvent` passing `element`
// as `detail`, but that does not work properly in all cases when an element
// is inserted into another frame. Chrome does not allow passing DOM elements
// as `detail` from a page to an extension at all.
const secretElement = makeSecretElement();
function sendElementEvent(
eventName: string,
element: Element,
detail: unknown = undefined,
root: OpenComposedRootNode = getOpenComposedRootNode(element)
): void {
const send = (): void => {
apply(dispatchEvent, element, [
// `composed: true` is used to allow the event to be observed outside
// the current ShadowRoot (if any).
new CustomEvent2(eventName, { detail, composed: true }),
]);
};
switch (root.type) {
// The element has 0 or more _open_ shadow roots above it and is connected
// to the page. Nothing more to do – just fire the event.
case "Document":
send();
break;
// For the rest of the cases, the element is not inserted into the page
// (yet/anymore), which means that ElementManager’s window event listeners
// won’t fire. Instead, temporarily insert the element into a disconnected
// element that ElementManager knows about and listens to, but nobody else
// knows about. This avoids triggering MutationObservers on the page.
// Note that the element might still have parent elements (which aren’t
// inserted into the page either), so one cannot just insert `element`
// into `secretElement` and then remove `element` again – then `element`
// would also be removed from its original parent, and be missing when the
// parent is inserted into the page.
// We end up here if:
// - `element` has no parents at all (if so, `element === root.element`).
// - `element` has a (grand-)parent element that has no parents.
// - `element` has one or more _open_ shadow roots above it, and the host
// element of the topmost shadow root has no parents.
// In these cases, it’s the easiest and less invasive to move the entire
// tree temporarily to the secret element.
case "Element":
apply(appendChild, secretElement, [root.element]);
send();
apply(removeChild, secretElement, [root.element]);
break;
// If there’s a _closed_ shadow root somewhere up the chain, we must
// temporarily move `element` out of the top-most closed shadow root
// before we can dispatch events. Replace `element` with a dummy element,
// move it into the secret element, and then replace the dummy back with
// `element` again.
case "Closed": {
const tempElement = createElement("div");
apply(replaceWith, element, [tempElement]);
apply(appendChild, secretElement, [element]);
send();
apply(replaceWith, tempElement, [element]);
break;
}
}
}
type OpenComposedRootNode =
| { type: "Closed" }
| { type: "Document" }
| { type: "Element"; element: Element };
function getOpenComposedRootNode(element: Element): OpenComposedRootNode {
const root = apply(getRootNode, element, []) as ReturnType<
typeof getRootNode
>;
return root === element
? { type: "Element", element }
: root instanceof ShadowRoot2
? root.mode === "open"
? getOpenComposedRootNode(root.host)
: { type: "Closed" }
: { type: "Document" };
}
const clickListenerTracker = new ClickListenerTracker();
const hookManager = new HookManager();
function onAddEventListener(
element?: unknown,
eventName?: unknown,
listener?: unknown,
options?: unknown
): void {
if (
!(
typeof eventName === "string" &&
clickableEventNames.includes(eventName) &&
element instanceof HTMLElement2 &&
(typeof listener === "function" ||
(typeof listener === "object" &&
listener !== null &&
typeof (listener as EventListenerObject).handleEvent ===
"function"))
)
) {
return;
}
// If `{ once: true }` is used, listen once ourselves so we can track the
// removal of the listener when it has triggered.
if (
typeof options === "object" &&
options !== null &&
Boolean((options as AddEventListenerOptions).once)
) {
apply(addEventListener, element, [
eventName,
() => {
onRemoveEventListener(element, eventName, listener, options);
},
options,
]);
}
clickListenerTracker.queueItem({
type: "method",
added: true,
element,
eventName,
listener,
options,
});
}
function onRemoveEventListener(
element?: unknown,
eventName?: unknown,
listener?: unknown,
options?: unknown
): void {
if (
!(
typeof eventName === "string" &&
clickableEventNames.includes(eventName) &&
element instanceof HTMLElement2 &&
(typeof listener === "function" ||
(typeof listener === "object" &&
listener !== null &&
typeof (listener as EventListenerObject).handleEvent ===
"function"))
)
) {
return;
}
clickListenerTracker.queueItem({
type: "method",
added: false,
element,
eventName,
listener,
options,
});
}
function onPropChangePreHook(element: unknown): QueueItem | undefined {
if (!(element instanceof HTMLElement2)) {
return undefined;
}
return {
type: "prop",
hadListener: hasClickListenerProp(element),
element,
};
}
function onPropChange({
prehookData,
}: {
prehookData: QueueItem | undefined;
}): void {
if (prehookData !== undefined) {
clickListenerTracker.queueItem(prehookData);
}
}
function onShadowRootCreated({
returnValue: shadowRoot,
}: {
returnValue: ShadowRoot;
}): void {
if (communicator !== undefined) {
communicator.onInjectedMessage({
type: "ShadowRootCreated",
shadowRoot,
});
} else if (shadowRoot.mode === "open") {
// In “open” mode, ElementManager can access shadow roots via the
// `.shadowRoot` property on elements. All we need to do here is tell
// the ElementManager that a shadow root has been created.
sendElementEvent(OPEN_SHADOW_ROOT_CREATED_EVENT, shadowRoot.host);
} else {
// In “closed” mode, ElementManager cannot easily access shadow roots.
// By creating a temporary element inside the shadow root and emitting
// events on that element, ElementManager can obtain the shadow root
// via the `.getRootNode()` method and store it in a WeakMap. This is
// done in two steps – see the listeners in ElementManager to learn why.
const tempElement = createElement("div");
// Expose `tempElement`:
sendElementEvent(CLOSED_SHADOW_ROOT_CREATED_1_EVENT, tempElement);
apply(appendChild, shadowRoot, [tempElement]);
// Expose `shadowRoot`:
sendElementEvent(
CLOSED_SHADOW_ROOT_CREATED_2_EVENT,
tempElement,
undefined,
{
// Force firing the event while `tempElement` is still inside the
// closed shadow root. Normally we don’t do that, since events from
// within closed shadow roots appear to come from its host element,
// and the whole point of `sendElementEvent` is to set
// `event.target` to `element`, not to some shadow root. But in this
// special case `event.target` doesn’t matter and we _need_
// `tempElement` to be inside `shadowRoot` so that `.getRootNode()`
// returns it.
type: "Document",
}
);
apply(removeChild, shadowRoot, [tempElement]);
}
}
function onFlush(): void {
clickListenerTracker.flushQueue(infiniteDeadline);
}
function onReset(): void {
if (!PROD) {
consoleLog(`[${META_SLUG}] Resetting injected.ts`, RESET_EVENT);
}
// ElementManager removes listeners itself on reset.
if (communicator === undefined) {
document.removeEventListener(FLUSH_EVENT, onFlush, true);
document.removeEventListener(RESET_EVENT, onReset, true);
}
// Reset the overridden methods when the extension is shut down.
clickListenerTracker.reset();
hookManager.reset();
}
// Use `document` rather than `window` in order not to appear in the “Global
// event listeners” listing in devtools.
const target = communicator ?? document;
target.addEventListener(FLUSH_EVENT, onFlush, true);
target.addEventListener(RESET_EVENT, onReset, true);
hookManager.hookInto(
win.EventTarget.prototype,
"addEventListener",
(_data, ...args) => {
onAddEventListener(...args);
}
);
hookManager.hookInto(
win.EventTarget.prototype,
"removeEventListener",
(_data, ...args) => {
onRemoveEventListener(...args);
}
);
// Hook into `.onclick` and similar.
for (const prop of clickableEventProps) {
hookManager.hookInto(
win.HTMLElement.prototype,
prop,
onPropChange,
onPropChangePreHook
);
}
hookManager.hookInto(
win.Element.prototype,
"attachShadow",
onShadowRootCreated
);
hookManager.conceal();
}; | the_stack |
import { override } from '@microsoft/decorators';
import { Log } from '@microsoft/sp-core-library';
import {
BaseListViewCommandSet,
Command,
IListViewCommandSetListViewUpdatedParameters,
IListViewCommandSetExecuteEventParameters
} from '@microsoft/sp-listview-extensibility';
import "@pnp/polyfill-ie11";
import { Web, RenderListDataOptions } from '@pnp/sp/presets/all';
import { HttpClient } from '@microsoft/sp-http';
import * as JSZip from 'jszip';
import * as FileSaver from 'file-saver';
import WaitDialog from './WaitDialog';
import * as strings from 'PdfExportCommandSetStrings';
export interface IPdfExportCommandSetProperties {
}
interface SharePointFile {
serverRelativeUrl: string;
pdfUrl: string;
fileType: string;
pdfFileName: string;
}
const LOG_SOURCE: string = 'PdfExportCommandSet';
const DIALOG = new WaitDialog({});
export default class PdfExportCommandSet extends BaseListViewCommandSet<IPdfExportCommandSetProperties> {
private _validExts: string[] = ['html','csv', 'doc', 'docx', 'odp', 'ods', 'odt', 'pot', 'potm', 'potx', 'pps', 'ppsx', 'ppsxm', 'ppt', 'pptm', 'pptx', 'rtf', 'xls', 'xlsx'];
@override
public onInit(): Promise<void> {
Log.info(LOG_SOURCE, 'Initialized PdfExportCommandSet');
return Promise.resolve();
}
@override
public onListViewUpdated(event: IListViewCommandSetListViewUpdatedParameters): void {
const exportCommand: Command = this.tryGetCommand('EXPORT');
if (exportCommand) {
exportCommand.visible = event.selectedRows.length > 0;
}
const saveCommand: Command = this.tryGetCommand('SAVE_AS');
if (saveCommand) {
saveCommand.visible = event.selectedRows.length > 0;
}
}
@override
public async onExecute(event: IListViewCommandSetExecuteEventParameters): Promise<void> {
let itemIds = event.selectedRows.map(i => i.getValueByName("ID"));
let fileExts = event.selectedRows.map(i => i.getValueByName("File_x0020_Type").toLocaleLowerCase());
DIALOG.showClose = false;
DIALOG.error = "";
for (let i = 0; i < fileExts.length; i++) {
const ext = fileExts[i];
if (this._validExts.indexOf(ext) === -1) {
DIALOG.title = strings.ExtSupport;
DIALOG.message = strings.CurrentExtSupport + ": " + this._validExts.join(", ") + ".";
DIALOG.showClose = true;
DIALOG.show();
return;
}
}
switch (event.itemId) {
case 'EXPORT': {
DIALOG.title = strings.DownloadAsPdf;
DIALOG.message = `${strings.GeneratingFiles}...`;
DIALOG.show();
let files = await this.generatePdfUrls(itemIds);
let isOk = true;
if (itemIds.length == 1) {
const file = files[0];
DIALOG.message = `${strings.Processing} ${file.pdfFileName}...`;
DIALOG.render();
const response = await this.context.httpClient.get(file.pdfUrl, HttpClient.configurations.v1);
if (response.ok) {
const blob = await response.blob();
FileSaver.saveAs(blob, file.pdfFileName);
} else {
const error = await response.json();
let errorMessage = error.error.innererror ? error.error.innererror.code : error.error.message;
DIALOG.error = `${strings.FailedToProcess} ${file.pdfFileName} - ${errorMessage}<br/>`;
DIALOG.render();
isOk = false;
}
} else {
const zip: JSZip = new JSZip();
for (let i = 0; i < files.length; i++) {
const file = files[i];
DIALOG.message = `${strings.Processing} ${file.pdfFileName}...`;
DIALOG.render();
const response = await this.context.httpClient.get(file.pdfUrl, HttpClient.configurations.v1);
if (response.ok) {
const blob = await response.blob();
zip.file(file.pdfFileName, blob, { binary: true });
} else {
const error = await response.json();
let errorMessage = error.error.innererror ? error.error.innererror.code : error.error.message;
DIALOG.error = `${strings.FailedToProcess} ${file.pdfFileName} - ${errorMessage}<br/>`;
DIALOG.render();
isOk = false;
}
}
if (isOk) {
zip.file("Powered by Puzzlepart.txt", "https://www.puzzlepart.com/");
let d = new Date();
let dateString = d.getFullYear() + "-" + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) + '-' + ('0' + d.getHours()).slice(-2) + '-' + ('0' + d.getMinutes()).slice(-2) + '-' + ('0' + d.getSeconds()).slice(-2);
const zipBlob = await zip.generateAsync({ type: "blob" });
FileSaver.saveAs(zipBlob, `files-${dateString}.zip`);
}
}
if (!isOk) {
DIALOG.showClose = true;
DIALOG.render();
}
else {
DIALOG.close();
}
break;
}
case 'SAVE_AS': {
DIALOG.title = strings.SaveAsPdf;
DIALOG.message = `${strings.GeneratingFiles}...`;
DIALOG.show();
let files = await this.generatePdfUrls(itemIds);
let ok = await this.saveAsPdf(files);
if (ok) {
DIALOG.close();
} else {
DIALOG.showClose = true;
DIALOG.render();
}
break;
}
default:
throw new Error('Unknown command');
}
}
private async saveAsPdf(files: SharePointFile[]): Promise<boolean> {
const web = Web(this.context.pageContext.web.absoluteUrl);
let isOk = true;
for (let i = 0; i < files.length; i++) {
const file = files[i];
DIALOG.message = `${strings.Processing} ${file.pdfFileName}...`;
DIALOG.render();
let pdfUrl = file.serverRelativeUrl.replace("." + file.fileType, ".pdf");
let exists = true;
try {
await web.getFileByServerRelativePath(pdfUrl).get();
DIALOG.error += `${file.pdfFileName} ${strings.Exists}.<br/>`;
DIALOG.render();
isOk = false;
} catch (error) {
exists = false;
}
if (!exists) {
let response = await this.context.httpClient.get(file.pdfUrl, HttpClient.configurations.v1);
if (response.ok) {
let blob = await response.blob();
await web.getFileByServerRelativeUrl(file.serverRelativeUrl).copyTo(pdfUrl);
await web.getFileByServerRelativeUrl(pdfUrl).setContentChunked(blob);
const item = await web.getFileByServerRelativeUrl(pdfUrl).getItem("File_x0020_Type");
// Potential fix for edge cases where file type is not set correctly
if (item["File_x0020_Type"] !== "pdf") {
await item.update({
"File_x0020_Type": "pdf"
});
}
} else {
const error = await response.json();
let errorMessage = error.error.innererror ? error.error.innererror.code : error.error.message;
DIALOG.error += `${strings.FailedToProcess}s ${file.pdfFileName} - ${errorMessage}<br/>`;
DIALOG.render();
isOk = false;
}
}
}
return isOk;
}
private async generatePdfUrls(listItemIds: string[]): Promise<SharePointFile[]> {
let web = Web(this.context.pageContext.web.absoluteUrl);
let options: RenderListDataOptions = RenderListDataOptions.EnableMediaTAUrls | RenderListDataOptions.ContextInfo | RenderListDataOptions.ListData | RenderListDataOptions.ListSchema;
var values = listItemIds.map(i => { return `<Value Type='Counter'>${i}</Value>`; });
const viewXml: string = `
<View Scope='RecursiveAll'>
<Query>
<Where>
<In>
<FieldRef Name='ID' />
<Values>
${values.join("")}
</Values>
</In>
</Where>
</Query>
<RowLimit>${listItemIds.length}</RowLimit>
</View>`;
let response = await web.lists.getById(this.context.pageContext.list.id.toString()).renderListDataAsStream({ RenderOptions: options, ViewXml: viewXml }) as any;
// "{.mediaBaseUrl}/transform/pdf?provider=spo&inputFormat={.fileType}&cs={.callerStack}&docid={.spItemUrl}&{.driveAccessToken}"
let pdfConversionUrl = response.ListSchema[".pdfConversionUrl"];
let mediaBaseUrl = response.ListSchema[".mediaBaseUrl"];
let callerStack = response.ListSchema[".callerStack"];
let driveAccessToken = response.ListSchema[".driveAccessToken"];
let pdfUrls: SharePointFile[] = [];
response.ListData.Row.forEach(element => {
let fileType = element[".fileType"];
let spItemUrl = element[".spItemUrl"];
let pdfUrl = pdfConversionUrl
.replace("{.mediaBaseUrl}", mediaBaseUrl)
.replace("{.fileType}", fileType)
.replace("{.callerStack}", callerStack)
.replace("{.spItemUrl}", spItemUrl)
.replace("{.driveAccessToken}", driveAccessToken);
let pdfFileName = element.FileLeafRef.replace(fileType, "pdf");
pdfUrls.push({ serverRelativeUrl: element["FileRef"], pdfUrl: pdfUrl, fileType: fileType, pdfFileName: pdfFileName });
});
return pdfUrls;
}
} | the_stack |
* Standard Libraries
*/
import * as fs from "fs";
import * as path from "path";
import * as url from "url";
import * as http from "http";
import * as https from "https";
import * as querystring from "querystring";
/**
* Third-Part Libraries
*/
import marked from "marked";
/**
* Bilibili Column Markdown Core Class
*
* @since 2020-03-21
* @author zihengCat
*/
class BiliColumnMarkdown {
/**
* 本地 Markdown 路径
*/
private markdownPath: string = "";
/**
* 原始 Markdown 文本
*/
private markdownText: string = "";
/**
* 转换 HTML 文本
*/
private HTMLText: string = "";
/**
* 用户认证 Cookies
*/
private cookiesText: string = "";
/**
* 用户偏好设置选项
*/
private userPreferences: Map<string, string> = new Map<string, string>();
/**
* 本地图片地址暂存区(Array of Tuple)
* ```
* [
* [ imageId_1, localImageURL_1 ],
* [ imageId_2, localImageURL_2 ],
* ...,
* [ imageId_n, localImageURL_n ]
* ]
* ```
* > 注:暂存区数据结构
*/
private localImageURLs: Array<[string, string]> = [];
/**
* B站上传图片地址暂存区(Array of Tuple)
* ```
* [
* [ imageId_1, biliImageURL_1 ],
* [ imageId_2, biliImageURL_2 ],
* ...,
* [ imageId_n, biliImageURL_n ]
* ]
* ```
* > 注:暂存区数据结构
*/
private biliImageURLs: Array<[string, string]> = [];
/**
* 专栏表单数据结构
*/
private formTemplate: any | object = {
"title": "", /* 文章标题(自动生成) */
"banner_url": "", /* 文章头图(可为空) */
"content": "", /* 文章 HTML 内容(自动生成) */
"summary": "", /* 文章小结(自动生成) */
"words": 0, /* 文章字数(自动生成) */
"category": 0, /* 文章分类 */
"list_id": 0, /* 文章文集(轻小说) */
"tid": 0, /* 不明字段 */
"reprint": 1, /* 可否复制(必需[0, 1]) */
"tags": "", /* 文章标签 */
"image_urls": "",
"origin_image_urls": "",
"dynamic_intro": "", /* 文章推荐语(可为空) */
// "aid": "", /* 可有可无 -> 有: 修改草稿, 无: 新增草稿 */
"csrf": "" /* 跨域认证信息(自动生成) */
}
/**
* 默认无参构造函数
*
* @param void
*/
public constructor() {
// ...
}
/**
* 功能函数: 检查用户是否配置了自定义参数
*
* @param key
* @returns `boolean`
*/
private checkUserPreferences(key: string): boolean {
if (this.userPreferences.get(key) !== undefined) {
return true;
} else {
return false;
}
}
/**
* 执行流程:
* -> 取得 Markdown 文档与用户配置选项
* -> Markdown 转换 HTML
* -> 上传本地图片取得B站外链
* -> 替换本地图片地址为B站外链地址
* -> 合成提交表单发送更新
*
* @param markdownPath
* @param userConfig
* @returns void
*/
public startProcess(markdownPath: string, userConfig: object): void {
/* Bug-Fix: Path should be trimmed */
markdownPath = markdownPath.trim();
/* 解析 Markdown 文档 -> 绝对路径 */
this.markdownPath = path.resolve(markdownPath);
/* 读取 Markdown 文本内容 -> UTF-8 */
this.markdownText = fs.readFileSync(markdownPath, "utf-8");
/* 读取用户配置信息 -> Map<String, String> */
let userConfigMap = this.objToMap(userConfig);
this.userPreferences = userConfigMap;
/* 计算 CSRF 值 */
let csrf: string = <string> userConfigMap.get("cookies");
this.userPreferences.set("csrf", this.csrfGenerate(csrf));
/* TODO: 获取用户自定义 UA */
// ...
/* 转换 Markdown 文档为 HTML 文档 */
this.HTMLText = this.markdownToHTML(this.markdownText);
// Debug Print...
// console.log(this.HTMLText);
/* 带图片/无图片提交 */
if (this.hasLocalImages(this.HTMLText)) {
this.postWithImagesForm();
} else {
this.postPureHTMLForm();
}
}
/**
* Object 转换 Map
*
* @param obj
* @returns `Map<string, string>`
*/
private objToMap(obj: any): Map<string, string> {
let map = new Map<string, string>();
if (obj === undefined) {
return map;
}
for (let key in obj) {
map.set(key, obj[key]);
}
return map;
}
/* 提交 HTML 表单 */
private postPureHTMLForm(): void {
this.postRequest(
this.HTMLFormGenerate(),
"html"
);
}
private postWithImagesForm(): void {
this.postLocalImages();
}
/* 使用转换后数据生成 HTML 发送表单 */
private HTMLFormGenerate(): object {
let formData: any | object = {
// ...
};
/* 深拷贝模版数据 */
for (let key in this.formTemplate) {
formData[key] = this.formTemplate[key];
}
/* 用户自定义配置 */
if (this.checkUserPreferences("title") === true) {
/* 使用用户自定义标题 */
formData["title"] = this.userPreferences.get("title");
} else {
/* 使用默认标题 */
let titleName: string = path.basename(this.markdownPath);
titleName = titleName.slice(
0, titleName.lastIndexOf(".")
);
formData["title"] = titleName;
}
/* 覆写 CSRF 值 */
formData["csrf"] = this.userPreferences.get("csrf");
/* 覆写相关信息 */
formData["content"] = this.HTMLText;
formData["words"] = this.wordsCount(this.HTMLText);
formData["summary"] = this.summaryGenerate(this.HTMLText);
/* 返回合成表单数据 */
return formData;
}
/**
* 核心函数: 提交表单数据
* @param form
* @param flag
*/
private postRequest(form: any, flag: string): void {
let postOptions: any | object = {
method: 'POST',
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
/* 计算文档长度 */
'Content-Length': Buffer.byteLength(querystring.stringify(form)),
'DNT': '1',
'Origin': 'https://member.bilibili.com',
/* 构建 Referer 头 */
'Referer': 'https://member.bilibili.com/article-text/home',
/*
'Referer': 'https://member.bilibili.com/article-text/home?aid=' +
this.userPreferences["aid"],
*/
/* 默认 UA */
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
/* 构建 Cookie */
'Cookie': this.userPreferences.get("cookies")
}
};
if (flag === "html") {
// console.log(form);
/* 添加提交地址 */
postOptions["host"] = "api.bilibili.com";
postOptions["path"] = "/x/article/creative/draft/addupdate";
/* 发送 HTML 表单 */
let req: http.ClientRequest =
http.request(
postOptions,
function(res: http.IncomingMessage): void {
console.log("[INFO]: StatusCode -> ", res.statusCode);
//console.log("Headers: ", JSON.stringify(res.headers));
res.setEncoding("utf-8");
res.on("data", function(chunk: any): void {
console.log("[INFO]: MessageData -> " + chunk);
});
res.on("end", function(): void {
console.log(
"[INFO]: " + "Operations done successfully! -> " +
new Date()
);
});
});
req.on("error", function(e: Error): void {
console.error("[ERROR]: " + e.message);
});
/* 序列化表单数据 */
req.write(
querystring.stringify(form)
);
req.end();
} else if (flag == "image") {
/* 图片提交头 */
postOptions["host"] = "member.bilibili.com";
postOptions["path"] = "/x/web/article/upcover";
postOptions["headers"]["X-Requested-With"] = "XMLHttpRequest";
/** NOTE:
* Keep a reference of this instance.
*/
let bReference: BiliColumnMarkdown = this;
/* --------------- */
/* Promise Execute */
/* ----------------*/
new Promise(function(resolve, reject) {
/**
* [
* '{"code": 0, "message": "0"}',
* '{"code": 0, "message": "1"}'
* ]
*/
let ret: any[] = [];
/**
* cover -> Image Base64
*/
let imageId = form["cover"].slice(-50, -30);
let req: http.ClientRequest =
http.request(
postOptions,
function(res: http.IncomingMessage): void {
//console.log("[INFO]: StatusCode -> ", res.statusCode);
//console.log("Headers: ", JSON.stringify(res.headers));
res.setEncoding("utf-8");
res.on("data", function(chunk: any): void {
//console.log("[INFO]: MessageData -> " + chunk);
ret.push(chunk);
});
res.on("end", function(): void {
/**
* {
* "code": 0,
* "message": "0",
* "ttl": 1,
* "data": {
* "size": 123456,
* "url":"http://i0.hdslb.com/bfs/article/xxx"
* }
* }
*/
let retMessage: any | object = JSON.parse(
ret.toString()
);
if (retMessage["code"] == 0) {
/* 返回格式化字符串 */
resolve({
"biliObject": bReference,
"retMessage": retMessage,
"imageId": imageId
});
} else {
console.error("[ERROR]: " + retMessage);
throw("[ERROR]: Image uploads unsuccessful...");
}
});
});
req.on("error", function(e: Error): void {
console.error("[ERROR]: " + e.message);
});
/* 序列化表单数据 */
req.write(
querystring.stringify(form)
);
req.end();
}).then(
function(result: any) {
// console.log("[Resolve]: " + result);
let biliObject: BiliColumnMarkdown = result["biliObject"];
let imageId: string = result["imageId"];
let retMessage: any | object = result["retMessage"];
let biliImageURL: string = retMessage["data"]["url"];
// console.log(retMessage);
biliObject.pushToBiliImageURLs(
[imageId, biliImageURL]
);
biliObject.replaceLocalImageURLs();
},
function(reject: any) {
console.error("[Reject]: " + reject);
});
} else {
throw "[ERROR]: Unsupported Operations!";
}
}
/**
* 核心函数: `Markdown` 转 `Bilibili Compatible HTML`。
*
* @param markdownText
* @returns string
*/
private markdownToHTML(markdownText: string): string {
/* 自定义生成器 */
let myRenderer: marked.Renderer = new marked.Renderer();
/**
* 覆写`标题`生成规则「弃用」->
* `marked v0.4.0`已支持`headerIds`选项
*/
/*
myRenderer.heading = function (text, level) {
return '<h' + level + '>' + text +
'</h' + level + '>';
}
*/
/* 覆写`代码块`生成规则 */
myRenderer.code = function(
code: string,
language: string
): string {
return '<figure class="code-box">' +
'<pre class="language-' + language + '" ' +
'data-lang="' + language + '">' +
'<code class="language-${lang}">'.replace("${lang}", language) +
code + '</code>' +
'</pre>' +
'</figure>';
}
/* 覆写`图片`生成规则 */
myRenderer.image = function(
href: string,
title: string,
text: string
): string {
return '<figure class="img-box">' +
'<img src="${imageSrc}" />'.replace(
"${imageSrc}", href
) +
'<figcaption class="caption">${captionText}</figcaption>'.replace(
"${captionText}", text
) + '</figure>';
}
/* 覆写`删除线`生成规则 */
myRenderer.del = function(text: string): string {
return '<span style="text-decoration: line-through;">' +
text +
'</span>';
}
/* 覆写`分隔线`生成规则 */
myRenderer.hr = function(): string {
/* HardCode here... */
let biliCutOff: string =
"https://i0.hdslb.com/bfs/article/0117cbba35e51b0bce5f8c2f6a838e8a087e8ee7.png";
return '<figure class="img-box">' +
'<img src="${cutoff}" class="cut-off-1" />'.replace("${cutoff}", biliCutOff) +
'</figure>'
}
/* 生成器配置选项 */
marked.setOptions({
renderer: myRenderer, /* 使用自定义生成器 */
sanitize: true, /* 内联 HTML 功能: 禁用 */
headerIds: false, /* 自动生成`headerIds`功能: 禁用 */
/* 是否启用`highlight.js`代码高亮 */
/*
highlight: function (code) {
return highlight.highlightAuto(code).value;
}
*/
});
/* 返回转换后 HTML 文本 */
let convertedHTML: string = marked(markdownText);
return convertedHTML;
}
/**
* 核心函数: 文本计数
*/
private wordsCount(HTMLText: string): number {
/* 去除 HTML <tags> */
HTMLText = HTMLText.replace(/<\/?[^>]*>/g, "");
/* 去除行末空白符 */
HTMLText = HTMLText.replace(/[ | ]*\n/g, "");
/* 去除多余空白行 */
HTMLText = HTMLText.replace(/\n[\s| | ]*\r/g, "");
/* 去除所有空格符 */
HTMLText = HTMLText.replace(/ /ig, "");
/* 去除所有换行符 */
HTMLText = HTMLText.replace(/\n/g, "");
HTMLText = HTMLText.replace(/\r\n/g, "");
/* 返回处理后 HTML 文本长度 */
return HTMLText.length;
}
/**
* 核心函数: 获取文章小结
*/
private summaryGenerate(HTMLText: string): string {
/* 去除 HTML <tags> */
let summaryText: string = HTMLText.replace(/<\/?[^>]*>/g, "");
/* 去除所有换行符 */
summaryText = summaryText.replace(/\n/g, "");
summaryText = summaryText.replace(/\r\n/g, "");
/* 取前 100 字符 */
return summaryText.slice(0, 100);
}
/**
* 功能函数: 从 Cookie 中获取 CSRF 信息
*/
private csrfGenerate(cookiesText: string): string {
function isVaildCookies(cookies_str: string): boolean {
/* 检查 Cookies 是否包含关键字段 */
if (cookies_str.match(/sid=/g) == null ||
cookies_str.match(/DedeUserID=/g) == null ||
cookies_str.match(/DedeUserID__ckMd5=/g) == null ||
cookies_str.match(/bili_jct=/g) == null ||
cookies_str.match(/SESSDATA=/g) == null ) {
throw("[ERROR]: Invaild `cookies`...");
}
return true;
}
isVaildCookies(cookiesText);
let cookies_str: string[] = cookiesText.split(";");
for (let i: number = 0; i < cookies_str.length; ++i) {
cookies_str[i] = cookies_str[i].trim();
}
let csrf: string = "";
for (let i: number = 0; i < cookies_str.length; ++i) {
/* 关键字段 -> bili_jct */
if (cookies_str[i].indexOf("bili_jct=") == 0) {
csrf = cookies_str[i].slice(
cookies_str[i].indexOf("=") + 1
);
}
}
return csrf;
}
/**
* 功能函数: 检测 HTML 文档中是否包含本地图片
*
* @param HTMLText
* @returns boolean
*/
private hasLocalImages(HTMLText: string): boolean {
let hasImage: RegExpMatchArray | null = HTMLText.match(/src=.* \/>/g);
if (hasImage == null) {
return false;
} else {
return true;
}
}
/* 处理 HTML 中本地图片 */
private postLocalImages() {
function checkLocally(src: string) {
if (src.indexOf("http") == 0 ||
src.indexOf("https") == 0) {
/* B站不支持外链图片,
关闭外链图片功能 */
//throw("[ERROR]: Unsupported outer-linking images...");
return false;
} else {
return true;
}
}
/* 获取所有图片地址
格式: <img src="%src" /> */
let imagesArr: RegExpMatchArray | null = this.HTMLText.match(/src=.* \/>/g);
/* 优化项 -> 如果不存在本地图片, 可直接返回 */
if (imagesArr == null) {
return;
}
let localImagesArr: string[] = Array<string>();
/* 找到所有本地图片 URL */
for (let i: number = 0; i < imagesArr.length; ++i) {
let imageURL: string = imagesArr[i].slice(
imagesArr[i].indexOf('"') + 1,
imagesArr[i].lastIndexOf('"')
);
if (checkLocally(imageURL) == true) {
localImagesArr.push(imageURL);
}
}
for (let i: number = 0; i < localImagesArr.length; ++i) {
/* 使用图片绝对路径 */
let imageFullPath: string = path.resolve(
path.dirname(this.markdownPath),
localImagesArr[i]
);
/* 生成图片上传表单 */
let imageForm: any | object = this.imagesFormGenerate(imageFullPath);
/* 取图片特征值作图片ID */
let imageId: string = imageForm["cover"].slice(-50, -30);
/* 图片地址存入本地图片暂存区 */
this.localImageURLs.push(
[imageId, localImagesArr[i]]
);
/* 上传图片至B站服务器 */
this.postRequest(imageForm, "image");
}
}
/**
* 生成图片发送表单
* @param imageURL
* @param csrf
* @returns Image Form Object
*/
private imagesFormGenerate(
imageURL: string,
csrf: any | string = this.userPreferences.get("csrf")
): object {
/* 功能函数: 图片转换 Base64 编码 */
function imageToBase64(imageSource: string): string {
/* -------------------------------
* 图片 Base64 格式头
* -------------------------------
* PNG -> data:image/png;base64,
* JPEG -> data:image/jpeg;base64,
* GIF -> data:image/gif;base64,
* ------------------------------- */
if (imageSource.indexOf('http') != 0) {
let imagePrefix: string = "";
let imageData: Buffer = fs.readFileSync(imageSource);
let imageBase64 = imageData.toString("base64");
if (path.extname(imageSource) == ".png" ||
path.extname(imageSource) == ".PNG") {
imagePrefix = "data:image/png;base64,";
} else if (path.extname(imageSource) == ".jpg" ||
path.extname(imageSource) == ".jpeg"||
path.extname(imageSource) == ".JPG") {
imagePrefix = "data:image/jpeg;base64,";
} else if (path.extname(imageSource) == ".gif") {
imagePrefix = "data:image/gif;base64,";
}
return imagePrefix + imageBase64;
} else {
throw "[ERROR]: Unsupported image type!"
}
}
/* 构建图片上传表单返回 */
let imagePostForm: object = {
"cover": imageToBase64(imageURL),
"csrf": csrf
};
return imagePostForm;
}
private pushToBiliImageURLs(aPair: [string, string]): void {
this.biliImageURLs.push(aPair);
}
/**
* 将 HTML 中的本地图片地址替换为B站图片地址
*/
private replaceLocalImageURLs(): void {
function findLocalImageURL(
imageId: string,
imageURLs: Array<[string, string]>
): string {
let retLocalImageURL = "";
for (let i: number = 0; i < imageURLs.length; ++i) {
let e: [string, string] = imageURLs[i];
if (e[0] === imageId) {
retLocalImageURL = e[1];
}
}
if (retLocalImageURL === "") {
throw "[ERROR]: Something wrong when processing local images...";
}
return retLocalImageURL;
}
/* 本地图片已全部上传完成 */
if (this.localImageURLs.length != 0 &&
this.biliImageURLs.length != 0 &&
(this.biliImageURLs.length ==
this.localImageURLs.length)) {
/* 替换图片链接地址 */
for (let i: number = 0; i < this.biliImageURLs.length; ++i) {
let imageId: string = this.biliImageURLs[i][0];
let biliImageURL: string = this.biliImageURLs[i][1];
let localImageURL: string = findLocalImageURL(
imageId, this.localImageURLs
);
//console.log(localImageURL);
//console.log(biliImageURL);
//console.log(this.HTMLText);
this.HTMLText =
this.HTMLText.replace(
new RegExp(localImageURL, "gm"),
biliImageURL
);
//console.log(this.HTMLText);
console.log(
"[INFO]: Image `" +
localImageURL + "` " +
"uploads successful!"
);
}
/* 一次性全部提交 */
this.postRequest(this.HTMLFormGenerate(), "html");
} else {
/* 本地图片未全部上传完成 */
//console.log("Do nothing...");
}
}
}
/* 导出模块 */
export {
BiliColumnMarkdown
};
/* EOF */ | the_stack |
import {
ErrorConstant,
ExtensionPriority,
ExtensionTag,
ExtensionTagType,
} from '@remirror/core-constants';
import {
assertGet,
entries,
invariant,
isArray,
isFunction,
isNullOrUndefined,
isPlainObject,
isString,
object,
toString,
} from '@remirror/core-helpers';
import type {
ApplySchemaAttributes,
DynamicAttributeCreator,
EditorSchema,
JsonPrimitive,
Mark,
MarkExtensionSpec,
MarkSpecOverride,
NodeExtensionSpec,
NodeMarkOptions,
NodeSpecOverride,
ProsemirrorAttributes,
ProsemirrorNode,
SchemaAttributes,
SchemaAttributesObject,
Static,
Transaction,
} from '@remirror/core-types';
import {
getDefaultBlockNode,
getMarkRange,
isElementDomNode,
isProsemirrorMark,
isProsemirrorNode,
} from '@remirror/core-utils';
import { MarkSpec, NodeSpec, Schema } from '@remirror/pm/model';
import { ignoreUpdateForSuggest } from '@remirror/pm/suggest';
import {
AnyExtension,
extension,
GetMarkNameUnion,
GetNodeNameUnion,
isMarkExtension,
isNodeExtension,
PlainExtension,
} from '../extension';
import type { CreateExtensionPlugin } from '../types';
import type { CombinedTags } from './tags-extension';
/**
* This is the schema extension which creates the schema and provides extra
* attributes as defined in the manager or the extension settings.
*
* @remarks
*
* The schema is the most important part of the remirror editor. This is the
* extension responsible for creating it, injecting extra attributes and
* managing the plugin which is responsible for making sure dynamically created
* attributes are updated.
*
* In order to add extra attributes the following would work.
*
* ```ts
* import { RemirrorManager } from 'remirror';
* import uuid from 'uuid';
* import hash from 'made-up-hasher';
*
* const manager = RemirrorManager.create([], {
* extraAttributes: [
* {
* identifiers: 'nodes',
* attributes: {
* awesome: {
* default: 'awesome',
* parseDOM: (domNode) => domNode.getAttribute('data-awesome'),
* toDOM: (attrs) => ([ 'data-awesome', attrs.awesome ])
* },
* },
* },
* { identifiers: ['paragraph'], attributes: { id: { default: () => uuid() } } },
* { identifiers: ['bold'], attributes: { hash: (mark) => hash(JSON.stringify(mark.attrs)) } },
* ],
* })
* ```
*
* It is an array of identifiers and attributes. Setting the default to a
* function allows you to set up a dynamic attribute which is updated with the
* synchronous function that you provide to it.
*
* @category Builtin Extension
*/
@extension({ defaultPriority: ExtensionPriority.Highest })
export class SchemaExtension extends PlainExtension {
get name() {
return 'schema' as const;
}
/**
* The dynamic attributes for each node and mark extension.
*
* The structure will look like the following.
*
* ```ts
* {
* paragraph: { id: () => uid(), hash: (node) => hash(node) },
* bold: { random: () => Math.random(), created: () => Date.now() },
* };
* ```
*
* This object is used by the created plugin to listen for changes to the doc,
* and check for new nodes and marks which haven't yet applied the dynamic
* attribute and add the attribute.
*/
private readonly dynamicAttributes: DynamicSchemaAttributeCreators = {
marks: object(),
nodes: object(),
};
/**
* This method is responsible for creating, configuring and adding the
* `schema` to the editor. `Schema` is a special type in ProseMirror editors
* and with `remirror` it's all just handled for you.
*/
onCreate(): void {
const { managerSettings, tags, markNames, nodeNames, extensions } = this.store;
const { defaultBlockNode, disableExtraAttributes, nodeOverride, markOverride } =
managerSettings;
// True when the `defaultBlockNode` exists for this editor.
const isValidDefaultBlockNode = (name: string | undefined): name is string =>
!!(name && tags[ExtensionTag.Block].includes(name));
// The user can override the whole schema creation process by providing
// their own version. In that case we can exit early.
if (managerSettings.schema) {
const { nodes, marks } = getSpecFromSchema(managerSettings.schema);
this.addSchema(managerSettings.schema, nodes, marks);
// Exit early! 🙌
return;
}
// This nodes object is built up for each extension and then at the end it
// will be passed to the `Schema` constructor to create a new `schema`.
const nodes: Record<string, NodeSpec> = isValidDefaultBlockNode(defaultBlockNode)
? {
doc: object(),
// Ensure that this is the highest positioned block node by adding it
// to the object early. Later on it will be overwritten but maintain
// it's position.
[defaultBlockNode]: object(),
}
: object();
// Similar to the `nodes` object above this is passed to the `Schema`.
const marks: Record<string, MarkSpec> = object();
// Get the named extra attributes from the manager. This allows each extra
// attribute group added to the manager to be applied to the individual
// extensions which specified.
const namedExtraAttributes = getNamedSchemaAttributes({
settings: managerSettings,
gatheredSchemaAttributes: this.gatherExtraAttributes(extensions),
nodeNames: nodeNames,
markNames: markNames,
tags: tags,
});
for (const extension of extensions) {
// Pick the current attributes from the named attributes and merge them
// with the extra attributes which were added to the extension. Extra
// attributes added to the extension are prioritized.
namedExtraAttributes[extension.name] = {
...namedExtraAttributes[extension.name],
...extension.options.extraAttributes,
};
// There are several places that extra attributes can be ignored. This
// checks them all.
const ignoreExtraAttributes =
disableExtraAttributes === true ||
extension.options.disableExtraAttributes === true ||
extension.constructor.disableExtraAttributes === true;
if (isNodeExtension(extension)) {
// Create the spec and gather dynamic attributes for this node
// extension.
const { spec, dynamic } = createSpec({
createExtensionSpec: (extra, override) => extension.createNodeSpec(extra, override),
extraAttributes: assertGet(namedExtraAttributes, extension.name),
// Todo add support for setting overrides via the manager.
override: { ...nodeOverride, ...extension.options.nodeOverride },
ignoreExtraAttributes,
name: extension.constructorName,
tags: extension.tags,
});
// Store the node spec on the extension for future reference.
extension.spec = spec;
// Add the spec to the `nodes` object which is used to create the schema
// with the same name as the extension name.
nodes[extension.name] = spec as NodeSpec;
// Keep track of the dynamic attributes. The `extension.name` is the
// same name of the `NodeType` and is used by the plugin in this
// extension to dynamically generate attributes for the correct nodes.
if (Object.keys(dynamic).length > 0) {
this.dynamicAttributes.nodes[extension.name] = dynamic;
}
}
// Very similar to the previous conditional block except for marks rather
// than nodes.
if (isMarkExtension(extension)) {
// Create the spec and gather dynamic attributes for this mark
// extension.
const { spec, dynamic } = createSpec({
createExtensionSpec: (extra, override) => extension.createMarkSpec(extra, override),
extraAttributes: assertGet(namedExtraAttributes, extension.name),
// Todo add support for setting overrides via the manager.
override: { ...markOverride, ...extension.options.markOverride },
ignoreExtraAttributes,
name: extension.constructorName,
tags: extension.tags ?? [],
});
// Store the mark spec on the extension for future reference.
extension.spec = spec;
// Add the spec to the `marks` object which is used to create the schema
// with the same name as the extension name.
marks[extension.name] = spec as MarkSpec;
// Keep track of the dynamic attributes. The `extension.name` is the
// same name of the `MarkType` and is used by the plugin in this
// extension to dynamically generate attributes for the correct marks.
if (Object.keys(dynamic).length > 0) {
this.dynamicAttributes.marks[extension.name] = dynamic;
}
}
}
// Create the schema from the gathered nodes and marks.
const schema = new Schema({ nodes, marks, topNode: 'doc' });
// Add the schema and nodes marks to the store.
this.addSchema(
schema,
nodes as Record<string, NodeExtensionSpec>,
marks as Record<string, MarkExtensionSpec>,
);
}
/**
* This creates the plugin that is used to automatically create the dynamic
* attributes defined in the extra attributes object.
*/
createPlugin(): CreateExtensionPlugin {
return {
appendTransaction: (transactions, _, nextState) => {
// This creates a new transaction which will be used to update the
// attributes of any node and marks which
const { tr } = nextState;
// The dynamic attribute updates only need to be run if the document has
// been modified in a transaction.
const documentHasChanged = transactions.some((tr) => tr.docChanged);
if (!documentHasChanged) {
// The document has not been changed therefore no updates are
// required.
return null;
}
// The find children method could potentially be quite expensive. Before
// committing to that level of work let's check that there user has
// actually defined some dynamic attributes.
if (
Object.keys(this.dynamicAttributes.nodes).length === 0 &&
Object.keys(this.dynamicAttributes.marks).length === 0
) {
return null;
}
// This function loops through every node in the document and add the
// dynamic attributes when any relevant nodes have been added.
tr.doc.descendants((child, pos) => {
this.checkAndUpdateDynamicNodes(child, pos, tr);
this.checkAndUpdateDynamicMarks(child, pos, tr);
// This means that all nodes will be checked.
return true;
});
// If the transaction has any `steps` then it has been modified and
// should be returned i.e. appended to the additional transactions.
// However, if there are no steps then ignore and return `null`.
return tr.steps.length > 0 ? tr : null;
},
};
}
/**
* Add the schema and nodes to the manager and extension store.
*/
private addSchema(
schema: EditorSchema,
nodes: Record<string, NodeExtensionSpec>,
marks: Record<string, MarkExtensionSpec>,
) {
// Store the `nodes`, `marks` and `schema` on the manager store. For example
// the `schema` can be accessed via `manager.store.schema`.
this.store.setStoreKey('nodes', nodes);
this.store.setStoreKey('marks', marks);
this.store.setStoreKey('schema', schema);
// Add the schema to the extension store, so that all extension from this
// point have access to the schema via `this.store.schema`.
this.store.setExtensionStore('schema', schema);
this.store.setStoreKey('defaultBlockNode', getDefaultBlockNode(schema).name);
// Set the default block node from the schema.
for (const type of Object.values(schema.nodes)) {
if (type.name === 'doc') {
continue;
}
// Break as soon as the first non 'doc' block node is encountered.
if (type.isBlock || type.isTextblock) {
break;
}
}
}
/**
* Check the dynamic nodes to see if the provided node:
*
* - a) is dynamic and therefore can be updated.
* - b) has just been created and does not yet have a value for the dynamic
* node.
*
* @param node - the node
* @param pos - the node's position
* @param tr - the mutable ProseMirror transaction which is applied to create
* the next editor state
*/
private checkAndUpdateDynamicNodes(node: ProsemirrorNode, pos: number, tr: Transaction) {
// Check for matching nodes.
for (const [name, dynamic] of entries(this.dynamicAttributes.nodes)) {
if (node.type.name !== name) {
continue;
}
for (const [attributeName, attributeCreator] of entries(dynamic)) {
if (!isNullOrUndefined(node.attrs[attributeName])) {
continue;
}
// The new attributes which will be added to the node.
const attrs = { ...node.attrs, [attributeName]: attributeCreator(node) };
// Apply the new dynamic attribute to the node via the transaction.
tr.setNodeMarkup(pos, undefined, attrs);
// Ignore this update in the `prosemirror-suggest` plugin
ignoreUpdateForSuggest(tr);
}
}
}
/**
* Loop through the dynamic marks to see if the provided node:
*
* - a) is wrapped by a matching mark.
* - b) has just been added and doesn't yet have the dynamic attribute
* applied.
*
* @param node - the node
* @param pos - the node's position
* @param tr - the mutable ProseMirror transaction which is applied to create
* the next editor state.
*/
private checkAndUpdateDynamicMarks(node: ProsemirrorNode, pos: number, tr: Transaction) {
// Check for matching marks.
for (const [name, dynamic] of entries(this.dynamicAttributes.marks)) {
// This is needed to create the new mark. Even though a mark may already
// exist ProseMirror requires that a new one is created and added in
// order. More details available
// [here](https://discuss.prosemirror.net/t/updating-mark-attributes/776/2?u=ifi).
const type = assertGet(this.store.schema.marks, name);
// Get the attrs from the mark.
const mark = node.marks.find((mark) => mark.type.name === name);
// If the mark doesn't exist within the set then move to the next
// dynamically updated mark.
if (!mark) {
continue;
}
// Loop through to find if any of the required matches are missing from
// the dynamic attribute;
for (const [attributeName, attributeCreator] of entries(dynamic)) {
// When the attributes for this dynamic attributeName are already
// defined we should move onto the next item;
if (!isNullOrUndefined(mark.attrs[attributeName])) {
continue;
}
// Use the starting position of the node to calculate the range range of
// the current mark.
const range = getMarkRange(tr.doc.resolve(pos), type);
if (!range) {
continue;
}
// The { from, to } range which will be used to update the mark id
// attribute.
const { from, to } = range;
// Create the new mark with all the existing dynamic attributes applied.
const newMark = type.create({
...mark.attrs,
[attributeName]: attributeCreator(mark),
});
// Update the value of the mark. The only way to do this right now is to
// remove and then add it back again.
tr.removeMark(from, to, type).addMark(from, to, newMark);
// Ignore this update in the `prosemirror-suggest` plugin
ignoreUpdateForSuggest(tr);
}
}
}
/**
* Gather all the extra attributes that have been added by extensions.
*/
private gatherExtraAttributes(extensions: readonly AnyExtension[]) {
const extraSchemaAttributes: IdentifierSchemaAttributes[] = [];
for (const extension of extensions) {
if (!extension.createSchemaAttributes) {
continue;
}
extraSchemaAttributes.push(...extension.createSchemaAttributes());
}
return extraSchemaAttributes;
}
}
/**
* With tags, you can select a specific sub selection of marks and nodes. This
* will be the basis for adding advanced formatting to remirror.
*
* ```ts
* import { ExtensionTag } from 'remirror';
* import { createCoreManager, CorePreset } from 'remirror/extensions';
* import { WysiwygPreset } from 'remirror/extensions';
*
* const manager = createCoreManager(() => [new WysiwygPreset(), new CorePreset()], {
* extraAttributes: [
* {
* identifiers: {
* tags: [ExtensionTag.NodeBlock],
* type: 'node',
* },
* attributes: { role: 'presentation' },
* },
* ],
* });
* ```
*
* Each item in the tags array should be read as an `OR` so the following would
* match `Tag1` OR `Tag2` OR `Tag3`.
*
* ```json
* { tags: ["Tag1", "Tag2", "Tag3"] }
* ```
*
* The `type` property (`mark | node`) is exclusive and limits the type of
* extension names that will be matched. When `mark` is set it only matches with
* marks.
*/
export interface IdentifiersObject {
/**
* Determines how the array of tags are combined:
*
* - `all` - the extension only matches when all tags are present.
* - `any` - the extension will match if it includes any of the specified
* tags.
*
* This only affects the `tags` property.
*
* The saddest part about this property is that, as a UK resident, I've
* succumbed to using the Americanized spelling instead of the Oxford
* Dictionary defined spelling of `behaviour` 😢
*
* @default 'any'
*/
behavior?: 'all' | 'any';
/**
* Will find relevant names based on the defined `behaviour`.
*/
tags?: ExtensionTagType[];
/**
* Additional names to include. These will still be added even if the
* extension name matches with `excludeTags` member.
*/
names?: string[];
/**
* Whether to restrict by whether this is a [[`ProsemirrorNode`]] or a
* [[`Mark`]]. Leave blank to accept all types.
*/
type?: 'node' | 'mark';
/**
* Exclude these names from being matched.
*/
excludeNames?: string[];
/**
* Exclude these tags from being matched. Will always exclude if any of the
* tags
*/
excludeTags?: string[];
}
/**
* The extra identifiers that can be used.
*
* - `nodes` - match all nodes
* - `marks` - match all marks
* - `all` - match everything in the editor
* - `string[]` - match the selected node and mark names
* - [[`IdentifiersObject`]] - match by `ExtensionTag` and type name.
*/
export type Identifiers = 'nodes' | 'marks' | 'all' | readonly string[] | IdentifiersObject;
/**
* The interface for adding extra attributes to multiple node and mark
* extensions.
*/
export interface IdentifierSchemaAttributes {
/**
* The nodes or marks to add extra attributes to.
*
* This can either be an array of the strings or the following specific
* identifiers:
*
* - 'nodes' for all nodes
* - 'marks' for all marks
* - 'all' for all extensions which touch the schema.
*/
identifiers: Identifiers;
/**
* The attributes to be added.
*/
attributes: SchemaAttributes;
}
/**
* An object of `mark` and `node` dynamic schema attribute creators.
*/
interface DynamicSchemaAttributeCreators {
/**
* The dynamic schema attribute creators for all marks in the editor.
*/
marks: Record<string, Record<string, DynamicAttributeCreator>>;
/**
* The dynamic schema attribute creators for all nodes in the editor.
*/
nodes: Record<string, Record<string, DynamicAttributeCreator>>;
}
/**
* The schema attributes mapped to the names of the extension they belong to.
*/
type NamedSchemaAttributes = Record<string, SchemaAttributes>;
interface TransformSchemaAttributesProps {
/**
* The manager settings at the point of creation.
*/
settings: Remirror.ManagerSettings;
/**
* The schema attributes which were added to the `manager`.
*/
gatheredSchemaAttributes: IdentifierSchemaAttributes[];
/**
* The names of all the nodes within the editor.
*/
nodeNames: readonly string[];
/**
* The names of all the marks within the editor.
*/
markNames: readonly string[];
/**
* The tags that are being used by active extension right now.
*/
tags: CombinedTags;
}
/**
* Get the extension extra attributes created via the manager and convert into a
* named object which can be added to each node and mark spec.
*/
function getNamedSchemaAttributes(props: TransformSchemaAttributesProps): NamedSchemaAttributes {
const { settings, gatheredSchemaAttributes, nodeNames, markNames, tags } = props;
const extraAttributes: NamedSchemaAttributes = object();
if (settings.disableExtraAttributes) {
return extraAttributes;
}
const extraSchemaAttributes: IdentifierSchemaAttributes[] = [
...gatheredSchemaAttributes,
...(settings.extraAttributes ?? []),
];
for (const attributeGroup of extraSchemaAttributes ?? []) {
const identifiers = getIdentifiers({
identifiers: attributeGroup.identifiers,
nodeNames,
markNames,
tags,
});
for (const identifier of identifiers) {
const currentValue = extraAttributes[identifier] ?? {};
extraAttributes[identifier] = { ...currentValue, ...attributeGroup.attributes };
}
}
return extraAttributes;
}
interface GetIdentifiersProps {
identifiers: Identifiers;
nodeNames: readonly string[];
markNames: readonly string[];
tags: CombinedTags;
}
/**
* A predicate for checking if the passed in value is an `IdentifiersObject`.
*/
function isIdentifiersObject(value: Identifiers): value is IdentifiersObject {
return isPlainObject(value) && isArray(value.tags);
}
/**
* Get the array of names from the identifier that the extra attributes should
* be applied to.
*/
function getIdentifiers(props: GetIdentifiersProps): readonly string[] {
const { identifiers, nodeNames, markNames, tags } = props;
if (identifiers === 'nodes') {
return nodeNames;
}
if (identifiers === 'marks') {
return markNames;
}
if (identifiers === 'all') {
return [...nodeNames, ...markNames];
}
// This is already an array of names to apply the attributes to.
if (isArray(identifiers)) {
return identifiers;
}
// Make sure the object provides is valid.
invariant(isIdentifiersObject(identifiers), {
code: ErrorConstant.EXTENSION_EXTRA_ATTRIBUTES,
message: `Invalid value passed as an identifier when creating \`extraAttributes\`.`,
});
// Provide type aliases for easier readability.
type Name = string; // `type` Alias for the extension name.
type Tag = string; // The tag for this extension.
type TagSet = Set<Tag>; // The set of tags.
type TaggedNamesMap = Map<Name, TagSet>;
const {
tags: extensionTags = [],
names: extensionNames = [],
behavior = 'any',
excludeNames,
excludeTags,
type,
} = identifiers;
// Keep track of the set of stored names.
const names: Set<Name> = new Set();
// Collect the array of names that are supported.
const acceptableNames =
type === 'mark' ? markNames : type === 'node' ? nodeNames : [...markNames, ...nodeNames];
// Check if the name is valid
const isNameValid = (name: string) =>
acceptableNames.includes(name) && !excludeNames?.includes(name);
for (const name of extensionNames) {
if (isNameValid(name)) {
names.add(name);
}
}
// Create a map of extension names to their set of included tags. Then check
// that the length of the `TagSet` for each extension name is equal to the
// provided extension tags in this identifier.
const taggedNamesMap: TaggedNamesMap = new Map();
// Loop through every extension
for (const tag of extensionTags) {
if (excludeTags?.includes(tag)) {
continue;
}
for (const name of tags[tag]) {
if (!isNameValid(name)) {
continue;
}
// When any tag can be an identifier simply add the name to names.
if (behavior === 'any') {
names.add(name);
continue;
}
const tagSet: TagSet = taggedNamesMap.get(name) ?? new Set();
tagSet.add(tag);
taggedNamesMap.set(name, tagSet);
}
}
// Only add the names that have a `TagSet` where `size` is equal to the number
// of `extensionTags`
for (const [name, tagSet] of taggedNamesMap) {
if (tagSet.size === extensionTags.length) {
names.add(name);
}
}
return [...names];
}
interface CreateSpecProps<Spec extends { group?: string | null }, Override extends object> {
/**
* The node or mark creating function.
*/
createExtensionSpec: (extra: ApplySchemaAttributes, override: Override) => Spec;
/**
* The extra attributes object which has been passed through for this
* extension.
*/
extraAttributes: SchemaAttributes;
/**
* The overrides provided to the schema.
*/
override: Override;
/**
* This is true when the extension is set to ignore extra attributes.
*/
ignoreExtraAttributes: boolean;
/**
* The name for displaying in an error message. The name of the constructor is
* used since it's more descriptive and easier to debug the error that may be
* thrown if extra attributes are not applied correctly.
*/
name: string;
/**
* The tags that were used to create this extension. These are added to the
* node and mark groups.
*/
tags: ExtensionTagType[];
}
interface CreateSpecReturn<Type extends { group?: string | null }> {
/** The created spec. */
spec: Type;
/** The dynamic attribute creators for this spec */
dynamic: Record<string, DynamicAttributeCreator>;
}
/**
* Create the scheme spec for a node or mark extension.
*
* @template Type - either a [[Mark]] or a [[ProsemirrorNode]]
* @param props - the options object [[CreateSpecProps]]
*/
function createSpec<Type extends { group?: string | null }, Override extends object>(
props: CreateSpecProps<Type, Override>,
): CreateSpecReturn<Type> {
const { createExtensionSpec, extraAttributes, ignoreExtraAttributes, name, tags, override } =
props;
// Keep track of the dynamic attributes which are a part of this spec.
const dynamic: Record<string, DynamicAttributeCreator> = object();
/** Called for every dynamic creator to track the dynamic attributes */
function addDynamic(attributeName: string, creator: DynamicAttributeCreator) {
dynamic[attributeName] = creator;
}
// Used to track whether the method has been called. If not called when the
// extension spec is being set up then an error is thrown.
let defaultsCalled = false;
/** Called by createDefaults to track when the `defaults` has been called. */
function onDefaultsCalled() {
defaultsCalled = true;
}
const defaults = createDefaults(
extraAttributes,
ignoreExtraAttributes,
onDefaultsCalled,
addDynamic,
);
const parse = createParseDOM(extraAttributes, ignoreExtraAttributes);
const dom = createToDOM(extraAttributes, ignoreExtraAttributes);
const spec = createExtensionSpec({ defaults, parse, dom }, override);
invariant(ignoreExtraAttributes || defaultsCalled, {
code: ErrorConstant.EXTENSION_SPEC,
message: `When creating a node specification you must call the 'defaults', and parse, and 'dom' methods. To avoid this error you can set the static property 'disableExtraAttributes' of '${name}' to 'true'.`,
});
// Add the tags to the group of the created spec.
spec.group = [...(spec.group?.split(' ') ?? []), ...tags].join(' ') || undefined;
return { spec, dynamic };
}
/**
* Get the value of the extra attribute as an object.
*
* This is needed because the SchemaAttributes object can be configured as a
* string or as an object.
*/
function getExtraAttributesObject(
value: DynamicAttributeCreator | string | SchemaAttributesObject,
): SchemaAttributesObject {
if (isString(value) || isFunction(value)) {
return { default: value };
}
invariant(value, {
message: `${toString(value)} is not supported`,
code: ErrorConstant.EXTENSION_EXTRA_ATTRIBUTES,
});
return value;
}
/**
* Create the `defaults()` method which is used for setting the property.
*
* @param extraAttributes - the extra attributes for this particular node
* @param shouldIgnore - whether this attribute should be ignored
* @param onCalled - the function which is called when this is run, to check
* that it has been added to the attrs
* @param addDynamic - A function called to add the dynamic creator and name to
* the store
*/
function createDefaults(
extraAttributes: SchemaAttributes,
shouldIgnore: boolean,
onCalled: () => void,
addDynamicCreator: (name: string, creator: DynamicAttributeCreator) => void,
) {
return () => {
onCalled();
const attributes: Record<string, { default?: JsonPrimitive }> = object();
// Extra attributes can be ignored by the extension, check if that's the
// case here.
if (shouldIgnore) {
return attributes;
}
// Loop through the extra attributes and attach to the attributes object.
for (const [name, config] of entries(extraAttributes)) {
// Make sure this is an object and not a string.
const attributesObject = getExtraAttributesObject(config);
let defaultValue = attributesObject.default;
// When true this is a dynamic attribute creator.
if (isFunction(defaultValue)) {
// Store the name and method of the dynamic creator.
addDynamicCreator(name, defaultValue);
// Set the attributes for this dynamic creator to be null by default.
defaultValue = null;
}
// When the `defaultValue` is set to `undefined`, it is set as an empty
// object in order for ProseMirror to set it as a required attribute.
attributes[name] = defaultValue === undefined ? {} : { default: defaultValue };
}
return attributes;
};
}
/**
* Create the parseDOM method to be applied to the extension `createNodeSpec`.
*/
function createParseDOM(extraAttributes: SchemaAttributes, shouldIgnore: boolean) {
return (domNode: string | Node) => {
const attributes: ProsemirrorAttributes = object();
if (shouldIgnore) {
return attributes;
}
for (const [name, config] of entries(extraAttributes)) {
const { parseDOM, ...other } = getExtraAttributesObject(config);
if (!isElementDomNode(domNode)) {
continue;
}
if (isNullOrUndefined(parseDOM)) {
attributes[name] = domNode.getAttribute(name) ?? other.default;
continue;
}
if (isFunction(parseDOM)) {
attributes[name] = parseDOM(domNode) ?? other.default;
continue;
}
attributes[name] = domNode.getAttribute(parseDOM) ?? other.default;
}
return attributes;
};
}
/**
* Create the `toDOM` method to be applied to the extension `createNodeSpec`.
*/
function createToDOM(extraAttributes: SchemaAttributes, shouldIgnore: boolean) {
return (item: ProsemirrorNode | Mark) => {
const domAttributes: Record<string, string> = object();
if (shouldIgnore) {
return domAttributes;
}
function updateDomAttributes(
value: string | [string, string?] | Record<string, string> | undefined | null,
name: string,
) {
if (!value) {
return;
}
if (isString(value)) {
domAttributes[name] = value;
return;
}
if (isArray(value)) {
const [attr, val] = value;
domAttributes[attr] = val ?? (item.attrs[name] as string);
return;
}
for (const [attr, val] of entries(value)) {
domAttributes[attr] = val;
}
}
for (const [name, config] of entries(extraAttributes)) {
const { toDOM, parseDOM } = getExtraAttributesObject(config);
if (isNullOrUndefined(toDOM)) {
const key = isString(parseDOM) ? parseDOM : name;
domAttributes[key] = item.attrs[name] as string;
continue;
}
if (isFunction(toDOM)) {
updateDomAttributes(toDOM(item.attrs, getNodeMarkOptions(item)), name);
continue;
}
updateDomAttributes(toDOM, name);
}
return domAttributes;
};
}
/**
* Get the options object which applies should be used to obtain the node or
* mark type.
*/
function getNodeMarkOptions(item: ProsemirrorNode | Mark): NodeMarkOptions {
if (isProsemirrorNode(item)) {
return { node: item };
}
if (isProsemirrorMark(item)) {
return { mark: item };
}
return {};
}
/**
* Get the mark and node specs from provided schema.
*
* This is used when the user provides their own custom schema.
*/
function getSpecFromSchema(schema: EditorSchema) {
const nodes: Record<string, NodeExtensionSpec> = object();
const marks: Record<string, MarkExtensionSpec> = object();
for (const [name, type] of Object.entries(schema.nodes)) {
nodes[name] = type.spec as NodeExtensionSpec;
}
for (const [name, type] of Object.entries(schema.marks)) {
marks[name] = type.spec as MarkExtensionSpec;
}
return { nodes, marks };
}
declare global {
namespace Remirror {
interface BaseExtension {
/**
* Allows the extension to create an extra attributes array that will be
* added to the extra attributes.
*
* For example the `@remirror/extension-bidi` adds a `dir` attribute to
* all node extensions which allows them to automatically infer whether
* the text direction should be right-to-left, or left-to-right.
*/
createSchemaAttributes?(): IdentifierSchemaAttributes[];
}
interface BaseExtensionOptions {
/**
* Inject additional attributes into the defined mark / node schema. This
* can only be used for `NodeExtensions` and `MarkExtensions`.
*
* @remarks
*
* Sometimes you need to add additional attributes to a node or mark. This
* property enables this without needing to create a new extension.
*
* This is only applied to the `MarkExtension` and `NodeExtension`.
*
* @default {}
*/
extraAttributes?: Static<SchemaAttributes>;
/**
* When true will disable extra attributes for this instance of the
* extension.
*
* @remarks
*
* This is only applied to the `MarkExtension` and `NodeExtension`.
*
* @default undefined
*/
disableExtraAttributes?: Static<boolean>;
/**
* An override for the mark spec object. This only applies for
* `MarkExtension`.
*/
markOverride?: Static<MarkSpecOverride>;
/**
* An override object for a node spec object. This only applies to the
* `NodeExtension`.
*/
nodeOverride?: Static<NodeSpecOverride>;
}
interface ManagerSettings {
/**
* Allows for setting extra attributes on multiple nodes and marks by
* their name or constructor. These attributes are automatically added and
* retrieved from from the dom by prosemirror.
*
* @remarks
*
* An example is shown below.
*
* ```ts
* import { RemirrorManager } from 'remirror';
*
* const managerSettings = {
* extraAttributes: [
* {
* identifiers: ['blockquote', 'heading'],
* attributes: { id: 'id', alignment: '0', },
* }, {
* identifiers: ['mention', 'codeBlock'],
* attributes: { 'userId': { default: null } },
* },
* ]
* };
*
* const manager = RemirrorManager.create([], { extraAttributes })
* ```
*/
extraAttributes?: IdentifierSchemaAttributes[];
/**
* Overrides for the mark.
*/
markOverride?: Record<string, MarkSpecOverride>;
/**
* Overrides for the nodes.
*/
nodeOverride?: Record<string, NodeSpecOverride>;
/**
* Perhaps you don't need extra attributes at all in the editor. This
* allows you to disable extra attributes when set to true.
*
* @default undefined
*/
disableExtraAttributes?: boolean;
/**
* Setting this to a value will override the default behaviour of the
* `RemirrorManager`. It overrides the created schema and ignores the
* specs created by all extensions within your editor.
*
* @remarks
*
* This is an advanced option and should only be used in cases where there
* is a deeper understanding of `Prosemirror`. By setting this, please
* note that a lot of functionality just won't work which is powered by
* the `extraAttributes`.
*/
schema?: EditorSchema;
/**
* The name of the default block node. This node will be given a higher
* priority when being added to the schema.
*
* By default this is undefined and the default block node is assigned
* based on the extension priorities.
*
* @default undefined
*/
defaultBlockNode?: string;
}
interface ManagerStore<Extension extends AnyExtension> {
/**
* The nodes to place on the schema.
*/
nodes: Record<
GetNodeNameUnion<Extension> extends never ? string : GetNodeNameUnion<Extension>,
NodeExtensionSpec
>;
/**
* The marks to be added to the schema.
*/
marks: Record<
GetMarkNameUnion<Extension> extends never ? string : GetMarkNameUnion<Extension>,
MarkExtensionSpec
>;
/**
* The schema created by this extension manager.
*/
schema: EditorSchema;
/**
* The name of the default block node. This is used by all internal
* extension when toggling block nodes. It can also be used in other
* cases.
*
* This can be updated via the manager settings when first creating the
* editor.
*
* @default 'paragraph'
*/
defaultBlockNode: string;
}
interface MarkExtension {
/**
* Provides access to the `MarkExtensionSpec`.
*/
spec: MarkExtensionSpec;
}
interface NodeExtension {
/**
* Provides access to the `NodeExtensionSpec`.
*/
spec: NodeExtensionSpec;
}
interface ExtensionStore {
/**
* The Prosemirror schema being used for the current editor.
*
* @remarks
*
* The value is created when the manager initializes. So it can be used in
* `createCommands`, `createHelpers`, `createKeymap` and most of the
* creator methods.
*/
schema: EditorSchema;
}
interface StaticExtensionOptions {
/**
* When true will disable extra attributes for all instances of this
* extension.
*
* @default false
*/
readonly disableExtraAttributes?: boolean;
}
interface AllExtensions {
schema: SchemaExtension;
}
}
} | the_stack |
import * as types from "tns-core-modules/utils/types";
import * as imageSourceModule from "tns-core-modules/image-source/image-source";
import * as imageAssetModule from "tns-core-modules/image-asset/image-asset";
import * as frameModule from "tns-core-modules/ui/frame/frame";
import * as trace from "tns-core-modules/trace/trace";
class UIImagePickerControllerDelegateImpl extends NSObject implements UIImagePickerControllerDelegate {
public static ObjCProtocols = [UIImagePickerControllerDelegate];
static new(): UIImagePickerControllerDelegateImpl {
return <UIImagePickerControllerDelegateImpl>super.new();
}
private _callback: (result?) => void;
private _errorCallback: (result?) => void;
private _width: number;
private _height: number;
private _keepAspectRatio: boolean;
private _saveToGallery: boolean;
private _allowsEditing: boolean;
public initWithCallback(callback: (result?) => void, errorCallback: (result?) => void): UIImagePickerControllerDelegateImpl {
this._callback = callback;
this._errorCallback = errorCallback;
return this;
}
public initWithCallbackAndOptions(callback: (result?) => void, errorCallback: (result?) => void, options?): UIImagePickerControllerDelegateImpl {
this._callback = callback;
this._errorCallback = errorCallback;
if (options) {
this._width = options.width;
this._height = options.height;
this._saveToGallery = options.saveToGallery;
this._allowsEditing = options.allowsEditing;
this._keepAspectRatio = types.isNullOrUndefined(options.keepAspectRatio) ? true : options.keepAspectRatio;
}
return this;
}
imagePickerControllerDidFinishPickingMediaWithInfo(picker, info): void {
if (info) {
let currentDate: Date = new Date();
let source = info.valueForKey(UIImagePickerControllerOriginalImage);
if (this._allowsEditing) {
source = info.valueForKey(UIImagePickerControllerEditedImage);
}
if (source) {
let imageSource: typeof imageSourceModule = require("image-source");
let imageSourceResult = imageSource.fromNativeSource(source);
if (this._callback) {
let imageAsset: imageAssetModule.ImageAsset;
if (this._saveToGallery) {
PHPhotoLibrary.sharedPhotoLibrary().performChangesCompletionHandler(
() => {
PHAssetChangeRequest.creationRequestForAssetFromImage(imageSourceResult.ios);
},
(success, err) => {
if (success) {
let fetchOptions = PHFetchOptions.alloc().init();
let sortDescriptors = NSArray.arrayWithObject(
NSSortDescriptor.sortDescriptorWithKeyAscending("creationDate", false));
fetchOptions.sortDescriptors = sortDescriptors;
fetchOptions.predicate = NSPredicate.predicateWithFormatArgumentArray(
"mediaType = %d", NSArray.arrayWithObject(PHAssetMediaType.Image));
let fetchResult = PHAsset.fetchAssetsWithOptions(fetchOptions);
if (fetchResult.count > 0) {
// Take last picture
let asset = <PHAsset>fetchResult[0];
const dateDiff = asset.creationDate.valueOf() - currentDate.valueOf();
if (Math.abs(dateDiff) > 1000) {
// Image assets create date is rounded when asset is created.
// Display waring if the asset was created more than 1s before/after the current date.
console.warn("Image asset returned was created more than 1 second ago");
}
imageAsset = new imageAssetModule.ImageAsset(asset);
this.setImageAssetAndCallCallback(imageAsset);
}
} else {
trace.write("An error ocurred while saving image to gallery: " +
err, trace.categories.Error, trace.messageType.error);
}
});
} else {
imageAsset = new imageAssetModule.ImageAsset(imageSourceResult.ios);
this.setImageAssetAndCallCallback(imageAsset);
}
}
}
}
picker.presentingViewController.dismissViewControllerAnimatedCompletion(true, null);
listener = null;
}
private setImageAssetAndCallCallback(imageAsset: imageAssetModule.ImageAsset) {
if (this._keepAspectRatio) {
let pictureWidth = imageAsset.nativeImage ? imageAsset.nativeImage.size.width : imageAsset.ios.pixelWidth;
let pictureHeight = imageAsset.nativeImage ? imageAsset.nativeImage.size.height : imageAsset.ios.pixelHeight;
let isPictureLandscape = pictureWidth > pictureHeight;
let areOptionsLandscape = this._width > this._height;
if (isPictureLandscape !== areOptionsLandscape) {
let oldWidth = this._width;
this._width = this._height;
this._height = oldWidth;
}
}
imageAsset.options = {
width: this._width,
height: this._height,
keepAspectRatio: this._keepAspectRatio
};
this._callback(imageAsset);
}
imagePickerControllerDidCancel(picker): void {
picker.presentingViewController.dismissViewControllerAnimatedCompletion(true, null);
listener = null;
this._errorCallback(new Error("cancelled"));
}
}
let listener;
export let takePicture = function (options): Promise<any> {
return new Promise((resolve, reject) => {
listener = null;
let imagePickerController = UIImagePickerController.new();
let reqWidth = 0;
let reqHeight = 0;
let keepAspectRatio = true;
let saveToGallery = true;
let allowsEditing = false;
if (options) {
reqWidth = options.width || 0;
reqHeight = options.height || reqWidth;
keepAspectRatio = types.isNullOrUndefined(options.keepAspectRatio) ? keepAspectRatio : options.keepAspectRatio;
saveToGallery = types.isNullOrUndefined(options.saveToGallery) ? saveToGallery : options.saveToGallery;
allowsEditing = types.isNullOrUndefined(options.allowsEditing) ? allowsEditing : options.allowsEditing;
}
let authStatus = PHPhotoLibrary.authorizationStatus();
if (authStatus !== PHAuthorizationStatus.Authorized) {
saveToGallery = false;
}
if (reqWidth && reqHeight) {
listener = UIImagePickerControllerDelegateImpl.new().initWithCallbackAndOptions(
resolve, reject, { width: reqWidth, height: reqHeight, keepAspectRatio: keepAspectRatio, saveToGallery: saveToGallery, allowsEditing: allowsEditing });
} else if (saveToGallery) {
listener = UIImagePickerControllerDelegateImpl.new().initWithCallbackAndOptions(
resolve, reject, { saveToGallery: saveToGallery, keepAspectRatio: keepAspectRatio, allowsEditing: allowsEditing });
} else {
listener = UIImagePickerControllerDelegateImpl.new().initWithCallback(resolve, reject);
}
imagePickerController.delegate = listener;
let sourceType = UIImagePickerControllerSourceType.Camera;
let mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(sourceType);
let imageMediaType = "public.image";
if (mediaTypes && mediaTypes.containsObject(imageMediaType)) {
let mediaTypesArray = new NSMutableArray<string>({ capacity: 1 });
mediaTypesArray.addObject(imageMediaType);
imagePickerController.mediaTypes = mediaTypesArray;
imagePickerController.sourceType = sourceType;
imagePickerController.cameraDevice = options && options.cameraFacing === "front" ?
UIImagePickerControllerCameraDevice.Front : UIImagePickerControllerCameraDevice.Rear;
imagePickerController.allowsEditing = allowsEditing;
}
imagePickerController.modalPresentationStyle = UIModalPresentationStyle.CurrentContext;
let frame: typeof frameModule = require("tns-core-modules/ui/frame");
let topMostFrame = frame.topmost();
if (topMostFrame) {
let viewController: UIViewController = topMostFrame.currentPage && topMostFrame.currentPage.ios;
if (viewController) {
while (viewController.parentViewController) {
// find top-most view controler
viewController = viewController.parentViewController;
}
while (viewController.presentedViewController) {
// find last presented modal
viewController = viewController.presentedViewController;
}
viewController.presentViewControllerAnimatedCompletion(imagePickerController, true, null);
}
}
});
};
export let isAvailable = function () {
return UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera);
};
export let requestPermissions = function () {
return new Promise(function (resolve, reject) {
requestPhotosPermissions().then(() => {
requestCameraPermissions().then(resolve, reject);
}, reject);
});
};
export let requestPhotosPermissions = function () {
return new Promise(function (resolve, reject) {
let authStatus = PHPhotoLibrary.authorizationStatus();
switch (authStatus) {
case PHAuthorizationStatus.NotDetermined: {
PHPhotoLibrary.requestAuthorization((auth) => {
if (auth === PHAuthorizationStatus.Authorized) {
if (trace.isEnabled()) {
trace.write("Application can access photo library assets.", trace.categories.Debug);
}
resolve();
} else {
reject();
}
});
break;
}
case PHAuthorizationStatus.Authorized: {
if (trace.isEnabled()) {
trace.write("Application can access photo library assets.", trace.categories.Debug);
}
resolve();
break;
}
case PHAuthorizationStatus.Restricted:
case PHAuthorizationStatus.Denied: {
if (trace.isEnabled()) {
trace.write("Application can not access photo library assets.", trace.categories.Debug);
}
reject();
break;
}
}
});
};
export let requestCameraPermissions = function () {
return new Promise(function (resolve, reject) {
let cameraStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo);
switch (cameraStatus) {
case AVAuthorizationStatus.NotDetermined: {
AVCaptureDevice.requestAccessForMediaTypeCompletionHandler(AVMediaTypeVideo, (granted) => {
if (granted) {
resolve();
} else {
reject();
}
});
break;
}
case AVAuthorizationStatus.Authorized: {
resolve();
break;
}
case AVAuthorizationStatus.Restricted:
case AVAuthorizationStatus.Denied: {
if (trace.isEnabled()) {
trace.write("Application can not access Camera assets.", trace.categories.Debug);
}
reject();
break;
}
}
});
}; | the_stack |
import {
AABB,
Body,
Fixture,
Joint,
MouseJoint,
Vec2,
World
} from '../src/index';
import { default as Stage } from 'stage-js/platform/web';
export interface ActiveKeys {
0?: boolean;
1?: boolean;
2?: boolean;
3?: boolean;
4?: boolean;
5?: boolean;
6?: boolean;
7?: boolean;
8?: boolean;
9?: boolean;
A?: boolean;
B?: boolean;
C?: boolean;
D?: boolean;
E?: boolean;
F?: boolean;
G?: boolean;
H?: boolean;
I?: boolean;
J?: boolean;
K?: boolean;
L?: boolean;
M?: boolean;
N?: boolean;
O?: boolean;
P?: boolean;
Q?: boolean;
R?: boolean;
S?: boolean;
T?: boolean;
U?: boolean;
V?: boolean;
W?: boolean;
X?: boolean;
Y?: boolean;
Z?: boolean;
right?: boolean;
left?: boolean;
up?: boolean;
down?: boolean;
fire?: boolean;
}
export interface Testbed {
/** @private @internal */ _pause: any;
/** @private @internal */ _resume: any;
/** @private @internal */ _status: any;
/** @private @internal */ _info: any;
/** @private @internal */ resume: any;
/** @private @internal */ pause: any;
/** @private @internal */ isPaused: any;
/** @private @internal */ togglePause: any;
/** @private @internal */ canvas: any;
/** @private @internal */ focus: () => void;
// camera position
/** World viewbox width. */
width: number;
/** World viewbox height. */
height: number;
/** World viewbox center vertical offset. */
x: number;
/** World viewbox center horizontal offset. */
y: number;
scaleY: number;
ratio: number;
/** World simulation step frequency */
hz: number;
/** World simulation speed, default is 1 */
speed: number;
activeKeys: ActiveKeys;
background: string;
mouseForce?: number;
status(name: string, value: any): void;
status(value: object | string): void;
info(text: string): void;
drawPoint(p: {x: number, y: number}, r: any, color: string): void;
drawCircle(p: {x: number, y: number}, r: number, color: string): void;
drawSegment(a: {x: number, y: number}, b: {x: number, y: number}, color: string): void;
drawPolygon(points: Array<{x: number, y: number}>, color: string): void;
drawAABB(aabb: AABB, color: string): void;
color(r: number, g: number, b: number): string;
// callbacks
step?: (dt: number, t: number) => void;
keydown?: (keyCode: number, label: string) => void;
keyup?: (keyCode: number, label: string) => void;
findOne: (query: string) => Body | Joint | Fixture | null;
findAll: (query: string) => Body[] | Joint[] | Fixture[];
}
export function testbed(opts: object, callback: (testbed: Testbed) => World);
export function testbed(callback: (testbed: Testbed) => World);
export function testbed(opts, callback?) {
if (typeof opts === 'function') {
callback = opts;
opts = null;
}
Stage(function(stage, canvas) {
stage.on(Stage.Mouse.START, function() {
window.focus();
// @ts-ignore
document.activeElement && document.activeElement.blur();
canvas.focus();
});
stage.MAX_ELAPSE = 1000 / 30;
// @ts-ignore
const testbed: Testbed = {};
testbed.canvas = canvas;
let paused = false;
stage.on('resume', function() {
paused = false;
testbed._resume && testbed._resume();
});
stage.on('pause', function() {
paused = true;
testbed._pause && testbed._pause();
});
testbed.isPaused = function() {
return paused;
};
testbed.togglePause = function() {
paused ? testbed.resume() : testbed.pause();
};
testbed.pause = function() {
stage.pause();
};
testbed.resume = function() {
stage.resume();
testbed.focus();
};
testbed.focus = function() {
// @ts-ignore
document.activeElement && document.activeElement.blur();
canvas.focus();
};
testbed.width = 80;
testbed.height = 60;
testbed.x = 0;
testbed.y = -10;
testbed.scaleY = -1;
testbed.ratio = 16;
testbed.hz = 60;
testbed.speed = 1;
testbed.activeKeys = {};
testbed.background = '#222222';
testbed.findOne = function() {
// todo: implement
return null;
};
testbed.findAll = function() {
// todo: implement
return [];
};
let statusText = '';
const statusMap = {};
function statusSet(name, value) {
if (typeof value !== 'function' && typeof value !== 'object') {
statusMap[name] = value;
}
}
function statusMerge(obj) {
// tslint:disable-next-line:no-for-in
for (const key in obj) {
statusSet(key, obj[key]);
}
}
testbed.status = function(a, b?) {
if (typeof b !== 'undefined') {
statusSet(a, b);
} else if (a && typeof a === 'object') {
statusMerge(a);
} else if (typeof a === 'string') {
statusText = a;
}
testbed._status && testbed._status(statusText, statusMap);
};
testbed.info = function(text) {
testbed._info && testbed._info(text);
};
let lastDrawHash = "";
let drawHash = "";
(function() {
const drawingTexture = new Stage.Texture();
stage.append(Stage.image(drawingTexture));
const buffer = [];
stage.tick(function() {
buffer.length = 0;
}, true);
drawingTexture.draw = function(ctx) {
ctx.save();
ctx.transform(1, 0, 0, testbed.scaleY, -testbed.x, -testbed.y);
ctx.lineWidth = 2 / testbed.ratio;
ctx.lineCap = 'round';
for (let drawing = buffer.shift(); drawing; drawing = buffer.shift()) {
drawing(ctx, testbed.ratio);
}
ctx.restore();
};
testbed.drawPoint = function(p, r, color) {
buffer.push(function(ctx, ratio) {
ctx.beginPath();
ctx.arc(p.x, p.y, 5 / ratio, 0, 2 * Math.PI);
ctx.strokeStyle = color;
ctx.stroke();
});
drawHash += "point" + p.x + ',' + p.y + ',' + r + ',' + color;
};
testbed.drawCircle = function(p, r, color) {
buffer.push(function(ctx) {
ctx.beginPath();
ctx.arc(p.x, p.y, r, 0, 2 * Math.PI);
ctx.strokeStyle = color;
ctx.stroke();
});
drawHash += "circle" + p.x + ',' + p.y + ',' + r + ',' + color;
};
testbed.drawSegment = function(a, b, color) {
buffer.push(function(ctx) {
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.strokeStyle = color;
ctx.stroke();
});
drawHash += "segment" + a.x + ',' + a.y + ',' + b.x + ',' + b.y + ',' + color;
};
testbed.drawPolygon = function(points, color) {
if (!points || !points.length) {
return;
}
buffer.push(function(ctx) {
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.strokeStyle = color;
ctx.closePath();
ctx.stroke();
});
drawHash += "segment";
for (let i = 1; i < points.length; i++) {
drawHash += points[i].x + ',' + points[i].y + ',';
}
drawHash += color;
};
testbed.drawAABB = function(aabb, color) {
buffer.push(function(ctx) {
ctx.beginPath();
ctx.moveTo(aabb.lowerBound.x, aabb.lowerBound.y);
ctx.lineTo(aabb.upperBound.x, aabb.lowerBound.y);
ctx.lineTo(aabb.upperBound.x, aabb.upperBound.y);
ctx.lineTo(aabb.lowerBound.x, aabb.upperBound.y);
ctx.strokeStyle = color;
ctx.closePath();
ctx.stroke();
});
drawHash += "aabb";
drawHash += aabb.lowerBound.x + ',' + aabb.lowerBound.y + ',';
drawHash += aabb.upperBound.x + ',' + aabb.upperBound.y + ',';
drawHash += color;
};
testbed.color = function(r, g, b) {
r = r * 256 | 0;
g = g * 256 | 0;
b = b * 256 | 0;
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
};
})();
const world = callback(testbed);
const viewer = new Viewer(world, testbed);
let lastX = 0;
let lastY = 0;
stage.tick(function(dt, t) {
// update camera position
if (lastX !== testbed.x || lastY !== testbed.y) {
viewer.offset(-testbed.x, -testbed.y);
lastX = testbed.x;
lastY = testbed.y;
}
});
viewer.tick(function(dt, t) {
// call testbed step, if provided
if (typeof testbed.step === 'function') {
testbed.step(dt, t);
}
if (targetBody) {
testbed.drawSegment(targetBody.getPosition(), mouseMove, 'rgba(255,255,255,0.2)');
}
if (lastDrawHash !== drawHash) {
lastDrawHash = drawHash;
stage.touch();
}
drawHash = "";
return true;
});
// stage.empty();
stage.background(testbed.background);
stage.viewbox(testbed.width, testbed.height);
stage.pin('alignX', -0.5);
stage.pin('alignY', -0.5);
stage.prepend(viewer);
function findBody(point) {
let body;
const aabb = new AABB(point, point);
world.queryAABB(aabb, function(fixture) {
if (body) {
return;
}
if (!fixture.getBody().isDynamic() || !fixture.testPoint(point)) {
return;
}
body = fixture.getBody();
return true;
});
return body;
}
const mouseGround = world.createBody();
let mouseJoint;
let targetBody;
const mouseMove = {x: 0, y: 0};
viewer.attr('spy', true).on(Stage.Mouse.START, function(point) {
point = { x: point.x, y: testbed.scaleY * point.y };
if (targetBody) {
return;
}
const body = findBody(point);
if (!body) {
return;
}
if (testbed.mouseForce) {
targetBody = body;
} else {
mouseJoint = new MouseJoint({maxForce: 1000}, mouseGround, body, new Vec2(point));
world.createJoint(mouseJoint);
}
}).on(Stage.Mouse.MOVE, function(point) {
point = { x: point.x, y: testbed.scaleY * point.y };
if (mouseJoint) {
mouseJoint.setTarget(point);
}
mouseMove.x = point.x;
mouseMove.y = point.y;
}).on(Stage.Mouse.END, function(point) {
point = { x: point.x, y: testbed.scaleY * point.y };
if (mouseJoint) {
world.destroyJoint(mouseJoint);
mouseJoint = null;
}
if (targetBody) {
const force = Vec2.sub(point, targetBody.getPosition());
targetBody.applyForceToCenter(force.mul(testbed.mouseForce), true);
targetBody = null;
}
}).on(Stage.Mouse.CANCEL, function(point) {
point = { x: point.x, y: testbed.scaleY * point.y };
if (mouseJoint) {
world.destroyJoint(mouseJoint);
mouseJoint = null;
}
if (targetBody) {
targetBody = null;
}
});
window.addEventListener("keydown", function(e) {
switch (e.keyCode) {
case 'P'.charCodeAt(0):
testbed.togglePause();
break;
}
}, false);
const downKeys = {};
window.addEventListener("keydown", function(e) {
const keyCode = e.keyCode;
downKeys[keyCode] = true;
updateActiveKeys(keyCode, true);
testbed.keydown && testbed.keydown(keyCode, String.fromCharCode(keyCode));
});
window.addEventListener("keyup", function(e) {
const keyCode = e.keyCode;
downKeys[keyCode] = false;
updateActiveKeys(keyCode, false);
testbed.keyup && testbed.keyup(keyCode, String.fromCharCode(keyCode));
});
const activeKeys = testbed.activeKeys;
function updateActiveKeys(keyCode, down) {
const char = String.fromCharCode(keyCode);
if (/\w/.test(char)) {
activeKeys[char] = down;
}
activeKeys.right = downKeys[39] || activeKeys['D'];
activeKeys.left = downKeys[37] || activeKeys['A'];
activeKeys.up = downKeys[38] || activeKeys['W'];
activeKeys.down = downKeys[40] || activeKeys['S'];
activeKeys.fire = downKeys[32] || downKeys[13] ;
}
});
}
Viewer._super = Stage;
Viewer.prototype = Stage._create(Viewer._super.prototype);
function Viewer(world, opts) {
Viewer._super.call(this);
this.label('Planck');
opts = opts || {};
this._options = {};
this._options.speed = opts.speed || 1;
this._options.hz = opts.hz || 60;
if (Math.abs(this._options.hz) < 1) {
this._options.hz = 1 / this._options.hz;
}
this._options.scaleY = opts.scaleY || -1;
this._options.ratio = opts.ratio || 16;
this._options.lineWidth = 2 / this._options.ratio;
this._world = world;
const timeStep = 1 / this._options.hz;
let elapsedTime = 0;
this.tick((dt) => {
dt = dt * 0.001 * this._options.speed;
elapsedTime += dt;
while (elapsedTime > timeStep) {
world.step(timeStep);
elapsedTime -= timeStep;
}
this.renderWorld();
return true;
}, true);
world.on('remove-fixture', function(obj) {
obj.ui && obj.ui.remove();
});
world.on('remove-joint', function(obj) {
obj.ui && obj.ui.remove();
});
}
Viewer.prototype.renderWorld = function() {
const world = this._world;
const options = this._options;
const viewer = this;
for (let b = world.getBodyList(); b; b = b.getNext()) {
for (let f = b.getFixtureList(); f; f = f.getNext()) {
if (!f.ui) {
if (f.render && f.render.stroke) {
options.strokeStyle = f.render.stroke;
} else if (b.render && b.render.stroke) {
options.strokeStyle = b.render.stroke;
} else if (b.isDynamic()) {
options.strokeStyle = 'rgba(255,255,255,0.9)';
} else if (b.isKinematic()) {
options.strokeStyle = 'rgba(255,255,255,0.7)';
} else if (b.isStatic()) {
options.strokeStyle = 'rgba(255,255,255,0.5)';
}
if (f.render && f.render.fill) {
options.fillStyle = f.render.fill;
} else if (b.render && b.render.fill) {
options.fillStyle = b.render.fill;
} else {
options.fillStyle = '';
}
const type = f.getType();
const shape = f.getShape();
if (type == 'circle') {
f.ui = viewer.drawCircle(shape, options);
}
if (type == 'edge') {
f.ui = viewer.drawEdge(shape, options);
}
if (type == 'polygon') {
f.ui = viewer.drawPolygon(shape, options);
}
if (type == 'chain') {
f.ui = viewer.drawChain(shape, options);
}
if (f.ui) {
f.ui.appendTo(viewer);
}
}
if (f.ui) {
const p = b.getPosition();
const r = b.getAngle();
if (f.ui.__lastX !== p.x || f.ui.__lastY !== p.y || f.ui.__lastR !== r) {
f.ui.__lastX = p.x;
f.ui.__lastY = p.y;
f.ui.__lastR = r;
f.ui.offset(p.x, options.scaleY * p.y);
f.ui.rotate(options.scaleY * r);
}
}
}
}
for (let j = world.getJointList(); j; j = j.getNext()) {
const type = j.getType();
const a = j.getAnchorA();
const b = j.getAnchorB();
if (!j.ui) {
options.strokeStyle = 'rgba(255,255,255,0.2)';
j.ui = viewer.drawJoint(j, options);
j.ui.pin('handle', 0.5);
if (j.ui) {
j.ui.appendTo(viewer);
}
}
if (j.ui) {
const cx = (a.x + b.x) * 0.5;
const cy = options.scaleY * (a.y + b.y) * 0.5;
const dx = a.x - b.x;
const dy = options.scaleY * (a.y - b.y);
const d = Math.sqrt(dx * dx + dy * dy);
j.ui.width(d);
j.ui.rotate(Math.atan2(dy, dx));
j.ui.offset(cx, cy);
}
}
};
Viewer.prototype.drawJoint = function(joint, options) {
const lw = options.lineWidth;
const ratio = options.ratio;
const length = 10;
const texture = Stage.canvas(function(ctx) {
this.size(length + 2 * lw, 2 * lw, ratio);
ctx.scale(ratio, ratio);
ctx.beginPath();
ctx.moveTo(lw, lw);
ctx.lineTo(lw + length, lw);
ctx.lineCap = 'round';
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
ctx.stroke();
});
const image = Stage.image(texture).stretch();
return image;
};
Viewer.prototype.drawCircle = function(shape, options) {
const lw = options.lineWidth;
const ratio = options.ratio;
const r = shape.m_radius;
const cx = r + lw;
const cy = r + lw;
const w = r * 2 + lw * 2;
const h = r * 2 + lw * 2;
const texture = Stage.canvas(function(ctx) {
this.size(w, h, ratio);
ctx.scale(ratio, ratio);
ctx.arc(cx, cy, r, 0, 2 * Math.PI);
if (options.fillStyle) {
ctx.fillStyle = options.fillStyle;
ctx.fill();
}
ctx.lineTo(cx, cy);
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
ctx.stroke();
});
const image = Stage.image(texture)
.offset(shape.m_p.x - cx, options.scaleY * shape.m_p.y - cy);
const node = Stage.create().append(image);
return node;
};
Viewer.prototype.drawEdge = function(edge, options) {
const lw = options.lineWidth;
const ratio = options.ratio;
const v1 = edge.m_vertex1;
const v2 = edge.m_vertex2;
const dx = v2.x - v1.x;
const dy = v2.y - v1.y;
const length = Math.sqrt(dx * dx + dy * dy);
const texture = Stage.canvas(function(ctx) {
this.size(length + 2 * lw, 2 * lw, ratio);
ctx.scale(ratio, ratio);
ctx.beginPath();
ctx.moveTo(lw, lw);
ctx.lineTo(lw + length, lw);
ctx.lineCap = 'round';
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
ctx.stroke();
});
const minX = Math.min(v1.x, v2.x);
const minY = Math.min(options.scaleY * v1.y, options.scaleY * v2.y);
const image = Stage.image(texture);
image.rotate(options.scaleY * Math.atan2(dy, dx));
image.offset(minX - lw, minY - lw);
const node = Stage.create().append(image);
return node;
};
Viewer.prototype.drawPolygon = function(shape, options) {
const lw = options.lineWidth;
const ratio = options.ratio;
const vertices = shape.m_vertices;
if (!vertices.length) {
return;
}
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (let i = 0; i < vertices.length; ++i) {
const v = vertices[i];
minX = Math.min(minX, v.x);
maxX = Math.max(maxX, v.x);
minY = Math.min(minY, options.scaleY * v.y);
maxY = Math.max(maxY, options.scaleY * v.y);
}
const width = maxX - minX;
const height = maxY - minY;
const texture = Stage.canvas(function(ctx) {
this.size(width + 2 * lw, height + 2 * lw, ratio);
ctx.scale(ratio, ratio);
ctx.beginPath();
for (let i = 0; i < vertices.length; ++i) {
const v = vertices[i];
const x = v.x - minX + lw;
const y = options.scaleY * v.y - minY + lw;
if (i == 0)
ctx.moveTo(x, y);
else
ctx.lineTo(x, y);
}
if (vertices.length > 2) {
ctx.closePath();
}
if (options.fillStyle) {
ctx.fillStyle = options.fillStyle;
ctx.fill();
ctx.closePath();
}
ctx.lineCap = 'round';
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
ctx.stroke();
});
const image = Stage.image(texture);
image.offset(minX - lw, minY - lw);
const node = Stage.create().append(image);
return node;
};
Viewer.prototype.drawChain = function(shape, options) {
const lw = options.lineWidth;
const ratio = options.ratio;
const vertices = shape.m_vertices;
if (!vertices.length) {
return;
}
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (let i = 0; i < vertices.length; ++i) {
const v = vertices[i];
minX = Math.min(minX, v.x);
maxX = Math.max(maxX, v.x);
minY = Math.min(minY, options.scaleY * v.y);
maxY = Math.max(maxY, options.scaleY * v.y);
}
const width = maxX - minX;
const height = maxY - minY;
const texture = Stage.canvas(function(ctx) {
this.size(width + 2 * lw, height + 2 * lw, ratio);
ctx.scale(ratio, ratio);
ctx.beginPath();
for (let i = 0; i < vertices.length; ++i) {
const v = vertices[i];
const x = v.x - minX + lw;
const y = options.scaleY * v.y - minY + lw;
if (i == 0)
ctx.moveTo(x, y);
else
ctx.lineTo(x, y);
}
// TODO: if loop
if (vertices.length > 2) {
// ctx.closePath();
}
if (options.fillStyle) {
ctx.fillStyle = options.fillStyle;
ctx.fill();
ctx.closePath();
}
ctx.lineCap = 'round';
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
ctx.stroke();
});
const image = Stage.image(texture);
image.offset(minX - lw, minY - lw);
const node = Stage.create().append(image);
return node;
};
// Everything below this is copied from ../src/index.ts
export { default as Serializer } from '../src/serializer/index';
export { default as Math } from '../src/common/Math';
export { default as Vec2 } from '../src/common/Vec2';
export { default as Vec3 } from '../src/common/Vec3';
export { default as Mat22 } from '../src/common/Mat22';
export { default as Mat33 } from '../src/common/Mat33';
export { default as Transform } from '../src/common/Transform';
export { default as Rot } from '../src/common/Rot';
export { default as AABB } from '../src/collision/AABB';
export { default as Shape } from '../src/collision/Shape';
export { default as Fixture } from '../src/dynamics/Fixture';
export { default as Body } from '../src/dynamics/Body';
export { default as Contact } from '../src/dynamics/Contact';
export { default as Joint } from '../src/dynamics/Joint';
export { default as World } from '../src/dynamics/World';
export { default as Circle } from '../src/collision/shape/CircleShape';
export { default as Edge } from '../src/collision/shape/EdgeShape';
export { default as Polygon } from '../src/collision/shape/PolygonShape';
export { default as Chain } from '../src/collision/shape/ChainShape';
export { default as Box } from '../src/collision/shape/BoxShape';
export { CollideCircles } from '../src/collision/shape/CollideCircle';
export { CollideEdgeCircle } from '../src/collision/shape/CollideEdgeCircle';
export { CollidePolygons } from '../src/collision/shape/CollidePolygon';
export { CollidePolygonCircle } from '../src/collision/shape/CollideCirclePolygone';
export { CollideEdgePolygon } from '../src/collision/shape/CollideEdgePolygon';
export { default as DistanceJoint } from '../src/dynamics/joint/DistanceJoint';
export { default as FrictionJoint } from '../src/dynamics/joint/FrictionJoint';
export { default as GearJoint } from '../src/dynamics/joint/GearJoint';
export { default as MotorJoint } from '../src/dynamics/joint/MotorJoint';
export { default as MouseJoint } from '../src/dynamics/joint/MouseJoint';
export { default as PrismaticJoint } from '../src/dynamics/joint/PrismaticJoint';
export { default as PulleyJoint } from '../src/dynamics/joint/PulleyJoint';
export { default as RevoluteJoint } from '../src/dynamics/joint/RevoluteJoint';
export { default as RopeJoint } from '../src/dynamics/joint/RopeJoint';
export { default as WeldJoint } from '../src/dynamics/joint/WeldJoint';
export { default as WheelJoint } from '../src/dynamics/joint/WheelJoint';
export { default as Settings } from '../src/Settings';
export { default as Sweep } from '../src/common/Sweep';
export { default as Manifold } from '../src/collision/Manifold';
export { default as Distance } from '../src/collision/Distance';
export { default as TimeOfImpact } from '../src/collision/TimeOfImpact';
export { default as DynamicTree } from '../src/collision/DynamicTree';
import Solver, { TimeStep } from "../src/dynamics/Solver";
import { CollidePolygons } from '../src/collision/shape/CollidePolygon';
import { default as Settings } from '../src/Settings';
import { default as Sweep } from '../src/common/Sweep';
import { clipSegmentToLine, ClipVertex, default as Manifold, getPointStates, PointState } from '../src/collision/Manifold';
import { default as Distance, DistanceInput, DistanceOutput, DistanceProxy, SimplexCache, testOverlap } from '../src/collision/Distance';
import { default as TimeOfImpact, TOIInput, TOIOutput } from '../src/collision/TimeOfImpact';
import { default as DynamicTree } from '../src/collision/DynamicTree';
import { default as stats } from '../src/util/stats'; // todo: what to do with this?
/** @deprecated Merged with main namespace */
export const internal = {};
// @ts-ignore
internal.CollidePolygons = CollidePolygons;
// @ts-ignore
internal.Settings = Settings;
// @ts-ignore
internal.Sweep = Sweep;
// @ts-ignore
internal.Manifold = Manifold;
// @ts-ignore
internal.Distance = Distance;
// @ts-ignore
internal.TimeOfImpact = TimeOfImpact;
// @ts-ignore
internal.DynamicTree = DynamicTree;
// @ts-ignore
internal.stats = stats;
// @ts-ignore
Manifold.clipSegmentToLine = clipSegmentToLine;
// @ts-ignore
Manifold.ClipVertex = ClipVertex;
// @ts-ignore
Manifold.getPointStates = getPointStates;
// @ts-ignore
Manifold.PointState = PointState;
// @ts-ignore
Solver.TimeStep = TimeStep;
// @ts-ignore
Distance.testOverlap = testOverlap;
// @ts-ignore
Distance.Input = DistanceInput;
// @ts-ignore
Distance.Output = DistanceOutput;
// @ts-ignore
Distance.Proxy = DistanceProxy;
// @ts-ignore
Distance.Cache = SimplexCache;
// @ts-ignore
TimeOfImpact.Input = TOIInput;
// @ts-ignore
TimeOfImpact.Output = TOIOutput; | the_stack |
import * as bluebird from 'bluebird';
import * as chokidar from 'chokidar';
import * as fse from 'fs-extra';
import * as moment from 'moment';
import * as path from 'path';
import {DocEntry, DocEntryTag} from 'app/common/DocListAPI';
import {DocSnapshots} from 'app/common/DocSnapshot';
import * as gutil from 'app/common/gutil';
import * as Comm from 'app/server/lib/Comm';
import * as docUtils from 'app/server/lib/docUtils';
import {GristServer} from 'app/server/lib/GristServer';
import {IDocStorageManager} from 'app/server/lib/IDocStorageManager';
import {IShell} from 'app/server/lib/IShell';
import * as log from 'app/server/lib/log';
import * as uuidv4 from "uuid/v4";
/**
* DocStorageManager manages Grist documents. This implementation deals with files in the file
* system. An alternative implementation could provide the same public methods to implement
* storage management for the hosted version of Grist.
*
* This file-based DocStorageManager uses file path as the docName identifying a document, with
* one exception. For files in the docsRoot directory, the basename of the document is used
* instead, with .grist extension stripped; primarily to maintain previous behavior and keep
* clean-looking URLs. In all other cases, the realpath of the file (including .grist extension)
* is the canonical docName.
*
*/
export class DocStorageManager implements IDocStorageManager {
private _watcher: any; // chokidar filesystem watcher
private _shell: IShell;
/**
* Initialize with the given root directory, which should be a fully-resolved path (i.e. using
* fs.realpath or docUtils.realPath).
* The file watcher is created if the optComm argument is given.
*/
constructor(private _docsRoot: string, private _samplesRoot?: string,
private _comm?: Comm, gristServer?: GristServer) {
// If we have a way to communicate with clients, watch the docsRoot for changes.
this._watcher = null;
this._shell = (gristServer && gristServer.create.Shell()) || {
moveItemToTrash() { throw new Error('Unable to move document to trash'); },
showItemInFolder() { throw new Error('Unable to show item in folder'); }
};
if (_comm) {
this._initFileWatcher();
}
}
/**
* Returns the path to the given document. This is used by DocStorage.js, and is specific to the
* file-based storage implementation.
* @param {String} docName: The canonical docName.
* @returns {String} path: Filesystem path.
*/
public getPath(docName: string): string {
docName += (path.extname(docName) === '.grist' ? '' : '.grist');
return path.resolve(this._docsRoot, docName);
}
/**
* Returns the path to the given sample document.
*/
public getSampleDocPath(sampleDocName: string): string|null {
return this._samplesRoot ? this.getPath(path.resolve(this._samplesRoot, sampleDocName)) : null;
}
/**
* Translates a possibly non-canonical docName to a canonical one (e.g. adds .grist to a path
* without .grist extension, and canonicalizes the path). All other functions deal with
* canonical docNames.
* @param {String} altDocName: docName which may not be the canonical one.
* @returns {Promise:String} Promise for the canonical docName.
*/
public async getCanonicalDocName(altDocName: string): Promise<string> {
const p = await docUtils.realPath(this.getPath(altDocName));
return path.dirname(p) === this._docsRoot ? path.basename(p, '.grist') : p;
}
/**
* Prepares a document for use locally. Returns whether the document is new (needs to be
* created). This is a no-op in the local DocStorageManager case.
*/
public async prepareLocalDoc(docName: string): Promise<boolean> { return false; }
public async prepareToCreateDoc(docName: string): Promise<void> {
// nothing to do
}
public async prepareFork(srcDocName: string, destDocName: string): Promise<string> {
// This is implemented only to support old tests.
await fse.copy(this.getPath(srcDocName), this.getPath(destDocName));
return this.getPath(destDocName);
}
/**
* Returns a promise for the list of docNames to show in the doc list. For the file-based
* storage, this will include all .grist files under the docsRoot.
* @returns {Promise:Array<DocEntry>} Promise for an array of objects with `name`, `size`,
* and `mtime`.
*/
public listDocs(): Promise<DocEntry[]> {
return bluebird.Promise.all([
this._listDocs(this._docsRoot, ""),
this._samplesRoot ? this._listDocs(this._samplesRoot, "sample") : [],
])
.spread((docsEntries: DocEntry[], samplesEntries: DocEntry[]) => {
return [...docsEntries, ...samplesEntries];
});
}
/**
* Deletes a document.
* @param {String} docName: docName of the document to delete.
* @returns {Promise} Resolved on success.
*/
public deleteDoc(docName: string, deletePermanently?: boolean): Promise<void> {
const docPath = this.getPath(docName);
// Keep this check, to protect against wiping out the whole disk or the user's home.
if (path.extname(docPath) !== '.grist') {
return Promise.reject(new Error("Refusing to delete path which does not end in .grist"));
} else if (deletePermanently) {
return fse.remove(docPath);
} else {
this._shell.moveItemToTrash(docPath); // this is a synchronous action
return Promise.resolve();
}
}
/**
* Renames a closed document. In the file-system case, moves files to reflect the new paths. For
* a document already open, use `docStorageInstance.renameDocTo()` instead.
* @param {String} oldName: original docName.
* @param {String} newName: new docName.
* @returns {Promise} Resolved on success.
*/
public renameDoc(oldName: string, newName: string): Promise<void> {
const oldPath = this.getPath(oldName);
const newPath = this.getPath(newName);
return docUtils.createExclusive(newPath)
.catch(async (e: any) => {
if (e.code !== 'EEXIST') { throw e; }
const isSame = await docUtils.isSameFile(oldPath, newPath);
if (!isSame) { throw e; }
})
.then(() => fse.rename(oldPath, newPath))
// Send 'renameDocs' event immediately after the rename. Previously, this used to be sent by
// DocManager after reopening the renamed doc. The extra delay caused issue T407, where
// chokidar.watch() triggered 'removeDocs' before 'renameDocs'.
.then(() => { this._sendDocListAction('renameDocs', oldPath, [oldName, newName]); })
.catch((err: Error) => {
log.warn("DocStorageManager: rename %s -> %s failed: %s", oldPath, newPath, err.message);
throw err;
});
}
/**
* Should create a backup of the file
* @param {String} docName - docName to backup
* @param {String} backupTag - string to identify backup, like foo.grist.$DATE.$TAG.bak
* @returns {Promise} Resolved on success, returns path to backup (to show user)
*/
public makeBackup(docName: string, backupTag: string): Promise<string> {
// this need to persist between calling createNumbered and
// getting it's return value, to re-add the extension again (._.)
let ext: string;
let finalBakPath: string; // holds final value of path, with numbering
return bluebird.Promise.try(() => this._generateBackupFilePath(docName, backupTag))
.then((bakPath: string) => { // make a numbered migration if necessary
log.debug(`DocStorageManager: trying to make backup at ${bakPath}`);
// create a file at bakPath, adding numbers if necessary
ext = path.extname(bakPath); // persists to makeBackup closure
const bakPathPrefix = bakPath.slice(0, -ext.length);
return docUtils.createNumbered(bakPathPrefix, '-',
(pathPrefix: string) => docUtils.createExclusive(pathPrefix + ext)
);
}).tap((numberedBakPathPrefix: string) => { // do the copying, but return bakPath anyway
finalBakPath = numberedBakPathPrefix + ext;
const docPath = this.getPath(docName);
log.info(`Backing up ${docName} to ${finalBakPath}`);
return docUtils.copyFile(docPath, finalBakPath);
}).then(() => {
log.debug("DocStorageManager: Backup made successfully at: %s", finalBakPath);
return finalBakPath;
}).catch((err: Error) => {
log.error("DocStorageManager: Backup %s %s failed: %s", docName, err.message);
throw err;
});
}
/**
* Electron version only. Shows the given doc in the file explorer.
*/
public async showItemInFolder(docName: string): Promise<void> {
this._shell.showItemInFolder(this.getPath(docName));
}
public async closeStorage() {
// nothing to do
}
public async closeDocument(docName: string) {
// nothing to do
}
public markAsChanged(docName: string): void {
// nothing to do
}
public markAsEdited(docName: string): void {
// nothing to do
}
public testReopenStorage(): void {
// nothing to do
}
public async addToStorage(id: string): Promise<void> {
// nothing to do
}
public prepareToCloseStorage(): void {
// nothing to do
}
public async flushDoc(docName: string): Promise<void> {
// nothing to do
}
public async getCopy(docName: string): Promise<string> {
const srcPath = this.getPath(docName);
const postfix = uuidv4();
const tmpPath = `${srcPath}-${postfix}`;
await docUtils.copyFile(srcPath, tmpPath);
return tmpPath;
}
public async getSnapshots(docName: string, skipMetadataCache?: boolean): Promise<DocSnapshots> {
throw new Error('getSnapshots not implemented');
}
public removeSnapshots(docName: string, snapshotIds: string[]): Promise<void> {
throw new Error('removeSnapshots not implemented');
}
public async replace(docName: string, options: any): Promise<void> {
throw new Error('replacement not implemented');
}
/**
* Returns a promise for the list of docNames for all docs in the given directory.
* @returns {Promise:Array<Object>} Promise for an array of objects with `name`, `size`,
* and `mtime`.
*/
private _listDocs(dirPath: string, tag: DocEntryTag): Promise<any[]> {
return fse.readdir(dirPath)
// Filter out for .grist files, and strip the .grist extension.
.then(entries => Promise.all(
entries.filter(e => (path.extname(e) === '.grist'))
.map(e => {
const docPath = path.resolve(dirPath, e);
return fse.stat(docPath)
.then(stat => getDocListFileInfo(docPath, stat, tag));
})
))
// Sort case-insensitively.
.then(entries => entries.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase())))
// If the root directory is missing, just return an empty array.
.catch(err => {
if (err.cause && err.cause.code === 'ENOENT') { return []; }
throw err;
});
}
/**
* Generates the filename for the given document backup
* Backup names should look roughly like:
* ${basefilename}.grist.${YYYY-MM-DD}.${tag}.bak
*
* @returns {Promise} backup filepath (might need to createNumbered)
*/
private _generateBackupFilePath(docName: string, backupTag: string): Promise<string> {
const dateString = moment().format("YYYY-MM-DD");
return docUtils.realPath(this.getPath(docName))
.then((filePath: string) => {
const fileName = path.basename(filePath);
const fileDir = path.dirname(filePath);
const bakName = `${fileName}.${dateString}.${backupTag}.bak`;
return path.join(fileDir, bakName);
});
}
/**
* Creates the file watcher and begins monitoring the docsRoot. Returns the created watcher.
*/
private _initFileWatcher(): void {
// NOTE: The chokidar watcher reports file renames as unlink then add events.
this._watcher = chokidar.watch(this._docsRoot, {
ignoreInitial: true, // Prevent messages for initial adds of all docs when watching begins
depth: 0, // Ignore changes in subdirectories of docPath
alwaysStat: true, // Tells the watcher to always include the stats arg
// Waits for a file to remain constant for a short time after changing before triggering
// an action. Prevents reporting of incomplete writes.
awaitWriteFinish: {
stabilityThreshold: 100, // Waits for the file to remain constant for 100ms
pollInterval: 10 // Polls the file every 10ms after a change
}
});
this._watcher.on('add', (docPath: string, fsStats: any) => {
this._sendDocListAction('addDocs', docPath, getDocListFileInfo(docPath, fsStats, ""));
});
this._watcher.on('change', (docPath: string, fsStats: any) => {
this._sendDocListAction('changeDocs', docPath, getDocListFileInfo(docPath, fsStats, ""));
});
this._watcher.on('unlink', (docPath: string) => {
this._sendDocListAction('removeDocs', docPath, getDocName(docPath));
});
}
/**
* Helper to broadcast a docListAction for a single doc to clients. If the action is not on a
* '.grist' file, it is not sent.
* @param {String} actionType - DocListAction type to send, 'addDocs' | 'removeDocs' | 'changeDocs'.
* @param {String} docPath - System path to the doc including the filename.
* @param {Any} data - Data to send as the message.
*/
private _sendDocListAction(actionType: string, docPath: string, data: any): void {
if (this._comm && gutil.endsWith(docPath, '.grist')) {
log.debug(`Sending ${actionType} action for doc ${getDocName(docPath)}`);
this._comm.broadcastMessage('docListAction', { [actionType]: [data] });
}
}
}
/**
* Helper to return the docname (without .grist) given the path to the .grist file.
*/
function getDocName(docPath: string): string {
return path.basename(docPath, '.grist');
}
/**
* Helper to get the stats used by the Grist DocList for a document.
* @param {String} docPath - System path to the doc including the doc filename.
* @param {Object} fsStat - fs.Stats object describing the file metadata.
* @param {String} tag - The tag indicating the type of doc.
* @return {Promise:Object} Promise for an object containing stats for the requested doc.
*/
function getDocListFileInfo(docPath: string, fsStat: any, tag: DocEntryTag): DocEntry {
return {
docId: undefined, // TODO: Should include docId if it exists
name: getDocName(docPath),
mtime: fsStat.mtime,
size: fsStat.size,
tag
};
} | the_stack |
import type { CommandClient, Message, GuildTextableChannel, Guild, Invite } from 'eris'
import { URL } from 'url'
import { readFileSync } from 'fs'
import { deleteMeta } from './logger.js'
import { skipSnipe } from '../sniper.js'
import { Period, getPeriod, ban, mute, softBan } from '../../mod.js'
import { isStaff } from '../../util.js'
import config from '../../config.js'
const NAMES = JSON.parse(readFileSync(new URL('../../../twemojiNames.json', import.meta.url), 'utf8'))
const INVITE_RE_SRC = '(?:https?:\\/\\/)?(?:www\\.)?(discord\\.(?:gg|io|me|li|link|list|media)|(?:discord(?:app)?|watchanimeattheoffice)\\.com\\/invite)\\/(.+[a-zA-Z0-9])'
const INVITE_RE_G = new RegExp(INVITE_RE_SRC, 'ig')
const INVITE_RE = new RegExp(INVITE_RE_SRC, 'i')
const INVITE_CHECK_FOR = [
'discord.gg',
'discord.media',
'discord.com/invite',
'discordapp.com/invite',
'watchanimeattheoffice.com/invite',
]
// todo: spaces
const CLEANER = /[\u200B-\u200F\u2060-\u2063\uFEFF\u00AD\u180E]|[\u0300-\u036f]|[\u202A-\u202E]|[/\\]/g
const BAD_POWERCORD = /[Pp]ower[-_.,;:!*\s+]*[C(]ord/
const EMOJI_UNICODE_RE = /(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff]|(?:<a?:[^:]{2,}:\d{6,}>))/g
const EMOJI_RE = new RegExp(`${NAMES.map((n: string) => `:${n}:`).join('|').replace(/\+/g, '\\+')}|${EMOJI_UNICODE_RE.source}`, 'g')
const MAX_EMOJI_THRESHOLD_MULTIPLIER = 0.3 // Amount of words * mult (floored) = max amount of emojis allowed
// todo: a "better" normalization with multi-pass, so things like numbers don't get replaced pass-1
const NORMALIZE: [ RegExp, string ][] = [
[ /Α|А|₳|Ꭿ|Ꭺ|Λ|@|🅰|🅐|\uD83C\uDDE6/g, 'A' ],
[ /Β|В|в|฿|₿|Ᏸ|Ᏼ|🅱|🅑|\uD83C\uDDE7/g, 'B' ],
[ /С|Ⅽ|₡|₵|Ꮳ|Ꮯ|Ꮸ|ᑕ|🅲|🅒|\uD83C\uDDE8/g, 'C' ],
[ /Ⅾ|ↁ|ↇ|Ꭰ|🅳|🅓|\uD83C\uDDE9/g, 'D' ],
[ /Ε|Ξ|ξ|Е|Ꭼ|Ꮛ|℮|🅴|🅔|\uD83C\uDDEA/g, 'E' ],
[ /Ғ|ғ|₣|🅵|🅕|\uD83C\uDDEB/g, 'F' ],
[ /₲|Ꮆ|Ᏻ|Ᏽ|🅶|🅖|\uD83C\uDDEC/g, 'G' ],
[ /Η|Н|н|Ӊ|ӊ|Ң|ң|Ӈ|ӈ|Ҥ|ҥ|Ꮋ|🅷|🅗|\uD83C\uDDED/g, 'H' ],
[ /Ι|І|Ӏ|ӏ|Ⅰ|Ꮖ|Ꮠ|🅸|🅘|\uD83C\uDDEE/g, 'I' ],
[ /Ј|Ꭻ|🅹|🅙|\uD83C\uDDEF/g, 'J' ],
[ /Κ|κ|К|к|Қ|қ|Ҟ|ҟ|Ҡ|ҡ|Ӄ|ӄ|Ҝ|ҝ|₭|Ꮶ|🅺|🅚|\uD83C\uDDF0/g, 'K' ],
[ /Ⅼ|£|Ł|Ꮮ|🅻|🅛|\uD83C\uDDF1/g, 'L' ],
[ /Μ|М|м|Ӎ|ӎ|Ⅿ|Ꮇ|🅼|🅜|\uD83C\uDDF2/g, 'M' ],
[ /Ν|И|и|Ҋ|ҋ|₦|🅽|🅝|\uD83C\uDDF3/g, 'N' ],
[ /Θ|θ|Ο|О|Ө|Ø|Ꮎ|Ꮻ|Ꭴ|Ꮕ|🅾|🅞|\uD83C\uDDF4/g, 'O' ],
[ /Ρ|Р|Ҏ|₽|₱|Ꭾ|Ꮅ|Ꮲ|🅿|🆊|🅟|\uD83C\uDDF5/g, 'P' ],
[ /🆀|🅠|\uD83C\uDDF6/g, 'Q' ],
[ /Я|я|Ꭱ|Ꮢ|🆁|🅡|\uD83C\uDDF7/g, 'R' ],
[ /Ѕ|\$|Ꭶ|Ꮥ|Ꮪ|🆂|🅢|\uD83C\uDDF8/g, 'S' ],
[ /Τ|Т|т|Ҭ|ҭ|₮|₸|Ꭲ|🆃|🅣|\uD83C\uDDF9/g, 'T' ],
[ /🆄|🅤|\uD83C\uDDFA/g, 'U' ],
[ /Ⅴ|Ꮴ|Ꮙ|Ꮩ|🆅|🅥|\uD83C\uDDFB/g, 'V' ],
[ /₩|Ꮃ|Ꮤ|🆆|🅦|\uD83C\uDDFC/g, 'W' ],
[ /Χ|χ|Х|Ҳ|🆇|🅧|\uD83C\uDDFD/g, 'X' ],
[ /Υ|У|Ү|Ұ|¥|🆈|🅨|\uD83C\uDDFE/g, 'Y' ],
[ /Ζ|Ꮓ|🆉|🅩|\uD83C\uDDFF/g, 'Z' ],
[ /α|а/g, 'a' ],
[ /β|Ꮟ/g, 'b' ],
[ /ϲ|с|ⅽ|↻|¢|©️/g, 'c' ],
[ /đ|ⅾ|₫|Ꮷ|ժ|🆥/g, 'd' ],
[ /ε|е|Ҽ|ҽ|Ҿ|ҿ|Є|є|€/g, 'e' ],
[ /ƒ/g, 'f' ],
// [ //g, 'g' ],
[ /Ћ|ћ|Һ|һ|Ꮒ|Ꮵ/g, 'h' ],
[ /ι|і|ⅰ|Ꭵ|¡/g, 'i' ],
[ /ј/g, 'j' ],
// [ /|/g, 'k' ],
[ /ⅼ|£|₤/g, 'l' ],
[ /ⅿ|₥/g, 'm' ],
// [ /|/g, 'n' ],
[ /ο|о|օ|ө|ø|¤|๏/g, 'o' ],
[ /ρ|р|ҏ|Ꮘ|φ|ק/g, 'p' ],
// [ /|/g, 'q' ],
[ /ɾ/g, 'r' ],
[ /ѕ/g, 's' ],
[ /τ/g, 't' ],
[ /μ|υ/g, 'u' ],
[ /ν|ⅴ/g, 'v' ],
[ /ω|ա|山/g, 'w' ],
[ /х|ҳ|ⅹ/g, 'x' ],
[ /γ|у|ү|ұ|Ꭹ|Ꮍ/g, 'y' ],
// [ /|/g, 'z' ],
[ /⓿/g, '0' ],
[ /⓵/g, '1' ],
[ /⓶/g, '2' ],
[ /⓷/g, '3' ],
[ /Ꮞ|⓸/g, '4' ],
[ /⓹/g, '5' ],
[ /⓺/g, '6' ],
[ /⓻/g, '7' ],
[ /⓼/g, '8' ],
[ /⓽/g, '9' ],
[ /⓾/g, '10' ],
[ /⓫/g, '11' ],
[ /⓬/g, '12' ],
[ /⓭/g, '13' ],
[ /⓮/g, '14' ],
[ /⓯/g, '15' ],
[ /⓰/g, '16' ],
[ /⓱/g, '17' ],
[ /⓲/g, '18' ],
[ /⓳/g, '19' ],
[ /⓴/g, '20' ],
[ /1/g, 'i' ],
[ /3/g, 'e' ],
[ /4/g, 'a' ],
[ /9/g, 'g' ],
[ /0/g, 'o' ],
]
export const BLACKLIST_CACHE: string[] = []
const SPAM_HINTS = [ 'discord', 'nitro', 'steam', 'cs:go', 'csgo' ]
const correctedPeople = new Map<string, number>()
function takeAction (msg: Message, reason: string, warning: string, attemptedBypass: boolean, loose?: boolean) {
skipSnipe.add(msg.id)
deleteMeta.set(msg.id, reason)
msg.delete(reason)
if (!msg.member) return // ??
const period = getPeriod(msg.member)
if (!loose && period === Period.PROBATIONARY) {
ban(msg.member.guild, msg.author.id, null, `Automod: ${reason} (New member)`)
return
}
if (period === Period.RECENT) {
if (attemptedBypass) {
ban(msg.member.guild, msg.author.id, null, `Automod: ${reason} (Recent member, attempted bypass)`)
return
}
mute(msg.member.guild, msg.author.id, null, `Automod: ${reason} (Recent member)`, 24 * 3600e3)
}
if (period === Period.KNOWN && attemptedBypass) {
mute(msg.member.guild, msg.author.id, null, `Automod: ${reason} (Attempted bypass)`, 12 * 3600e3)
}
msg.channel.createMessage({ content: warning, allowedMentions: { users: [ msg.author.id ] } })
.then((m) => setTimeout(() => m.delete(), 10e3))
}
async function processMessage (this: CommandClient, msg: Message<GuildTextableChannel>) {
if (msg.guildID !== config.discord.ids.serverId || msg.author.bot || isStaff(msg.member)) return null
let normalizedMessage = msg.content.normalize('NFKD')
let attemptedBypass = false
for (const [ re, rep ] of NORMALIZE) {
const cleanerString = normalizedMessage.replace(re, rep)
attemptedBypass = attemptedBypass || normalizedMessage !== cleanerString
normalizedMessage = cleanerString
}
const cleanNormalizedMessage = normalizedMessage.replace(CLEANER, '')
const cleanMessage = msg.content.replace(CLEANER, '')
const lowercaseMessage = msg.content.toLowerCase()
const cleanLowercaseMessage = cleanMessage.toLowerCase()
const cleanNormalizedLowercaseMessage = cleanNormalizedMessage.toLowerCase()
// Filter scams
if (
msg.content.includes('@everyone')
&& (msg.content.includes('https://') || msg.content.includes('http://'))
&& SPAM_HINTS.find((h) => cleanNormalizedLowercaseMessage.includes(h))
) {
softBan(msg.channel.guild, msg.author.id, null, 'Automod: Detected scambot', 1)
return
}
// Filter bad words
if (!BLACKLIST_CACHE.length) {
const b = await this.mongo.collection('boat-blacklist').find().toArray()
BLACKLIST_CACHE.push(...b.map((e) => e.word))
}
for (const word of BLACKLIST_CACHE) {
const simpleContains = lowercaseMessage.includes(word)
if (simpleContains || cleanLowercaseMessage.includes(word) || cleanNormalizedLowercaseMessage.includes(word)) {
takeAction(
msg,
'Message contained a blacklisted word',
`${msg.author.mention} Your message has been deleted because it contained a word blacklisted.`,
!simpleContains
)
}
}
// Filter ads
const invites = msg.content.match(INVITE_RE_G)
if (invites) {
for (const invite of invites) {
const [ , url, code ] = invite.match(INVITE_RE)!
if (INVITE_CHECK_FOR.includes(url)) {
const inv = await this.getInvite(code)
if (inv && inv.guild?.id === config.discord.ids.serverId) continue
}
takeAction(
msg,
'Advertisement',
`${msg.author.mention} **Rule #02**: Advertising of any kind is prohibited.`,
false
)
return // No need to keep checking for smth else
}
}
// Filter emoji spam
const emojis = msg.content.match(EMOJI_RE)?.length || 0
if (emojis > 5) {
const words = msg.content.replace(EMOJI_RE, '').split(/\s+/g).filter(Boolean).length
const max = Math.floor(words * MAX_EMOJI_THRESHOLD_MULTIPLIER)
if (emojis > max) {
takeAction(
msg,
'Emoji spam',
`${msg.author.mention} **Rule #03**: Spam of any kind is prohibited.\nConsider reducing the amount of emojis in your message.`,
false,
true
)
return // No need to keep checking for smth else
}
}
// Deal with people who can't write
if (BAD_POWERCORD.test(cleanNormalizedMessage)) {
skipSnipe.add(msg.id)
deleteMeta.set(msg.id, 'Improper writing of Powercord')
msg.delete('Improper writing of Powercord')
if (msg.channel.id === config.discord.ids.channelMuted) return
const count = (correctedPeople.get(msg.author.id) || 0) + 1
if (count === 3) {
msg.channel.createMessage({ content: 'I said: **There is no uppercase C**. "Powercord".', allowedMentions: {} })
mute(msg.channel.guild, msg.author.id, null, 'Can\'t spell "Powercord" (3rd time)', 300e3)
correctedPeople.set(msg.author.id, 0)
} else {
msg.channel.createMessage({
content: count === 2
? 'There is no uppercase C. "Powercord". You shouldn\'t try again.'
: 'There is no uppercase C. "Powercord".',
allowedMentions: {},
})
correctedPeople.set(msg.author.id, count)
}
}
}
function checkInvite (guild: Guild, invite: Invite) {
const member = invite.inviter && guild.members.get(invite.inviter.id)
console.log(member?.username)
if (!member) return
const channel = guild.channels.get(invite.channel.id)
console.log(channel?.name)
if (!channel) return
if (!channel.permissionsOf(member).has('readMessages')) {
invite.delete('Honeypot: no permissions to see channel but created an invite')
// todo: ban instead of logging
const staff = guild.channels.get(config.discord.ids.channelStaff) as GuildTextableChannel | undefined
staff?.createMessage({ content: `:eyes: ${invite.code} <@${member.id}> ${member.username}#${member.discriminator} <#${invite.channel.id}>`, allowedMentions: {} })
}
// todo: check if user is muted, flag invite as suspicious
}
export default function (bot: CommandClient) {
bot.on('messageCreate', processMessage)
bot.on('messageUpdate', processMessage)
bot.on('inviteCreate', checkInvite)
} | the_stack |
"use strict";
import { TeamServerContext} from "../../contexts/servercontext";
import { IArgumentProvider, IExecutionResult, ITfvcCommand, IPendingChange } from "../interfaces";
import { ArgumentBuilder } from "./argumentbuilder";
import { CommandHelper } from "./commandhelper";
import * as fs from "fs";
/**
* This command returns the status of the workspace as a list of pending changes.
* NOTE: Currently this command does not support all of the options of the command line
* <p/>
* status [/workspace:<value>] [/shelveset:<value>] [/format:brief|detailed|xml] [/recursive] [/user:<value>] [/nodetect] [<itemSpec>...]
*/
export class Status implements ITfvcCommand<IPendingChange[]> {
private _serverContext: TeamServerContext;
private _localPaths: string[];
private _ignoreFolders: boolean;
public constructor(serverContext: TeamServerContext, ignoreFolders: boolean, localPaths?: string[]) {
this._serverContext = serverContext;
this._ignoreFolders = ignoreFolders;
this._localPaths = localPaths;
}
public GetArguments(): IArgumentProvider {
const builder: ArgumentBuilder = new ArgumentBuilder("status", this._serverContext)
.AddSwitchWithValue("format", "xml", false)
.AddSwitch("recursive");
if (this._localPaths && this._localPaths.length > 0) {
for (let i: number = 0; i < this._localPaths.length; i++) {
builder.Add(this._localPaths[i]);
}
}
return builder;
}
public GetOptions(): any {
return {};
}
/**
* Parses the output of the status command when formatted as xml.
* SAMPLE
* <?xml version="1.0" encoding="utf-8"?>
* <status>
* <pending-changes>
* <pending-change server-item="$/tfsTest_03/Folder333/DemandEquals_renamed.java" version="217" owner="NORTHAMERICA\jpricket" date="2017-02-08T11:12:06.766-0500" lock="none" change-type="rename" workspace="Folder1_00" source-item="$/tfsTest_03/Folder333/DemandEquals.java" computer="JPRICKET-DEV2" local-item="D:\tmp\tfsTest03_44\Folder333\DemandEquals_renamed.java" file-type="windows-1252"/>
* </pending-changes>
* <candidate-pending-changes>
* <pending-change server-item="$/tfsTest_01/test.txt" version="0" owner="jason" date="2016-07-13T12:36:51.060-0400" lock="none" change-type="add" workspace="MyNewWorkspace2" computer="JPRICKET-DEV2" local-item="D:\tmp\test\test.txt"/>
* </candidate-pending-changes>
* </status>
*/
public async ParseOutput(executionResult: IExecutionResult): Promise<IPendingChange[]> {
// Throw if any errors are found in stderr or if exitcode is not 0
CommandHelper.ProcessErrors(executionResult);
const changes: IPendingChange[] = [];
const xml: string = CommandHelper.TrimToXml(executionResult.stdout);
// Parse the xml using xml2js
const json: any = await CommandHelper.ParseXml(xml);
if (json && json.status) {
// get all the pending changes first
const pending: any = json.status.pendingchanges[0].pendingchange;
if (pending) {
for (let i: number = 0; i < pending.length; i++) {
this.add(changes, this.convert(pending[i].$, false), this._ignoreFolders);
}
}
// next, get all the candidate pending changes
const candidate: any = json.status.candidatependingchanges[0].pendingchange;
if (candidate) {
for (let i: number = 0; i < candidate.length; i++) {
this.add(changes, this.convert(candidate[i].$, true), this._ignoreFolders);
}
}
}
return changes;
}
public GetExeArguments(): IArgumentProvider {
//return this.GetArguments();
const builder: ArgumentBuilder = new ArgumentBuilder("status", this._serverContext)
.AddSwitchWithValue("format", "detailed", false)
.AddSwitch("recursive");
if (this._localPaths && this._localPaths.length > 0) {
for (let i: number = 0; i < this._localPaths.length; i++) {
builder.Add(this._localPaths[i]);
}
}
return builder;
}
public GetExeOptions(): any {
return this.GetOptions();
}
/*
Parses the output of the status command when formatted as detailed
SAMPLE
$/jeyou/README.md;C19
User : Jeff Young (TFS)
Date : Wednesday, February 22, 2017 1:47:26 PM
Lock : none
Change : edit
Workspace : jeyou-dev00-tfexe-OnPrem
Local item : [JEYOU-DEV00] C:\repos\TfExe.Tfvc.L2VSCodeExtension.RC.TFS\README.md
File type : utf-8
-------------------------------------------------------------------------------------------------------------------------------------------------------------
Detected Changes:
-------------------------------------------------------------------------------------------------------------------------------------------------------------
$/jeyou/therightstuff.txt
User : Jeff Young (TFS)
Date : Wednesday, February 22, 2017 11:48:34 AM
Lock : none
Change : add
Workspace : jeyou-dev00-tfexe-OnPrem
Local item : [JEYOU-DEV00] C:\repos\TfExe.Tfvc.L2VSCodeExtension.RC.TFS\therightstuff.txt
1 change(s), 0 detected change(s)
*/
public async ParseExeOutput(executionResult: IExecutionResult): Promise<IPendingChange[]> {
// Throw if any errors are found in stderr or if exitcode is not 0
CommandHelper.ProcessErrors(executionResult);
const changes: IPendingChange[] = [];
if (!executionResult.stdout) {
return changes;
}
const lines: string[] = CommandHelper.SplitIntoLines(executionResult.stdout, true, false); //leave empty lines
let detectedChanges: boolean = false;
let curChange: IPendingChange;
for (let i: number = 0; i < lines.length; i++) {
const line: string = lines[i];
if (line.indexOf(" detected change(s)") > 0) {
//This tells us we're done
break;
}
if (!line || line.trim().length === 0) {
//If we have a curChange, we're finished with it
if (curChange !== undefined) {
changes.push(curChange);
curChange = undefined;
}
continue;
}
if (line.startsWith("--------") || line.toLowerCase().startsWith("detected changes: ")) {
//Starting Detected Changes...
detectedChanges = true;
continue;
}
if (line.startsWith("$/")) {
//$/jeyou/README.md;C19 //versioned
//$/jeyou/README.md //isCandidate
const parts: string[] = line.split(";C");
curChange = { changeType: undefined, computer: undefined, date: undefined, localItem: undefined,
sourceItem: undefined, lock: undefined, owner: undefined,
serverItem: (parts && parts.length >= 1 ? parts[0] : undefined),
version: (parts && parts.length === 2 ? parts[1] : "0"),
workspace: undefined, isCandidate: detectedChanges };
} else {
// Add the property to the current item
const colonPos: number = line.indexOf(":");
if (colonPos > 0) {
const propertyName = this.getPropertyName(line.slice(0, colonPos).trim().toLowerCase());
if (propertyName) {
let propertyValue: string = colonPos + 1 < line.length ? line.slice(colonPos + 1).trim() : "";
if (propertyName.toLowerCase() === "localitem") {
//Local item : [JEYOU-DEV00] C:\repos\TfExe.Tfvc.L2VSCodeExtension.RC.TFS\README.md
const parts: string[] = propertyValue.split("] ");
curChange["computer"] = parts[0].substr(1); //pop off the beginning [
propertyValue = parts[1];
}
curChange[propertyName] = propertyValue;
}
}
}
}
return changes;
}
private getPropertyName(name: string): string {
switch (name) {
case "local item": return "localItem";
case "source item": return "sourceItem";
case "user": return "owner"; //TODO: I don't think this is accurate
case "date": return "date";
case "lock": return "lock";
case "change": return "changeType";
case "workspace": return "workspace";
}
return undefined;
}
private add(changes: IPendingChange[], newChange: IPendingChange, ignoreFolders: boolean) {
// Deleted files won't exist, but we still include them in the results
if (ignoreFolders && fs.existsSync(newChange.localItem)) {
// check to see if the local item is a file or folder
const f: string = newChange.localItem;
const stats: any = fs.lstatSync(f);
if (stats.isDirectory()) {
// It's a directory/folder and we don't want those
return;
}
}
changes.push(newChange);
}
private convert(jsonChange: any, isCandidate: boolean): IPendingChange {
// TODO check to make sure jsonChange is valid
return {
changeType: jsonChange.changetype,
computer: jsonChange.computer,
date: jsonChange.date,
localItem: jsonChange.localitem,
sourceItem: jsonChange.sourceitem,
lock: jsonChange.lock,
owner: jsonChange.owner,
serverItem: jsonChange.serveritem,
version: jsonChange.version,
workspace: jsonChange.workspace,
isCandidate: isCandidate
};
}
} | the_stack |
import { PersistentModel, StoryboardFilePath } from '../store/editor-state'
import { fastForEach, NO_OP } from '../../../core/shared/utils'
import { createPersistentModel, delay } from '../../../utils/utils.test-utils'
import { generateUID } from '../../../core/shared/uid-utils'
import {
AssetFile,
isAssetFile,
ProjectFile,
TextFile,
} from '../../../core/shared/project-file-types'
import { AssetToSave, SaveProjectResponse, LoadProjectResponse } from '../server'
import { localProjectKey } from '../../../common/persistence'
import { MockUtopiaTsWorkers } from '../../../core/workers/workers'
import {
addFileToProjectContents,
AssetFileWithFileName,
getContentsTreeFileFromString,
} from '../../assets'
import { forceNotNull } from '../../../core/shared/optional-utils'
import { assetFile } from '../../../core/model/project-file-utils'
import { loggedInUser, notLoggedIn } from '../../../common/user'
import { EditorAction, EditorDispatch } from '../action-types'
import { LocalProject } from './generic/persistence-types'
import { PersistenceMachine } from './persistence'
import { PersistenceBackend } from './persistence-backend'
let mockSaveLog: { [key: string]: Array<PersistentModel> } = {}
let mockDownloadedAssetsLog: { [projectId: string]: Array<string> } = {}
let mockUploadedAssetsLog: { [projectId: string]: Array<string> } = {}
let mockProjectsToError: Set<string> = new Set<string>()
let allProjectIds: Array<string> = []
let serverProjects: { [key: string]: PersistentModel } = {}
let localProjects: { [key: string]: LocalProject<PersistentModel> } = {}
const base64Contents = 'data:asset/xyz;base64,SomeBase64'
const mockAssetFileWithBase64 = assetFile(base64Contents)
const AssetFileWithoutBase64 = assetFile(undefined)
const ProjectName = 'Project Name'
const BaseModel = createPersistentModel()
const FirstRevision = updateModel(BaseModel)
const SecondRevision = updateModel(FirstRevision)
const ThirdRevision = updateModel(SecondRevision)
const FourthRevision = updateModel(ThirdRevision)
function mockRandomProjectID(): string {
const newId = generateUID(allProjectIds)
allProjectIds.push(newId)
return newId
}
function updateModel(model: PersistentModel): PersistentModel {
const oldFile = forceNotNull(
'Unexpectedly null.',
getContentsTreeFileFromString(model.projectContents, StoryboardFilePath),
)
const updatedFile = {
...oldFile,
lastRevisedTime: Date.now(),
}
return {
...model,
projectContents: addFileToProjectContents(
model.projectContents,
StoryboardFilePath,
updatedFile,
),
}
}
jest.mock('../server', () => ({
updateSavedProject: async (
projectId: string,
persistentModel: PersistentModel | null,
name: string | null,
): Promise<SaveProjectResponse> => {
if (mockProjectsToError.has(projectId)) {
return Promise.reject(`Deliberately failing for ${projectId}`)
}
if (persistentModel != null) {
let currentLog = mockSaveLog[projectId] ?? []
currentLog.push(persistentModel)
mockSaveLog[projectId] = currentLog
serverProjects[projectId] = persistentModel
}
return Promise.resolve({ id: projectId, ownerId: 'Owner' })
},
saveAssets: async (projectId: string, assets: Array<AssetToSave>): Promise<void> => {
const uploadedAssets = assets.map((a) => a.fileName)
mockUploadedAssetsLog[projectId] = uploadedAssets
return Promise.resolve()
},
downloadAssetsFromProject: async (
projectId: string | null,
allProjectAssets: Array<AssetFileWithFileName>,
): Promise<Array<AssetFileWithFileName>> => {
const downloadedAssets = allProjectAssets
.filter((a) => a.file.base64 == null)
.map((a) => a.fileName)
mockDownloadedAssetsLog[projectId!] = downloadedAssets
return allProjectAssets.map((assetWithFile) => ({
...assetWithFile,
file: mockAssetFileWithBase64,
}))
},
createNewProjectID: async (): Promise<string> => {
return mockRandomProjectID()
},
assetToSave: (fileType: string, base64: string, fileName: string): AssetToSave => {
return {
fileType: fileType,
base64: base64,
fileName: fileName,
}
},
loadProject: async (
projectId: string,
_lastSavedTS: string | null = null,
): Promise<LoadProjectResponse> => {
const project = serverProjects[projectId]
if (project == null) {
return { type: 'ProjectNotFound' }
} else {
return {
type: 'ProjectLoaded',
id: projectId,
ownerId: 'Owner',
title: 'Project Name',
createdAt: '',
modifiedAt: '',
content: project,
}
}
},
}))
jest.mock('../actions/actions', () => ({
...(jest.requireActual('../actions/actions') as any), // This pattern allows us to only mock a single function https://jestjs.io/docs/en/jest-object#jestrequireactualmodulename
load: async (): Promise<void> => {
return Promise.resolve()
},
}))
jest.mock('../../../common/server', () => ({
checkProjectOwnership: async (projectId: string) => ({
isOwner: true,
}),
}))
jest.setTimeout(10000)
jest.mock('localforage', () => ({
getItem: async (id: string): Promise<LocalProject<PersistentModel> | null> => {
return Promise.resolve(localProjects[id])
},
setItem: async (id: string, project: LocalProject<PersistentModel>) => {
localProjects[id] = project
},
removeItem: async (id: string) => {
delete localProjects[id]
},
keys: async () => {
return Object.keys(localProjects)
},
}))
function setupTest(saveThrottle: number = 0) {
let capturedData = {
newProjectId: undefined as string | undefined,
updatedFiles: {} as { [fileName: string]: AssetFile },
dispatchedActions: [] as Array<EditorAction>,
projectNotFound: false,
createdOrLoadedProject: undefined as PersistentModel | undefined,
}
const testDispatch: EditorDispatch = (actions: ReadonlyArray<EditorAction>) => {
capturedData.dispatchedActions.push(...actions)
fastForEach(actions, (action) => {
if (action.action === 'SET_PROJECT_ID') {
capturedData.newProjectId = action.id
} else if (action.action === 'UPDATE_FILE' && isAssetFile(action.file)) {
capturedData.updatedFiles[action.filePath] = action.file
}
})
}
const onProjectNotFound = () => (capturedData.projectNotFound = true)
const onCreatedOrLoadedProject = (
_projectId: string,
_projectName: string,
createdOrLoadedProject: PersistentModel,
) => (capturedData.createdOrLoadedProject = createdOrLoadedProject)
const testMachine = new PersistenceMachine(
PersistenceBackend,
testDispatch,
onProjectNotFound,
onCreatedOrLoadedProject,
saveThrottle,
)
return {
capturedData: capturedData,
testDispatch: testDispatch,
testMachine: testMachine,
}
}
describe('Saving', () => {
it('Saves locally when logged out', async () => {
const { capturedData, testMachine } = setupTest()
testMachine.createNew(ProjectName, BaseModel)
await delay(20)
testMachine.save(ProjectName, FirstRevision, 'force')
await delay(20)
testMachine.stop()
expect(capturedData.newProjectId).toBeDefined()
expect(mockSaveLog[capturedData.newProjectId!]).toBeUndefined()
expect(localProjects[localProjectKey(capturedData.newProjectId!)]).toBeDefined()
expect(localProjects[localProjectKey(capturedData.newProjectId!)]!.model).toEqual(FirstRevision)
})
it('Saves to server when logged in', async () => {
const { capturedData, testMachine } = setupTest()
testMachine.login()
await delay(20)
testMachine.createNew(ProjectName, BaseModel)
await delay(20)
testMachine.save(ProjectName, FirstRevision, 'force')
await delay(20)
testMachine.stop()
expect(localProjects[localProjectKey(capturedData.newProjectId!)]).toBeUndefined()
expect(capturedData.newProjectId).toBeDefined()
expect(mockSaveLog[capturedData.newProjectId!]).toEqual([BaseModel, FirstRevision])
})
it('Throttles saves', async () => {
const { capturedData, testMachine } = setupTest(10000)
testMachine.login()
await delay(20)
testMachine.createNew(ProjectName, BaseModel)
await delay(20)
testMachine.save(ProjectName, FirstRevision, 'throttle') // Should be throttled and replaced by the next save
await delay(20)
testMachine.save(ProjectName, SecondRevision, 'throttle') // Should be throttled and replaced by the next save
await delay(20)
testMachine.save(ProjectName, ThirdRevision, 'throttle')
await delay(20)
testMachine.sendThrottledSave()
await delay(20)
testMachine.save(ProjectName, FourthRevision, 'throttle') // Should be throttled and won't save before the end of the test
await delay(20)
testMachine.stop()
expect(localProjects[localProjectKey(capturedData.newProjectId!)]).toBeUndefined()
expect(capturedData.newProjectId).toBeDefined()
expect(mockSaveLog[capturedData.newProjectId!]).toEqual([BaseModel, ThirdRevision])
})
it('Does not throttle forced saves', async () => {
const { capturedData, testMachine } = setupTest(10000)
testMachine.login()
await delay(20)
testMachine.createNew(ProjectName, BaseModel)
await delay(20)
testMachine.save(ProjectName, FirstRevision, 'force')
await delay(20)
testMachine.save(ProjectName, SecondRevision, 'force')
await delay(20)
testMachine.save(ProjectName, ThirdRevision, 'force')
await delay(20)
testMachine.save(ProjectName, FourthRevision, 'force')
await delay(20)
testMachine.stop()
expect(localProjects[localProjectKey(capturedData.newProjectId!)]).toBeUndefined()
expect(capturedData.newProjectId).toBeDefined()
expect(mockSaveLog[capturedData.newProjectId!]).toEqual([
BaseModel,
FirstRevision,
SecondRevision,
ThirdRevision,
FourthRevision,
])
})
})
describe('Login state', () => {
// TODO Rheese and Balazs FIX THIS!
xit('Logging in mid-session will switch to server saving and delete the local save', async () => {
const { capturedData, testMachine } = setupTest()
testMachine.createNew(ProjectName, BaseModel)
await delay(20)
// Check it was saved locally only
expect(capturedData.newProjectId).toBeDefined()
expect(mockSaveLog[capturedData.newProjectId!]).toBeUndefined()
expect(localProjects[localProjectKey(capturedData.newProjectId!)]).toBeDefined()
expect(localProjects[localProjectKey(capturedData.newProjectId!)]!.model).toEqual(BaseModel)
testMachine.login()
await delay(20)
// Check that logging in uploaded it and deleted the local version
expect(mockSaveLog[capturedData.newProjectId!]).toEqual([BaseModel])
expect(localProjects[localProjectKey(capturedData.newProjectId!)]).toBeUndefined()
testMachine.save(ProjectName, FirstRevision, 'force')
await delay(20)
testMachine.stop()
// Check that future saves go to the server
expect(mockSaveLog[capturedData.newProjectId!]).toEqual([BaseModel, FirstRevision])
expect(localProjects[localProjectKey(capturedData.newProjectId!)]).toBeUndefined()
})
it('Logging out mid-session will switch to local saving', async () => {
const { capturedData, testMachine } = setupTest()
testMachine.login()
await delay(20)
testMachine.createNew(ProjectName, BaseModel)
await delay(20)
// Check it was saved to the server
expect(localProjects[localProjectKey(capturedData.newProjectId!)]).toBeUndefined()
expect(capturedData.newProjectId).toBeDefined()
expect(mockSaveLog[capturedData.newProjectId!]).toEqual([BaseModel])
testMachine.logout()
await delay(20)
testMachine.save(ProjectName, FirstRevision, 'force')
await delay(20)
testMachine.stop()
// Check it was saved locally
expect(localProjects[localProjectKey(capturedData.newProjectId!)]).toBeDefined()
expect(localProjects[localProjectKey(capturedData.newProjectId!)]!.model).toEqual(FirstRevision)
expect(mockSaveLog[capturedData.newProjectId!]).toEqual([BaseModel]) // Should be no new saves
})
})
describe('Loading a project', () => {
function addServerProject(id: string, model: PersistentModel) {
serverProjects[id] = model
}
function addLocalProject(id: string, model: PersistentModel) {
const now = new Date().toISOString()
localProjects[localProjectKey(id)] = {
model: model,
createdAt: now,
lastModified: now,
thumbnail: '',
name: ProjectName,
}
}
it('Loads a server project', async () => {
const { capturedData, testMachine } = setupTest()
const projectId = mockRandomProjectID()
addServerProject(projectId, BaseModel)
testMachine.load(projectId)
await delay(20)
expect(capturedData.projectNotFound).toBeFalsy()
expect(capturedData.createdOrLoadedProject).toEqual(BaseModel)
})
// TODO Rheese and Balazs FIX THIS!
xit('Loads a local project', async () => {
const { capturedData, testMachine } = setupTest()
const projectId = mockRandomProjectID()
addLocalProject(projectId, BaseModel)
testMachine.load(projectId)
await delay(20)
expect(capturedData.projectNotFound).toBeFalsy()
expect(capturedData.createdOrLoadedProject).toEqual(BaseModel)
})
// TODO Rheese and Balazs fix this
xit('Favours a local project over a server project', async () => {
const { capturedData, testMachine } = setupTest()
const serverProject = BaseModel
const localProject = updateModel(BaseModel)
const projectId = mockRandomProjectID()
addServerProject(projectId, serverProject)
addLocalProject(projectId, localProject)
testMachine.load(projectId)
await delay(40)
expect(capturedData.projectNotFound).toBeFalsy()
expect(capturedData.createdOrLoadedProject).toEqual(localProject)
})
})
describe('Forking a project', () => {
const AssetFileName = 'asset.xyz'
const startProject: PersistentModel = {
...BaseModel,
projectContents: addFileToProjectContents(
BaseModel.projectContents,
AssetFileName,
AssetFileWithoutBase64,
),
}
const startProjectIncludingBase64: PersistentModel = {
...BaseModel,
projectContents: addFileToProjectContents(
BaseModel.projectContents,
AssetFileName,
mockAssetFileWithBase64,
),
}
it('Downloads the base 64 for assets and uploads them against the new project id if the user is signed in', async () => {
const { capturedData, testMachine } = setupTest()
// Create the initial project
testMachine.login()
await delay(20)
testMachine.createNew(ProjectName, startProject)
await delay(20)
expect(capturedData.newProjectId).toBeDefined()
const startProjectId = capturedData.newProjectId!
testMachine.fork()
await delay(20)
testMachine.stop()
const forkedProjectId = capturedData.newProjectId!
expect(forkedProjectId).not.toEqual(startProjectId)
expect(mockDownloadedAssetsLog[startProjectId]).toEqual([AssetFileName])
expect(mockUploadedAssetsLog[forkedProjectId]).toEqual([AssetFileName])
expect(mockSaveLog[forkedProjectId]).toEqual([startProject])
expect(capturedData.updatedFiles[AssetFileName]).toEqual(AssetFileWithoutBase64)
expect(
capturedData.dispatchedActions.some(
(action) => action.action === 'SET_FORKED_FROM_PROJECT_ID' && action.id === startProjectId,
),
).toBeTruthy()
})
it('Downloads the base 64 for assets and stores them in the project if the user is not signed in', async () => {
const { capturedData, testMachine } = setupTest()
// Create the initial project
testMachine.login()
await delay(20)
testMachine.createNew(ProjectName, startProject)
await delay(20)
expect(capturedData.newProjectId).toBeDefined()
const startProjectId = capturedData.newProjectId!
testMachine.logout()
await delay(20)
testMachine.fork()
await delay(20)
testMachine.stop()
const forkedProjectId = capturedData.newProjectId!
expect(forkedProjectId).not.toEqual(startProjectId)
expect(mockDownloadedAssetsLog[startProjectId]).toEqual([AssetFileName])
expect(mockUploadedAssetsLog[forkedProjectId]).toBeUndefined()
expect(mockSaveLog[forkedProjectId]).toBeUndefined()
expect(localProjects[localProjectKey(forkedProjectId)]).toBeDefined()
expect(localProjects[localProjectKey(forkedProjectId)]!.model).toEqual({
...startProject,
projectContents: addFileToProjectContents(
startProject.projectContents,
AssetFileName,
assetFile(base64Contents),
),
})
expect(capturedData.updatedFiles[AssetFileName]).toEqual(mockAssetFileWithBase64)
expect(
capturedData.dispatchedActions.some(
(action) => action.action === 'SET_FORKED_FROM_PROJECT_ID' && action.id === startProjectId,
),
).toBeTruthy()
})
it('Does not download or upload anything if the original project constains the base 64 and the user is not signed in', async () => {
const { capturedData, testMachine } = setupTest()
// Create the initial project
await delay(20)
testMachine.createNew(ProjectName, startProjectIncludingBase64)
await delay(20)
expect(capturedData.newProjectId).toBeDefined()
const startProjectId = capturedData.newProjectId!
await delay(20)
testMachine.fork()
await delay(20)
testMachine.stop()
const forkedProjectId = capturedData.newProjectId!
expect(forkedProjectId).not.toEqual(startProjectId)
expect(mockDownloadedAssetsLog[startProjectId]).toEqual([])
expect(mockUploadedAssetsLog[forkedProjectId]).toBeUndefined()
expect(mockSaveLog[forkedProjectId]).toBeUndefined()
expect(localProjects[localProjectKey(forkedProjectId)]).toBeDefined()
expect(localProjects[localProjectKey(capturedData.newProjectId!)]!.model).toEqual(
startProjectIncludingBase64,
)
expect(capturedData.updatedFiles[AssetFileName]).toEqual(mockAssetFileWithBase64)
expect(
capturedData.dispatchedActions.some(
(action) => action.action === 'SET_FORKED_FROM_PROJECT_ID' && action.id === startProjectId,
),
).toBeTruthy()
})
}) | the_stack |
import { DiscordenoChannel } from "../../structures/channel.ts";
import { DiscordenoGuild } from "../../structures/guild.ts";
import { DiscordenoMember } from "../../structures/member.ts";
import { DiscordenoMessage } from "../../structures/message.ts";
import { DiscordenoRole } from "../../structures/role.ts";
import { Collection } from "../../util/collection.ts";
import { PresenceUpdate } from "../activity/presence_update.ts";
import { StageInstance } from "../channels/stage_instance.ts";
import { ThreadMember } from "../channels/threads/thread_member.ts";
import { ThreadMembersUpdate } from "../channels/threads/thread_members_update.ts";
import { Emoji } from "../emojis/emoji.ts";
import { GatewayPayload } from "../gateway/gateway_payload.ts";
import { DiscordGatewayPayload } from "../gateway/gateway_payload.ts";
import { IntegrationCreateUpdate } from "../integrations/integration_create_update.ts";
import { IntegrationDelete } from "../integrations/integration_delete.ts";
import { ApplicationCommandCreateUpdateDelete } from "../interactions/commands/application_command_create_update_delete.ts";
import { Interaction } from "../interactions/interaction.ts";
import { InviteCreate } from "../invites/invite_create.ts";
import { InviteDelete } from "../invites/invite_delete.ts";
import { MessageReactionAdd } from "../messages/message_reaction_add.ts";
import { MessageReactionRemove } from "../messages/message_reaction_remove.ts";
import { MessageReactionRemoveAll } from "../messages/message_reaction_remove_all.ts";
import { TypingStart } from "../misc/typing_start.ts";
import { User } from "../users/user.ts";
import { VoiceServerUpdate } from "../voice/voice_server_update.ts";
import { VoiceState } from "../voice/voice_state.ts";
import { DebugArg } from "./debug_arg.ts";
import { GuildUpdateChange } from "./guild_update_change.ts";
export type EventHandlersDefinitions = {
/** Sent when a new Slash Command is created, relevant to the current user. */
applicationCommandCreate: [data: ApplicationCommandCreateUpdateDelete];
/** Sent when a Slash Command relevant to the current user is updated. */
applicationCommandUpdate: [data: ApplicationCommandCreateUpdateDelete];
/** Sent when a Slash Command relevant to the current user is deleted. */
applicationCommandDelete: [data: ApplicationCommandCreateUpdateDelete];
/** Sent when properties about the user change. */
botUpdate: [user: User];
/** Sent when a new guild channel is created, relevant to the current user. */
channelCreate: [channel: DiscordenoChannel];
/** Sent when a channel is updated. This is not sent when the field `last_message_id` is altered. To keep track of the `last_message_id` changes, you must listen for `MESSAGE_CREATE` events. */
channelUpdate: [channel: DiscordenoChannel, oldChannel: DiscordenoChannel];
/** Sent when a channel relevant to the current user is deleted. */
channelDelete: [channel: DiscordenoChannel];
/** Sent when a message pin is updated */
channelPinsUpdate: [channel: DiscordenoChannel, guild?: DiscordenoGuild, lastPinTimestamp?: string | null];
debug: [args: string | DebugArg, data?: string];
/** Sent before every event. Discordeno awaits the execution of this event before main event gets sent. */
dispatchRequirements: [data: DiscordGatewayPayload, shardId: number];
/** Sent when a user is banned from a guild. */
guildBanAdd: [guild: DiscordenoGuild, user: User, member?: DiscordenoMember];
/** Sent when a user is unbanned from a guild. */
guildBanRemove: [guild: DiscordenoGuild, user: User, member?: DiscordenoMember];
/**
* This event can be sent in three different scenarios:
* 1. When a user is initially connecting, to lazily load and backfill information for all unavailable guilds sent in the `READY` event. Guilds that are unavailable due to an outage will send a `GUILD_DELETE` event.
* 2. When a Guild becomes available again to the client.
* 3. When the current user joins a new Guild.
*
* This event does not get sent on startup
*/
guildCreate: [guild: DiscordenoGuild];
/** This event does get sent on start when shards are loading the guilds */
guildLoaded: [guild: DiscordenoGuild];
/** When a guild goes available this event will be ran. */
guildAvailable: [guild: DiscordenoGuild];
/** When a guild goes unavailable this event will be ran. */
guildUnavailable: [guild: DiscordenoGuild];
/** Sent when a guilds integration gets updated */
guildIntegrationsUpdate: [guild: DiscordenoGuild];
/** Sent when a guild is updated. */
guildUpdate: [guild: DiscordenoGuild, changes: GuildUpdateChange[]];
/** Sent when a guild becomes or was already unavailable due to an outage, or when the user leaves or is removed from a guild. If the `unavailable` field is not set, the user was removed from the guild. */
guildDelete: [guild: DiscordenoGuild];
/** Sent when a guild's emojis have been updated. */
guildEmojisUpdate: [guild: DiscordenoGuild, emojis: Collection<bigint, Emoji>, oldEmojis: Collection<bigint, Emoji>];
/** Sent when a new user joins a guild. */
guildMemberAdd: [guild: DiscordenoGuild, member: DiscordenoMember];
/** Sent when a user is removed from a guild (leave/kick/ban). */
guildMemberRemove: [guild: DiscordenoGuild, user: User, member?: DiscordenoMember];
/** Sent when a guild member is updated. This will also fire when the user object of a guild member changes. */
guildMemberUpdate: [guild: DiscordenoGuild, member: DiscordenoMember, oldMember?: DiscordenoMember];
/** Sent when a user uses a Slash Command. */
interactionCreate: [data: Omit<Interaction, "member">, member?: DiscordenoMember];
/** Sent when a user uses a Slash Command in a guild. */
interactionGuildCreate: [data: Omit<Interaction, "member">, member: DiscordenoMember];
/** Sent when a user uses a Slash Command in a dm. */
interactionDMCreate: [data: Omit<Interaction, "member">];
/** Sent when a message is created. */
messageCreate: [message: DiscordenoMessage];
/** Sent when a message is deleted. */
messageDelete: [partial: { id: string; channel: DiscordenoChannel }, message?: DiscordenoMessage];
/** Sent when a message is updated. */
messageUpdate: [message: DiscordenoMessage, oldMessage: DiscordenoMessage];
/** Sent when a user updates its nickname */
nicknameUpdate: [guild: DiscordenoGuild, member: DiscordenoMember, nickname: string, oldNickname?: string];
/** A user's presence is their current state on a guild. This event is sent when a user's presence or info, such as name or avatar, is updated. */
presenceUpdate: [presence: PresenceUpdate, oldPresence?: PresenceUpdate];
/** Sent before every event execution. Discordeno will not await its execution. */
raw: [data: GatewayPayload];
/** Sent when all shards went ready. */
ready: [];
/** Sent when a user adds a reaction to a message. */
reactionAdd: [data: MessageReactionAdd, message?: DiscordenoMessage];
/** Sent when a user removes a reaction from a message. */
reactionRemove: [data: MessageReactionRemove, message?: DiscordenoMessage];
/** Sent when a user explicitly removes all reactions from a message. */
reactionRemoveAll: [payload: MessageReactionRemoveAll, message?: DiscordenoMessage];
/** Sent when a bot removes all instances of a given emoji from the reactions of a message. */
reactionRemoveEmoji: [emoji: Partial<Emoji>, messageId: bigint, channelId: bigint, guildId?: bigint];
/** Sent when a guild role is created. */
roleCreate: [guild: DiscordenoGuild, role: DiscordenoRole];
/** Sent when a guild role is deleted. */
roleDelete: [guild: DiscordenoGuild, role: DiscordenoRole];
/** Sent when a guild role is updated. */
roleUpdate: [guild: DiscordenoGuild, role: DiscordenoRole, old: DiscordenoRole];
roleGained: [guild: DiscordenoGuild, member: DiscordenoMember, roleId: bigint];
roleLost: [guild: DiscordenoGuild, member: DiscordenoMember, roleId: bigint];
shardReady: [shardId: number];
/** Sent when a shard failed to load. */
shardFailedToLoad: [shardId: number, unavailableGuildIds: Set<bigint>];
/** Sent when a Stage instance is created (i.e. the Stage is now "live"). */
stageInstanceCreate: [instance: StageInstance];
/** Sent when a Stage instance has been deleted (i.e. the Stage has been closed). */
stageInstanceDelete: [instance: StageInstance];
/** Sent when a Stage instance has been updated. */
stageInstanceUpdate: [instance: StageInstance];
/** Sent when a thread is created */
threadCreate: [channel: DiscordenoChannel];
/** Sent when a thread is updated */
threadUpdate: [cahnnel: DiscordenoChannel, oldChannel: DiscordenoChannel];
/** Sent when the bot gains access to threads */
threadListSync: [channels: Collection<bigint, DiscordenoChannel>, members: ThreadMember[], guildId: bigint];
/** Sent when the current users thread member is updated */
threadMemberUpdate: [threadMember: ThreadMember];
/** Sent when anyone is added to or removed from a thread */
threadMembersUpdate: [update: ThreadMembersUpdate];
/** Sent when a thread is deleted */
threadDelete: [channel: DiscordenoChannel];
/** Sent when a user starts typing in a channel. */
typingStart: [data: TypingStart];
/** Sent when a user joins a voice channel */
voiceChannelJoin: [member: DiscordenoMember, channelId: bigint];
/** Sent when a user leaves a voice channel. Does not get sent when user switches the voice channel */
voiceChannelLeave: [member: DiscordenoMember, channelId: bigint];
/** Sent when a user switches the voice channel */
voiceChannelSwitch: [member: DiscordenoMember, channelId: bigint, oldChannelId: bigint];
/** Sent when a voice server is updated with information for making the bot connect to a voice channel. */
voiceServerUpdate: [payload: VoiceServerUpdate, guild: DiscordenoGuild];
/** Sent when someone joins/leaves/moves voice channels. */
voiceStateUpdate: [member: DiscordenoMember, voiceState: VoiceState];
/** Sent when a guild channel's webhook is created, updated, or deleted. */
webhooksUpdate: [channelId: bigint, guildId: bigint];
/** Sent when a member has passed the guild's Membership Screening requirements */
membershipScreeningPassed: [guild: DiscordenoGuild, member: DiscordenoMember];
/** Sent when an integration is created on a server such as twitch, youtube etc.. */
integrationCreate: [data: IntegrationCreateUpdate];
/** Sent when an integration is updated. */
integrationUpdate: [data: IntegrationCreateUpdate];
/** Sent when an integration is deleted. */
integrationDelete: [data: IntegrationDelete];
/** Sent when a new invite to a channel is created. */
inviteCreate: [data: InviteCreate];
/** Sent when an invite is deleted. */
inviteDelete: [data: InviteDelete];
};
export type EventHandlers = {
[E in keyof EventHandlersDefinitions]?: (...args: EventHandlersDefinitions[E]) => unknown;
}; | the_stack |
import { getAllPackageInfo, findGitRoot } from '../monorepo/index';
import { readConfig } from '../read-config';
import * as glob from 'glob';
import * as path from 'path';
import * as fs from 'fs';
import chalk from 'chalk';
interface ImportErrorGroup {
count: number;
matches: { [filePath: string]: { importPath: string; alternative?: string }[] };
}
interface ImportErrors {
pathAbsolute: ImportErrorGroup;
pathNotFile: ImportErrorGroup;
pathRelative: ImportErrorGroup;
pathDeep: ImportErrorGroup;
pathReExported: ImportErrorGroup;
importStar: ImportErrorGroup;
exportMulti: ImportErrorGroup;
exportDefault: ImportErrorGroup;
}
export function lintImports() {
const gitRoot = findGitRoot();
const sourcePath = path.join(process.cwd(), 'src');
const cwdNodeModulesPath = path.join(process.cwd(), 'node_modules');
const nodeModulesPath = path.join(gitRoot, 'node_modules');
if (!fs.existsSync(sourcePath)) {
return;
}
const allowedDeepImports = [
// This is a temporary measure until we figure out what root file these should be exported from.
// TODO: Ideally these would eventually be removed.
'@fluentui/react-examples/lib/react-experiments/TilesList/ExampleHelpers',
'@fluentui/react-examples/lib/react-experiments/CollapsibleSection/CollapsibleSection.Recursive.Example',
'@fluentui/react-examples/lib/react/Keytip/KeytipSetup',
'@fluentui/react-charting/lib/types/IDataPoint',
'@fluentui/react-experiments/lib/utilities/scrolling/ScrollContainer',
// Once the components using this data are promoted, the data should go into @fluentui/example-data
'@fluentui/react-experiments/lib/common/TestImages',
// Only used in experimental examples. Will need a different approach for this to work with the editor.
'@fluentui/foundation-legacy/lib/next/composed',
// Imported by theming examples. Need to find a different approach.
];
const allowedReexportedImports = ['@fluentui/foundation-legacy/lib/next/composed'];
const reExportedPackages = {
'@fluentui/foundation-legacy': 'Foundation',
'@fluentui/font-icons-mdl2': 'Icons',
'@fluentui/merge-styles': 'Styling',
'@fluentui/style-utilities': 'Styling',
'@fluentui/utilities': 'Utilities',
'@fluentui/date-time-utilities': 'DateTimeUtilities',
};
const packagesInfo = getAllPackageInfo();
const currentPackageJson = readConfig('package.json');
const currentMonorepoPackage = currentPackageJson.name;
return lintSource();
function lintSource() {
const files = glob.sync(path.join(sourcePath, '**/*.{ts,tsx}'));
const importErrors: ImportErrors = {
pathAbsolute: { count: 0, matches: {} },
pathNotFile: { count: 0, matches: {} },
pathRelative: { count: 0, matches: {} },
pathDeep: { count: 0, matches: {} },
pathReExported: { count: 0, matches: {} },
importStar: { count: 0, matches: {} },
exportMulti: { count: 0, matches: {} },
exportDefault: { count: 0, matches: {} },
};
for (const file of files) {
const isExample = file.includes('.Example.') && !file.includes('.scss');
if (!file.includes('.test.ts')) {
_evaluateFile(file, importErrors, isExample);
}
}
if (reportFilePathErrors(importErrors)) {
return Promise.reject('Errors in imports were found!');
}
return Promise.resolve();
}
function _evaluateFile(filePath: string, importErrors: ImportErrors, isExample: boolean) {
// !! be careful !! changing the regex can affect matched parts below.
const importStatementRegex = /^(import|export) [^'"]*(?:from )?['"]([^'"]+)['"];.*$/;
const fileContent = fs.readFileSync(filePath, 'utf8');
const importStatements = fileContent.match(new RegExp(importStatementRegex, 'gm'));
if (importStatements) {
importStatements.forEach(statement => {
const parts = importStatementRegex.exec(statement);
if (parts) {
_evaluateImport(filePath, parts, importErrors, isExample);
}
});
}
if (isExample) {
// borrowing this script to also check for some problematic export patterns in examples
const relativePath = path.relative(sourcePath, filePath);
// Check for multiple exported things that might be components (if this happens, the example editor
// and export to codepen won't know what to render)
const exportRegex = /^export (const|class) (\w+)/;
const exportStatements = fileContent.match(new RegExp(exportRegex, 'gm'));
if (!exportStatements) {
_addError(importErrors.exportMulti, relativePath, 'no exported class or const');
} else if (exportStatements.length > 1) {
const exports = exportStatements.map(exp => exp.match(exportRegex)[2]);
_addError(importErrors.exportMulti, relativePath, 'choose one of ' + exports.join(', '));
}
// Check for default exports
const defaultExport = fileContent.match(/^export default (class |const )?(\w+)/m);
if (defaultExport) {
_addError(importErrors.exportDefault, relativePath, defaultExport[2]);
}
}
}
/**
* @param importMatch - Result of running `importStatementRegex` against a single import
* (`[1]` will be the import path)
*/
function _evaluateImport(
filePath: string,
importMatch: RegExpMatchArray,
importErrors: ImportErrors,
isExample?: boolean,
) {
const importPath = importMatch[2];
const packageRootPath = importPath.split('/')[0];
const relativePath = path.relative(sourcePath, filePath);
let fullImportPath: string;
let pathIsRelative = false;
let pathIsDeep = false;
let pkgName: string;
if (importPath[0] === '.') {
// import is a file path. is this a file?
fullImportPath = _evaluateImportPath(path.dirname(filePath), importPath);
pathIsRelative = true;
} else if (packagesInfo[importPath] || packagesInfo[packageRootPath]) {
// skip the full import of packages within the monorepo
// filters out file paths that contain "examples", ".doc.", "exampleData"
const filterOut = /(examples)|(\.doc\.)|(exampleData)/gm;
const isAcceptedPath = filePath.match(filterOut) === null;
const isntAtPath = importPath[0] !== '@';
// checks if the import root directory is the same as the current working directory
const isSameDirectory = process.cwd().match(new RegExp(`(${packageRootPath})$`, 'gm'));
if (!isExample && isntAtPath && isAcceptedPath && isSameDirectory) {
_addError(importErrors.pathAbsolute, relativePath, importPath);
}
return;
} else {
const pkgNameMatch = importPath.match(/^(@[\w-]+\/[\w-]+|[\w-]+)/);
if (pkgNameMatch === null) {
// This means the import does not adhere to what we are looking for, so skip linting.
return;
}
pkgName = pkgNameMatch[1];
// we don't evaluate imports of non monorepo packages
if (!Object.keys(packagesInfo).includes(pkgName)) {
return;
}
if (pkgName === currentMonorepoPackage) {
const importPathWithoutPkgName = importPath.substring(pkgName.length + 1 /* 1 is for '/' */);
fullImportPath = _evaluateImportPath(process.cwd(), './' + importPathWithoutPkgName);
} else {
fullImportPath =
_evaluateImportPath(nodeModulesPath, './' + importPath) ||
_evaluateImportPath(cwdNodeModulesPath, './' + importPath);
}
// A "deep" path is anything that goes further into the package than <pkg>/lib/<file>
let allowedSegments = pkgName[0] === '@' ? 4 : 3;
const isCompatImport = importPath.match(/\/compat/g);
allowedSegments = isCompatImport ? allowedSegments + 1 : allowedSegments;
pathIsDeep = importPath.split(/\//g).length > allowedSegments;
}
if (!fullImportPath || fs.statSync(fullImportPath).isDirectory()) {
_addError(importErrors.pathNotFile, relativePath, importPath);
}
if (isExample) {
const isScss = importPath.endsWith('.scss');
if (pathIsRelative && !isScss) {
_addError(importErrors.pathRelative, relativePath, importPath);
}
if (pathIsDeep && !isScss && !allowedDeepImports.includes(importPath)) {
_addError(importErrors.pathDeep, relativePath, importPath);
}
if (reExportedPackages[pkgName] && !allowedReexportedImports.includes(importPath)) {
_addError(
importErrors.pathReExported,
relativePath,
importPath,
'@fluentui/react/lib/' + reExportedPackages[pkgName],
);
}
if (importMatch[0].startsWith('import * from') && !isScss) {
_addError(importErrors.importStar, relativePath, importPath);
}
}
}
function _evaluateImportPath(filePath: string, importPath: string) {
const fullImportPath = path.resolve(filePath, importPath);
const extensions = ['.ts', '.tsx', '.js', ''];
for (const ext of extensions) {
const match = fullImportPath + ext;
if (fs.existsSync(match)) {
return match;
}
}
return undefined;
}
function _addError(errorGroup: ImportErrorGroup, relativePath: string, importPath: string, alternative?: string) {
errorGroup.count++;
errorGroup.matches[relativePath] = errorGroup.matches[relativePath] || [];
errorGroup.matches[relativePath].push({ importPath, alternative });
}
function reportFilePathErrors(importErrors: ImportErrors) {
const errorMessages: { [k in keyof ImportErrors]: string } = {
pathAbsolute:
'files are using absolute imports. Please update the following imports to use relative paths instead:',
pathNotFile:
'import path(s) do not reference physical files. This can break AMD imports. ' +
'Please ensure the following imports reference physical files:',
pathRelative:
'example files are using relative imports. For example portability, please ensure that the following imports are absolute:',
pathDeep:
'example files are using deep imports. To promote best practices, ' +
`please only import from root-level files ('<package-name>' or '<package-name>/lib/<file>').`,
pathReExported:
'example files are directly importing from packages that @fluentui/react re-exports. ' +
'Please change the following imports to reference @fluentui/react instead:',
importStar:
'example files are using "import *" which causes problems with the website example editor. Please import things by name instead.',
exportMulti:
'example files are exporting multiple classes/consts (or none). Please export exactly one component per example.',
exportDefault: 'example files are using a default export. Please use only named exports.',
};
let hasError = false;
for (const groupName of Object.keys(importErrors)) {
const errorGroup: ImportErrorGroup = importErrors[groupName];
if (errorGroup.count) {
hasError = true;
console.error(`${chalk.red('ERROR')}: ${errorGroup.count} ${errorMessages[groupName]}`);
console.error('-------------------------------------');
for (const filePath in errorGroup.matches) {
console.error(` ${filePath}:`);
for (const { importPath, alternative } of errorGroup.matches[filePath]) {
console.error(` ${chalk.inverse(importPath)}`);
if (alternative) {
console.error(` (use instead: '${alternative}')`);
}
}
}
}
}
return hasError;
}
}
// @ts-ignore
if (require.main === module) {
lintImports();
} | the_stack |
import { Scorer } from "./scorer";
import { InvertedIndex, toCodePoints } from "./inverted_index";
import { BoolQuery, FuzzyQuery, Query, QueryTypes, TermQuery, WildcardQuery } from "./query_types";
import { Dict } from "../../common/types";
import { RunAutomaton } from "./fuzzy/run_automaton";
import { LevenshteinAutomata } from "./fuzzy/levenshtein_automata";
import QueryResults = Scorer.QueryResults;
import Index = InvertedIndex.Index;
import { analyze, Analyzer } from "./analyzer/analyzer";
function calculateMinShouldMatch(optionalClauseCount: number, spec: undefined | number | string): number {
if (spec === undefined) {
return 1;
}
if (typeof spec === "number") {
return (spec < 0) ? optionalClauseCount + spec : spec;
}
let result = optionalClauseCount;
if (spec.includes("<")) {
// Parse conditional minimumShouldMatch.;
for (const s of spec.split(" ")) {
const parts = s.split("<");
const upperBound = parseInt(parts[0]);
if (optionalClauseCount <= upperBound) {
return result;
} else {
result = calculateMinShouldMatch(optionalClauseCount, parts[1]);
}
}
return result;
}
if (spec.includes("%")) {
// Parse percentage.
const percent = parseInt(spec.slice(0, -1));
const calc = (result * percent) * (1 / 100);
result = (calc < 0) ? result + Math.ceil(calc) : Math.floor(calc);
} else {
const calc = parseInt(spec);
result = (calc < 0) ? result + calc : calc;
}
return (result < 1) ? 1 : result;
}
/**
* @hidden
*/
export class IndexSearcher {
private _invIdxs: Dict<InvertedIndex>;
private _docs: Set<InvertedIndex.DocumentIndex>;
private _scorer: Scorer;
/**
* Constructs an index searcher.
* @param {Dict<InvertedIndex>} invIdxs - the inverted indexes
* @param {Set<number>} docs - the ids of the documents
*/
constructor(invIdxs: Dict<InvertedIndex>, docs: Set<InvertedIndex.DocumentIndex>) {
this._invIdxs = invIdxs;
this._docs = docs;
this._scorer = new Scorer(this._invIdxs);
}
public search(query: Query): Scorer.ScoreResults {
let queryResults = this._recursive(query.query, true);
// Do final scoring.
if (query.calculate_scoring !== undefined ? query.calculate_scoring : true) {
return this._scorer.finalScore(query, queryResults);
}
const result: Scorer.ScoreResults = {};
for (const key of queryResults.keys()) {
result[key] = {score: 1};
}
return result;
}
public setDirty() {
this._scorer.setDirty();
}
private _recursive(query: any, doScoring: boolean | null) {
let queryResults: QueryResults = new Map();
const boost = query.boost !== undefined ? query.boost : 1;
const fieldName = query.field !== undefined ? query.field : null;
let root = null;
let analyzer: Analyzer = null;
if (this._invIdxs[fieldName] !== undefined) {
root = this._invIdxs[fieldName].root;
analyzer = this._invIdxs[fieldName].analyzer;
}
switch (query.type) {
case "bool": {
queryResults = null;
if (query.must !== undefined) {
queryResults = this._getUnique(query.must, doScoring, queryResults);
}
if (query.filter !== undefined) {
queryResults = this._getUnique(query.filter, null, queryResults);
}
if (query.should !== undefined) {
const shouldDocs = this._getAll(query.should, doScoring);
let empty = false;
if (queryResults === null) {
empty = true;
queryResults = new Map();
}
const msm = Math.max(1, calculateMinShouldMatch(query.should.length, query.minimum_should_match));
if (empty && msm === 1) {
// Take all documents.
queryResults = shouldDocs;
} else {
// Remove documents with fewer matches.
for (const [docId, res] of shouldDocs) {
if (res.length >= msm) {
if (queryResults.has(docId)) {
queryResults.get(docId).push(...res);
} else if (empty) {
queryResults.set(docId, res);
} else {
queryResults.delete(docId);
}
}
}
}
}
// Match all documents if must/filter/should is not defined.
if (queryResults === null) {
queryResults = this._recursive({type: "match_all"}, false);
}
if (query.not !== undefined) {
let notDocs = this._getAll(query.not, null);
// Remove all matching documents.
for (const docId of notDocs.keys()) {
if (queryResults.has(docId)) {
queryResults.delete(docId);
}
}
}
// Boost query results afterwards.
if (boost !== 1) {
for (const [_, result] of queryResults) {
for (let i = 0; i < result.length; i++) {
result[i].boost *= boost;
}
}
}
break;
}
case "term": {
const cps = toCodePoints(query.value);
let termIdx = InvertedIndex.getTermIndex(cps, root);
this._scorer.score(fieldName, boost, termIdx, doScoring, queryResults, cps);
break;
}
case "terms": {
for (let i = 0; i < query.value.length; i++) {
const cps = toCodePoints(query.value[i]);
let termIdx = InvertedIndex.getTermIndex(cps, root);
this._scorer.score(fieldName, boost, termIdx, doScoring, queryResults, cps);
}
break;
}
case "fuzzy": {
const [f, idf] = fuzzySearch(query, root);
for (let i = 0; i < f.length; i++) {
this._scorer.score(fieldName, boost * f[i].boost, f[i].index, doScoring, queryResults, f[i].term, idf);
}
break;
}
case "wildcard": {
const enableScoring = query.enable_scoring !== undefined ? query.enable_scoring : false;
const w = wildcardSearch(query, root);
for (let i = 0; i < w.length; i++) {
this._scorer.score(fieldName, boost, w[i].index, doScoring && enableScoring, queryResults,
w[i].term);
}
break;
}
case "match_all": {
for (let docId of this._docs) {
this._scorer.scoreConstant(boost, docId, queryResults);
}
break;
}
case "constant_score": {
let tmpQueryResults = this._getAll(query.filter, false);
// Add to each document a constant score.
for (const docId of tmpQueryResults.keys()) {
this._scorer.scoreConstant(boost, docId, queryResults);
}
break;
}
case "prefix": {
const enableScoring = query.enable_scoring !== undefined ? query.enable_scoring : false;
const cps = toCodePoints(query.value);
const termIdx = InvertedIndex.getTermIndex(cps, root);
if (termIdx !== null) {
const termIdxs = InvertedIndex.extendTermIndex(termIdx);
for (let i = 0; i < termIdxs.length; i++) {
this._scorer.score(fieldName, boost, termIdxs[i].index, doScoring && enableScoring, queryResults,
[...cps, ...termIdxs[i].term]);
}
}
break;
}
case "exists": {
if (root !== null) {
for (const docId of this._invIdxs[fieldName].docStore.keys()) {
this._scorer.scoreConstant(boost, docId, queryResults);
}
}
break;
}
case "match": {
const terms = analyze(analyzer, query.value);
const operator = query.operator !== undefined ? query.operator : "or";
const boolQuery: BoolQuery = {type: "bool"};
const subQueries: QueryTypes[] = [];
if (operator === "or") {
if (query.minimum_should_match !== undefined) {
boolQuery.minimum_should_match = query.minimum_should_match;
}
// Create a should query.
boolQuery.should = subQueries;
} else {
// Create a must query.
boolQuery.must = subQueries;
}
boolQuery.boost = boost;
if (query.fuzziness !== undefined) {
let prefixLength = query.prefix_length !== undefined ? query.prefix_length : 2;
let extended = query.extended !== undefined ? query.extended : false;
// Add each fuzzy.
for (let i = 0; i < terms.length; i++) {
subQueries.push({
type: "fuzzy", field: fieldName, value: terms[i], fuzziness: query.fuzziness,
prefix_length: prefixLength, extended: extended
} as FuzzyQuery);
}
} else {
// Add each term.
for (let i = 0; i < terms.length; i++) {
subQueries.push({type: "term", field: fieldName, value: terms[i]} as TermQuery);
}
}
queryResults = this._recursive(boolQuery, doScoring);
break;
}
default:
break;
}
return queryResults;
}
private _getUnique(queries: any[], doScoring: boolean | null, queryResults: QueryResults): QueryResults {
if (queries.length === 0) {
return queryResults;
}
for (let i = 0; i < queries.length; i++) {
let currDocs = this._recursive(queries[i], doScoring);
if (queryResults === null) {
queryResults = this._recursive(queries[0], doScoring);
continue;
}
for (const docId of queryResults.keys()) {
if (!currDocs.has(docId)) {
queryResults.delete(docId);
} else {
queryResults.get(docId).push(...currDocs.get(docId));
}
}
}
return queryResults;
}
private _getAll(queries: any[], doScoring: boolean | null, queryResults: QueryResults = new Map()): QueryResults {
for (let i = 0; i < queries.length; i++) {
let currDocs = this._recursive(queries[i], doScoring);
for (const docId of currDocs.keys()) {
if (!queryResults.has(docId)) {
queryResults.set(docId, currDocs.get(docId));
} else {
queryResults.get(docId).push(...currDocs.get(docId));
}
}
}
return queryResults;
}
}
type FuzzyResult = { index: Index, term: number[], boost: number };
/**
* Calculates the levenshtein distance. Specialized version.
* Copyright Kigiri: https://github.com/kigiri
* Milot Mirdita: https://github.com/milot-mirdita
* Toni Neubert: https://github.com/Viatorus/
* @param {string} a - a string
* @param {string} b - a string
*/
function calculateLevenshteinDistance(a: number[], b: number[]): number {
let i;
let j;
let prev;
let val;
const row = Array(a.length + 1);
// init the row
for (i = 0; i <= a.length; i++) {
row[i] = i;
}
// fill in the rest
for (i = 1; i <= b.length; i++) {
prev = i;
for (j = 1; j <= a.length; j++) {
if (b[i - 1] === a[j - 1]) { // match
val = row[j - 1];
} else {
val = Math.min(row[j - 1] + 1, // substitution
Math.min(prev + 1, // insertion
row[j] + 1)); // deletion
// transposition
if (i > 1 && j > 1 && b[i - 2] === a[j - 1] && a[j - 2] === b[i - 1]) {
val = Math.min(val, row[j - 1] - (a[j - 1] === b[i - 1] ? 1 : 0));
}
}
row[j - 1] = prev;
prev = val;
}
row[a.length] = prev;
}
return row[a.length];
}
/**
* Performs a fuzzy search.
* @param {FuzzyQuery} query - the fuzzy query
* @param {Index} root - the root index
* @returns {[FuzzyResult, number]} - the fuzzy results and the maximum df
*/
function fuzzySearch(query: FuzzyQuery, root: Index): [FuzzyResult[], number] {
let value = toCodePoints(query.value);
let fuzziness = query.fuzziness !== undefined ? query.fuzziness : "AUTO";
if (fuzziness === "AUTO") {
if (value.length <= 2) {
fuzziness = 0;
} else if (value.length <= 5) {
fuzziness = 1;
} else {
fuzziness = 2;
}
}
let prefixLength = query.prefix_length !== undefined ? query.prefix_length : 0;
let extended = query.extended !== undefined ? query.extended : false;
// Do just a prefix search if zero fuzziness.
if (fuzziness === 0) {
prefixLength = value.length;
}
let result: FuzzyResult[] = [];
let startIdx = root;
let prefix = value.slice(0, prefixLength);
let fuzzy = value;
let df = 0;
// Perform a prefix search.
if (prefixLength !== 0) {
startIdx = InvertedIndex.getTermIndex(prefix, startIdx);
fuzzy = fuzzy.slice(prefixLength);
}
// No startIdx found.
if (startIdx === null) {
return [result, df];
}
// Fuzzy is not necessary anymore, because prefix search includes the whole query value.
if (fuzzy.length === 0) {
if (extended) {
// Add all terms down the index.
const all = InvertedIndex.extendTermIndex(startIdx);
for (let i = 0; i < all.length; i++) {
result.push({index: all[i].index, term: all[i].term, boost: 1});
df = Math.max(df, all[i].index.df);
}
} else if (startIdx.dc !== undefined) {
// Add prefix search result.
result.push({index: startIdx, term: value, boost: 1});
df = startIdx.df;
}
return [result, df];
}
// The matching term.
const term = [0];
// Create an automaton from the fuzzy.
const automaton = new RunAutomaton(new LevenshteinAutomata(fuzzy, fuzziness).toAutomaton());
function determineEditDistance(state: number, term: number[], fuzzy: number[]): number {
// Check how many edits this fuzzy can still do.
let ed = 0;
state = automaton.step(state, 0);
if (state !== -1 && automaton.isAccept(state)) {
ed++;
state = automaton.step(state, 0);
if (state !== -1 && automaton.isAccept(state)) {
ed++;
}
// Special handling for smaller terms.
if (term.length < fuzzy.length) {
if (ed !== fuzziness) {
return calculateLevenshteinDistance(term, fuzzy);
}
// Include the term and fuzzy length.
ed -= fuzzy.length - term.length;
}
}
return fuzziness as number - ed;
}
function recursive(state: number, key: number, idx: Index) {
term[term.length - 1] = key;
// Check the current key of term with the automaton.
state = automaton.step(state, key);
if (state === -1) {
return;
}
if (automaton.isAccept(state)) {
if (extended) {
// Add all terms down the index.
const all = InvertedIndex.extendTermIndex(idx);
for (let i = 0; i < all.length; i++) {
result.push({index: all[i].index, term: all[i].term, boost: 1});
df = Math.max(df, all[i].index.df);
}
return;
} else if (idx.df !== undefined) {
// Calculate boost.
const distance = determineEditDistance(state, term, fuzzy);
const boost = Math.max(0, 1 - distance / Math.min(prefix.length + term.length, value.length));
result.push({index: idx, term: [...prefix, ...term], boost});
df = Math.max(df, idx.df);
}
}
term.push(0);
for (const child of idx) {
recursive(state, child[0], child[1]);
}
term.pop();
}
for (const child of startIdx) {
recursive(0, child[0], child[1]);
}
return [result, df];
}
type WildcardResult = { index: Index, term: number[] };
/**
* Performs a wildcard search.
* @param {WildcardQuery} query - the wildcard query
* @param {Index} root - the root index
* @returns {Array} - the results
*/
function wildcardSearch(query: WildcardQuery, root: Index): WildcardResult[] {
let wildcard = toCodePoints(query.value);
let result: WildcardResult[] = [];
function recursive(index: Index, idx: number = 0, term: number[] = [], escaped: boolean = false) {
if (index === null) {
return;
}
if (idx === wildcard.length) {
if (index.df !== undefined) {
result.push({index: index, term: term.slice()});
}
return;
}
// Escaped character.
if (!escaped && wildcard[idx] === 92 /* \ */) {
recursive(index, idx + 1, term, true);
} else if (!escaped && wildcard[idx] === 63 /* ? */) {
for (const child of index) {
recursive(child[1], idx + 1, [...term, child[0]]);
}
} else if (!escaped && wildcard[idx] === 42 /* * */) {
// Check if asterisk is last wildcard character
if (idx + 1 === wildcard.length) {
const all = InvertedIndex.extendTermIndex(index);
for (let i = 0; i < all.length; i++) {
recursive(all[i].index, idx + 1, [...term, ...all[i].term]);
}
} else {
// Iterate over the whole tree.
recursive(index, idx + 1, term, false);
const indices: InvertedIndex.IndexTerm[] = [{index: index, term: []}];
do {
const index = indices.pop();
for (const child of index.index) {
recursive(child[1], idx + 1, [...term, ...index.term, child[0]]);
indices.push({index: child[1], term: [...index.term, child[0]]});
}
} while (indices.length !== 0);
}
} else {
recursive(InvertedIndex.getTermIndex([wildcard[idx]], index), idx + 1, [...term, wildcard[idx]]);
}
}
recursive(root);
return result;
} | the_stack |
namespace XDate_Test
{
class test_base
{
public assert( ref : boolean )
{
if( true == ref)
{
console.info("OK");
}
else
{
console.warn("NG");
}
}
}
//based on xdate/test/adding.js
class adding extends test_base
{
private addYears() : boolean
{
var d1 = new XDate(2011, 2, 1);
d1.addYears(10);
var d2 = new XDate(2011, 2, 1);
d2.addYears(-2);
return d1.getFullYear() == 2021 &&
d1.getMonth() == 2 &&
d1.getDate() == 1 &&
d2.getFullYear() == 2009 &&
d2.getMonth() == 2 &&
d2.getDate() == 1;
}
private addMonths() : boolean
{
var d1 = new XDate(2012, 2, 6);
d1.addMonths(3);
var d2 = new XDate(2012, 2, 6);
d2.addMonths(-3);
return d1.getFullYear() == 2012 &&
d1.getMonth() == 5 &&
d1.getDate() == 6 &&
d2.getFullYear() == 2011 &&
d2.getMonth() == 11 &&
d2.getDate() == 6;
}
private addMonths_prevent_overflow() : boolean
{
var d1 = new XDate(2010, 11, 30); // dec 30
d1.addMonths(2, true);
var d2 = new XDate(2011, 5, 30); // jun 30
d2.addMonths(-4, true);
return d1.getFullYear() == 2011 &&
d1.getMonth() == 1 &&
d1.getDate() == 28 &&
d2.getFullYear() == 2011 &&
d2.getMonth() == 1 &&
d2.getDate() == 28;
}
private addMonths_prevent_overflow_backwards_january_bug() : boolean {
var d1 = new XDate(2013, 0, 28); // Jan 28
var d2 = new XDate(2013, 0, 14); // Jan 14
return d1.addMonths(-1, true).toString('yyyy-MM-dd') == '2012-12-28' && // Dec 28
d2.addMonths(-1, true).toString('yyyy-MM-dd') == '2012-12-14'; // Dec 14
}
private addDays() : boolean {
var d1 = new XDate(2009, 5, 8);
d1.addDays(30);
var d2 = new XDate(2009, 5, 8);
d2.addDays(-4);
return d1.getFullYear() == 2009 &&
d1.getMonth() == 6 &&
d1.getDate() == 8 &&
d2.getFullYear() == 2009 &&
d2.getMonth() == 5 &&
d2.getDate() == 4;
}
private addHours_addMinutes_addSeconds_addMilliseconds() : boolean {
var d = new XDate(2010, 0, 1, 5, 30, 24, 500);
d.addHours(2);
d.addMinutes(15);
d.addSeconds(6);
d.addMilliseconds(50);
return d.getHours() == 7 &&
d.getMinutes() == 45 &&
d.getSeconds() == 30 &&
d.getMilliseconds() == 550;
}
private addWeeks() : boolean {
return new XDate(2011, 7, 12).addWeeks(2).getDate() == 26 &&
new XDate(2011, 7, 12).addWeeks(-2).getDate() == 29;
}
public constructor()
{
super();
super.assert( this.addYears() );
super.assert( this.addMonths_prevent_overflow() );
super.assert( this.addMonths_prevent_overflow_backwards_january_bug() );
super.assert( this.addDays() );
super.assert( this.addHours_addMinutes_addSeconds_addMilliseconds() );
super.assert( this.addWeeks() );
}
}
class constructors extends test_base
{
public no_args() : boolean {
var xdate = new XDate();
var time = +new Date();
return Math.abs(xdate.getTime() - time) < 1000 && !xdate.getUTCMode();
}
public only_utcMode_false(): boolean {
var xdate = new XDate(false);
var time = +new Date();
return Math.abs(xdate.getTime() - time) < 1000 && !xdate.getUTCMode();
}
public only_utcMode_true() : boolean {
var xdate = new XDate(true);
var time = +new Date();
return Math.abs(xdate.getTime() - time) < 1000 && xdate.getUTCMode();
}
public from_XDate_XDate() : boolean {
var xdate1 = new XDate();
var xdate2 = new XDate(xdate1);
return xdate1.getTime() == xdate2.getTime() &&
!xdate1.getUTCMode() && !xdate2.getUTCMode();
}
public from_XDate_XDate_with_utcMode_true() : boolean {
var xdate1 = new XDate().setUTCMode(true);
var xdate2 = new XDate(xdate1);
//return xdate1.getTime() == xdate2.getTime() &&
//xdate1.getUTCMode() && xdate2.getUTCMode();
return true;
}
public from_XDate_XDate_override_with_utcMode_true() : boolean {
var xdate1 = new XDate();
var xdate2 = new XDate(xdate1, true);
return xdate1.getTime() == xdate2.getTime() &&
!xdate1.getUTCMode() && xdate2.getUTCMode();
}
public from_XDate_XDate_override_with_utcMode_false() : boolean {
var xdate1 = new XDate().setUTCMode(true);
var xdate2 = new XDate(xdate1, false);
return xdate1.getTime() == xdate2.getTime() &&
xdate1.getUTCMode() && !xdate2.getUTCMode();
}
public from_native_Date_utcMode_false() : boolean {
var date = new Date();
var xdate1 = new XDate(date);
var xdate2 = new XDate(date, false);
return date.getTime() == xdate1.getTime() &&
date.getTime() == xdate2.getTime() &&
!xdate1.getUTCMode() && !xdate2.getUTCMode();
}
public from_native_Date_utcMode_true(): boolean {
var date = new Date();
var xdate = new XDate(date, true);
return date.getTime() == xdate.getTime() &&
xdate.getUTCMode();
}
public from_milliseconds_time_utcMode_false() : boolean {
var MS = 933490800000;
var xdate1 = new XDate(MS);
var xdate2 = new XDate(MS, false);
return !xdate1.getUTCMode() &&
!xdate2.getUTCMode() &&
xdate1.getTime() == MS &&
xdate2.getTime() == MS;
}
public from_milliseconds_time_utcMode_true() : boolean {
var MS = 933490800000;
var xdate = new XDate(MS, true);
return xdate.getUTCMode() && xdate.getTime() == MS;
}
public year_month_date_utcMode_false() : boolean {
var YEAR = 2011;
var MONTH = 5;
var DATE = 4;
var xdate1 = new XDate(YEAR, MONTH, DATE);
//var xdate2 = new XDate(YEAR, MONTH, DATE, false);
var xdate2 = new XDate(YEAR, MONTH, DATE);
xdate2.setUTCMode(false);
return !xdate1.getUTCMode() && !xdate2.getUTCMode() &&
xdate1.getTime() == xdate2.getTime() &&
xdate1.getFullYear() == YEAR &&
xdate1.getMonth() == MONTH &&
xdate1.getDate() == DATE &&
!xdate1.getHours() &&
!xdate1.getMinutes() &&
!xdate1.getSeconds() &&
!xdate1.getMilliseconds();
}
public toString_utcMode_undefined_true() : boolean {
var xdate1 = new XDate('2012-09-21');
var xdate2 = new XDate('2012-09-21', true);
return xdate1.toString('yyyy-MM-dd HH-mm-ss') == '2012-09-21 00-00-00' &&
xdate2.toString('yyyy-MM-dd HH-mm-ss') == '2012-09-21 00-00-00';
}
public year_month_date_minutes_seconds_milliseconds_utcMode_false() : boolean {
var YEAR = 2011;
var MONTH = 5;
var DATE = 4;
var HOURS = 13;
var MINUTES = 45;
var SECONDS = 20;
var MILLISECONDS = 750;
var xdate1 = new XDate(YEAR, MONTH, DATE, HOURS, MINUTES, SECONDS, MILLISECONDS);
var xdate2 = new XDate(YEAR, MONTH, DATE, HOURS, MINUTES, SECONDS, MILLISECONDS, false);
return !xdate1.getUTCMode() && !xdate2.getUTCMode() &&
xdate1.getTime() == xdate2.getTime() &&
xdate1.getFullYear() == YEAR &&
xdate1.getMonth() == MONTH &&
xdate1.getDate() == DATE &&
xdate1.getHours() == HOURS &&
xdate1.getMinutes() == MINUTES &&
xdate1.getSeconds() == SECONDS &&
xdate1.getMilliseconds() == MILLISECONDS;
}
public year_month_date_utcMode_true() : boolean {
var YEAR = 2011;
var MONTH = 5;
var DATE = 4;
//var xdate = new XDate(YEAR, MONTH, DATE, true);
var xdate = new XDate(YEAR, MONTH, DATE);
xdate.setUTCMode(true);
return xdate.getUTCMode() &&
xdate.getFullYear() == YEAR &&
xdate.getMonth() == MONTH &&
xdate.getDate() == DATE &&
!xdate.getHours() &&
!xdate.getMinutes() &&
!xdate.getSeconds() &&
!xdate.getMilliseconds();
}
public year_month_date_minutes_seconds_milliseconds_utcMode_true() : boolean {
var YEAR = 2011;
var MONTH = 5;
var DATE = 4;
var HOURS = 13;
var MINUTES = 45;
var SECONDS = 20;
var MILLISECONDS = 750;
var xdate = new XDate(YEAR, MONTH, DATE, HOURS, MINUTES, SECONDS, MILLISECONDS, true);
return xdate.getUTCMode() &&
xdate.getFullYear() == YEAR &&
xdate.getMonth() == MONTH &&
xdate.getDate() == DATE &&
xdate.getHours() == HOURS &&
xdate.getMinutes() == MINUTES &&
xdate.getSeconds() == SECONDS &&
xdate.getMilliseconds() == MILLISECONDS;
}
/*
public without_new_operator() : boolean {
return XDate("Sun Aug 14 2011 00:28:53 GMT-0700 (PDT)") &&
!XDate("asdf").valid();
}
*/
public constructor()
{
super();
super.assert( this.no_args() );
super.assert( this.only_utcMode_false() );
super.assert( this.only_utcMode_true() );
super.assert( this.from_XDate_XDate() );
super.assert(this.from_XDate_XDate_with_utcMode_true());
super.assert(this.from_XDate_XDate_override_with_utcMode_true());
super.assert(this.from_XDate_XDate_override_with_utcMode_false());
super.assert(this.from_native_Date_utcMode_false());
super.assert(this.from_native_Date_utcMode_true());
super.assert(this.from_milliseconds_time_utcMode_false());
super.assert(this.from_milliseconds_time_utcMode_true());
super.assert(this.year_month_date_utcMode_false());
super.assert(this.toString_utcMode_undefined_true());
super.assert(this.year_month_date_minutes_seconds_milliseconds_utcMode_false());
super.assert(this.year_month_date_utcMode_true());
super.assert(this.year_month_date_minutes_seconds_milliseconds_utcMode_true());
}
}
// based on xdate/test/diffing.js
class diffing extends test_base
{
public diffWeeks() : boolean{
return Math.floor(new XDate(2011, 4, 18).diffWeeks(new XDate(2011, 4, 26))) == 1 &&
//Math.abs(new XDate(2011, 4, 18).diffWeeks(new XDate(2011, 4, 26), true) - (1+1/7)) < .001 &&
Math.floor(new XDate(2011, 4, 18).diffWeeks(new XDate(2011, 4, 24))) == 0 &&
//Math.abs(new XDate(2011, 4, 18).diffWeeks(new XDate(2011, 4, 24), true) - (1-1/7)) < .001 &&
Math.floor(new XDate(2011, 4, 18).diffWeeks(new XDate('2011-05-26'))) == 1;
}
public diffYears() :boolean {
return new XDate('2011-04-10').diffYears('2013-04-10') == 2 &&
new XDate('2011-01-01T06:06:06').diffYears('2013-07-01T06:06:06') == 2.5;
}
public diffMonths() :boolean {
return new XDate('2011-06-05').diffMonths('2012-07-05') == 13 &&
new XDate('2012-07-05').diffMonths('2011-06-05') == -13;
}
public diffDays() :boolean {
return new XDate('2012-12-25').diffDays('2012-12-30') == 5;
}
public diffHours() :boolean {
return new XDate('2012-05-05T06:30:00').diffHours('2012-05-05T04:00:00') == -2.5;
}
public diffMinutes() :boolean {
return new XDate('2012-05-01T05:50').diffMinutes('2012-05-01T06:10:30') == 20.5;
}
public diffSeconds() :boolean {
return new XDate('2012-03-01T00:00:45').diffSeconds('2012-03-01T00:01:15') == 30;
}
public diffMilliseconds() :boolean {
return new XDate('2011-06-06T05:05:05').diffMilliseconds('2011-06-06T05:05:08.100') == 3100;
}
public constructor()
{
super();
super.assert( this.diffWeeks() );
super.assert( this.diffYears() );
super.assert( this.diffMonths() );
super.assert( this.diffDays() );
super.assert( this.diffHours() );
super.assert( this.diffMinutes() );
super.assert( this.diffSeconds() );
super.assert( this.diffMilliseconds() );
}
}
// based on xdate/test/formatting.js
class formatting extends test_base
{
public numbers_am() : boolean {
return new XDate(1986, 5, 8, 4, 3, 2)
.toString('MM/dd/yyyy hh:mm:ss tt') == "06/08/1986 04:03:02 am";
}
public numbers_am_uppercase() : boolean {
return new XDate(1986, 5, 8, 4, 3, 2)
.toString('MM/dd/yyyy hh:mm:ss TT') == "06/08/1986 04:03:02 AM";
}
public numbers_am_mini() : boolean {
return new XDate(1986, 5, 8, 4, 3, 2)
.toString('M/d/yy h:m:s t') == "6/8/86 4:3:2 a";
}
public numbers_pm() : boolean {
return new XDate(1986, 5, 8, 14, 3, 2)
.toString('MM/dd/yyyy hh:mm:ss tt') == "06/08/1986 02:03:02 pm";
}
public numbers_pm_uppercase() : boolean {
return new XDate(1986, 5, 8, 14, 3, 2)
.toString('MM/dd/yyyy hh:mm:ss TT') == "06/08/1986 02:03:02 PM";
}
public numbers_pm_mini() : boolean {
return new XDate(1986, 5, 8, 14, 3, 2)
.toString('M/d/yy h:m:s t') == "6/8/86 2:3:2 p";
}
public no_am_pm_confusion() : boolean {
return new XDate(2012, 5, 8).toString('tt') == 'am' &&
new XDate(2012, 5, 8, 12).toString('tt') == 'pm';
}
public numbers_24_hour_clock() : boolean {
return new XDate(1986, 5, 8, 14, 3, 2)
.toString('dd/MM/yyyy HH:mm:ss') == "08/06/1986 14:03:02";
}
public short_names() : boolean {
return new XDate(2011, 10, 5)
.toString('ddd, MMM dd, yyyy') == "Sat, Nov 05, 2011";
}
public long_namesu() : boolean {
return new XDate(2011, 10, 5)
.toString('dddd, MMMM dd, yyyy') == "Saturday, November 05, 2011";
}
public ordinals() : boolean {
return new XDate(2011, 1, 1).toString('dS') == "1st" &&
new XDate(2011, 1, 2).toString('dS') == "2nd" &&
new XDate(2011, 1, 3).toString('dS') == "3rd" &&
new XDate(2011, 1, 4).toString('dS') == "4th" &&
new XDate(2011, 1, 23).toString('dS') == "23rd" &&
new XDate(2011, 1, 11).toString('dS') == "11th";
}
public fff_milliseconds() : boolean {
var d = new XDate();
var s = d.toString('fff');
return d.getMilliseconds() === parseInt(s, 10) && s.length==3;
}
public timezone() : boolean {
var d1 = new XDate();
d1.getTimezoneOffset = function() { return 7 * 60 + 15 };
var d2 = new XDate();
d2.getTimezoneOffset = function() { return -(7 * 60 + 15) };
return d1.toString('z') == '-7' &&
d1.toString('zz') == '-07' &&
d1.toString('zzz') == '-07:15' &&
d2.toString('z') == '+7' &&
d2.toString('zz') == '+07' &&
d2.toString('zzz') == '+07:15';
}
public toString_i() : boolean {
var d = new XDate(2011, 5, 8, 14, 35, 21);
return d.toString('i') == '2011-06-08T14:35:21';
}
public toString_i_utcMode_true() : boolean {
var d = new XDate(2011, 5, 8, 14, 35, 21);
d.setUTCMode(true);
return d.toString('i') == '2011-06-08T14:35:21';
}
public toString_u() : boolean {
var d = new XDate(2011, 5, 8, 14, 35, 21);
return d.toString('u').indexOf('2011-06-08T14:35:21') == 0;
}
public toString_u_utcMode_true() : boolean {
var d = new XDate(2011, 5, 8, 14, 35, 21);
d.setUTCMode(true);
return d.toString('u') == '2011-06-08T14:35:21Z';
}
public toUTCString_i() : boolean {
var d = new XDate(Date.UTC(2011, 5, 8, 14, 35, 21));
return d.toUTCString('i') == '2011-06-08T14:35:21';
}
public toUTCString_i_utcMode_true() : boolean {
var d = new XDate(Date.UTC(2011, 5, 8, 14, 35, 21), true);
return d.toUTCString('i') == '2011-06-08T14:35:21';
}
public toUTCString_u() : boolean {
var d = new XDate(Date.UTC(2011, 5, 8, 14, 35, 21));
return d.toUTCString('u') == '2011-06-08T14:35:21Z';
}
public toUTCString_u_utcMode_true() : boolean {
var d = new XDate(Date.UTC(2011, 5, 8, 14, 35, 21), true);
return d.toUTCString('u') == '2011-06-08T14:35:21Z';
}
public non_zero_parenthesis() : boolean {
var d1 = new XDate(2010, 5, 8, 1);
var d2 = new XDate(2010, 5, 8, 14, 30);
return d1.toString('M/d/yyyy h(:mm)tt') == "6/8/2010 1am" &&
d2.toString('M/d/yyyy h(:mm)tt') == "6/8/2010 2:30pm";
}
public non_zero_parenthesis_nested() : boolean {
return new XDate(2011, 5, 8).toString("(h(:mm)tt)") == "12am" &&
new XDate(2011, 5, 8, 6).toString("(h(:mm)tt)") == "6am" &&
new XDate(2011, 5, 8, 6, 30).toString("(h(:mm)tt)") == "6:30am";
}
public non_zero_parenthesis_crazy_quotes() : boolean {
return new XDate(2010, 5, 8, 14, 30)
.toString("M/d/yyyy h(:mm')')tt") == "6/8/2010 2:30)pm";
}
public string_literal() : boolean {
var d = new XDate(2011, 5, 8);
return d.toString("MMM dS 'yyyy!mm'") == "Jun 8th yyyy!mm";
}
public escaped_single_quote() : boolean {
var d = new XDate(2011, 5, 8);
return d.toString("''MMM dS yyyy''") == "'Jun 8th 2011'";
}
public toString_toUTCString_settings_param() : boolean {
var settings = {
dayNames: ['Sunday', 'Benduday', 'Zhellday', 'Taungsday', 'Centaxday', 'Primeday', 'Saturday']
};
return new XDate(2011, 3, 29).toString('dddd yyyy', settings) == 'Primeday 2011' &&
new XDate(2011, 3, 4, 12).toUTCString('dddd yyyy', settings) == 'Benduday 2011';
}
public iso_week_correct_digits() : boolean {
return new XDate(2011, 2, 1).toString('w') == '9' &&
new XDate(2011, 2, 1).toUTCString('w') == '9' &&
new XDate(2011, 2, 1).toString('ww') == '09' &&
new XDate(2011, 2, 1).toUTCString('ww') == '09';
}
public toString_toUTCString_different_locale() : boolean {
XDate.locales['starwars'] = {
dayNames: ['Sunday', 'Benduday', 'Zhellday', 'Taungsday', 'Centaxday', 'Primeday', 'Saturday']
};
return new XDate(2011, 3, 29).toString('dddd yyyy', 'starwars') == 'Primeday 2011' &&
new XDate(2011, 3, 4, 12).toUTCString('dddd yyyy', 'starwars') == 'Benduday 2011';
}
public toString_toUTCString_new_default_locale() : boolean {
XDate.locales['starwars'] = {
dayNames: ['Sunday', 'Benduday', 'Zhellday', 'Taungsday', 'Centaxday', 'Primeday', 'Saturday']
};
XDate.defaultLocale = 'starwars';
var good =
new XDate(2011, 3, 29).toString('dddd yyyy') == 'Primeday 2011' &&
new XDate(2011, 3, 4, 12).toUTCString('dddd yyyy') == 'Benduday 2011';
XDate.defaultLocale = '';
return good;
}
public custom_formatter_string() : boolean {
XDate.formatters.xxx = 'yyyyMMdd';
var d = new XDate('2012-11-01');
return d.toString('xxx') == '20121101';
}
public custom_formatter_function() : boolean {
XDate.formatters.vvv = function(xdate, useUTC) {
return "cool/" + useUTC + "/" + xdate.getDate();
};
var d = new XDate('2012-10-05');
return d.toString('vvv') == "cool/false/5" &&
d.toUTCString('vvv') == "cool/true/5";
}
public toString_methods_hasLocalTimezone_yes() : boolean {
var realDate = new Date(2011, 3, 20, 12, 30);
var xdate = new XDate(2011, 3, 20, 12, 30);
return realDate.toString() == xdate.toString() &&
realDate.toDateString() == xdate.toDateString() &&
realDate.toTimeString() == xdate.toTimeString() &&
realDate.toLocaleString() == xdate.toLocaleString() &&
realDate.toLocaleDateString() == xdate.toLocaleDateString() &&
realDate.toLocaleTimeString() == xdate.toLocaleTimeString() &&
realDate.toUTCString() == xdate.toUTCString();
//toGMTString() was abolition
//&&
//realDate.toGMTString() == xdate.toGMTString();
}
public toString_methods_hasLocalTimezone_no() : boolean {
var realDate = new Date(2011, 3, 20, 12, 30);
var xdate = new XDate(2011, 3, 20, 12, 30);
xdate.setUTCMode(false);
return realDate.toString().indexOf(xdate.toString()) == 0 &&
realDate.toTimeString().indexOf(xdate.toTimeString()) == 0 &&
realDate.toLocaleString().indexOf(xdate.toLocaleString()) == 0 &&
realDate.toLocaleDateString().indexOf(xdate.toLocaleDateString()) == 0 &&
realDate.toLocaleTimeString().indexOf(xdate.toLocaleTimeString()) == 0;
}
public toGMTString() : boolean {
var xdate = new XDate();
return xdate.toUTCString() == xdate.toGMTString();
}
}
//based on xdate/test/getters.js
class getters extends test_base
{
public getTime_valueOf() : boolean {
var MS = 933490800000;
var xdate1 = new XDate(MS);
var xdate2 = new XDate(MS, false);
// return xdate1.getTime() == MS && xdate1.valueOf() == MS && +xdate1 == MS &&
// xdate2.getTime() == MS && xdate2.valueOf() == MS && xdate2 == MS;
return xdate1.getTime() == MS && xdate1.valueOf() == MS &&
xdate2.getTime() == MS && xdate2.valueOf() == MS;
}
public getUTC() : boolean {
var YEAR = 2011;
var MONTH = 5;
var DATE = 4;
var HOURS = 13;
var MINUTES = 45;
var SECONDS = 20;
var MILLISECONDS = 750;
var xdate = new XDate(Date.UTC(YEAR, MONTH, DATE, HOURS, MINUTES, SECONDS, MILLISECONDS));
return xdate.getUTCFullYear() == YEAR &&
xdate.getUTCMonth() == MONTH &&
xdate.getUTCDate() == DATE &&
xdate.getUTCHours() == HOURS &&
xdate.getUTCMinutes() == MINUTES &&
xdate.getUTCSeconds() == SECONDS &&
xdate.getUTCMilliseconds() == MILLISECONDS;
}
//Deprecated
// public getYear() : boolean {
// var xdate = new XDate(1999, 0, 1);
// return xdate.getYear() == 99;
// }
public getWeek() : boolean {
return new XDate(2011, 2, 1).getWeek() == 9;
}
public getUTCWeek() : boolean {
return new XDate(2011, 2, 1, 12, 30).getUTCWeek() == 9;
}
//Non-standard
/*
public getWeek_getUTCWeek_mega_test() : boolean {
if (!Date.prototype.toLocaleFormat) {
return "need Mozilla toLocaleFormat";
}
var realDate = new Date(2011, 0, 1, 12, 0);
var xdate = new XDate(2011, 0, 1, 12, 0);
while (xdate.getFullYear() != 2014) {
var w1 = parseInt(realDate.toLocaleFormat('%V'), 10);
var w2 = xdate.getWeek();
if (w1 != w2) {
return [
false,
realDate.toString() + '=' + w1 + ' ' + xdate.toString() + '=' + w2
];
}
var realDateUTC = XDate(realDate).setUTCMode(true, true).toDate();
w1 = parseInt(realDateUTC.toLocaleFormat('%V'), 10);
w2 = xdate.getUTCWeek();
if (w1 != w2) {
return [
false,
realDateUTC.toUTCString() + '=' + w1 + ' ' + xdate.toUTCString() + '=' + w2 + ' (UTC!)'
];
}
realDate.setDate(realDate.getDate() + 1);
xdate.setDate(xdate.getDate() + 1);
}
return true;
}
*/
}
// based on xdate/test/parsing.js
class parsing extends test_base
{
public IETF() : boolean {
var s = "Sat Apr 23 2011 13:44:12 GMT";
var d = new XDate(s);
return d.getUTCFullYear() == 2011 &&
d.getUTCMonth() == 3 &&
d.getUTCDate() == 23 &&
d.getUTCHours() == 13 &&
d.getUTCMinutes() == 44 &&
d.getUTCSeconds() == 12 &&
!d.getUTCMode() &&
+d == +new Date(s);
}
public ISO_no_time() : boolean
{
var s = "2010-06-08";
var d = new XDate(s);
return d.getFullYear() == 2010 &&
d.getMonth() == 5 &&
d.getDate() == 8 &&
!d.getHours() &&
!d.getMinutes() &&
!d.getSeconds() &&
!d.getMilliseconds() &&
!d.getUTCMode();
}
public ISO_T() : boolean {
var s = "2010-06-08T14:45:30";
var d = new XDate(s);
return d.getFullYear() == 2010 &&
d.getMonth() == 5 &&
d.getDate() == 8 &&
d.getHours() == 14 &&
d.getMinutes() == 45 &&
d.getSeconds() == 30 &&
!d.getMilliseconds() &&
!d.getUTCMode();
}
public ISO_space() : boolean {
var s = "2010-06-08 14:45:30";
var d = new XDate(s);
return d.getFullYear() == 2010 &&
d.getMonth() == 5 &&
d.getDate() == 8 &&
d.getHours() == 14 &&
d.getMinutes() == 45 &&
d.getSeconds() == 30 &&
!d.getMilliseconds() &&
!d.getUTCMode();
}
public ISO_no_seconds() : boolean {
var s = "2010-06-08T14:45";
var d = new XDate(s);
return d.getFullYear() == 2010 &&
d.getMonth() == 5 &&
d.getDate() == 8 &&
d.getHours() == 14 &&
d.getMinutes() == 45 &&
!d.getSeconds() &&
!d.getMilliseconds() &&
!d.getUTCMode();
}
public ISO_milliseconds() : boolean {
var s = "2010-06-08T14:45:30.500";
var d = new XDate(s);
return d.getFullYear() == 2010 &&
d.getMonth() == 5 &&
d.getDate() == 8 &&
d.getHours() == 14 &&
d.getMinutes() == 45 &&
d.getSeconds() == 30 &&
d.getMilliseconds() == 500 &&
!d.getUTCMode();
}
public ISO_timezone_colon() : boolean {
var s = "2010-06-08T14:00:28-02:30";
var d = new XDate(s);
return d.getUTCHours() == 16 &&
d.getUTCMinutes() == 30 &&
d.getUTCSeconds() == 28 &&
!d.getUTCMode();
}
public ISO_timezone_no_colon() : boolean {
var s = "2010-06-08T14:00:28-0230";
var d = new XDate(s);
return d.getUTCHours() == 16 &&
d.getUTCMinutes() == 30 &&
d.getUTCSeconds() == 28 &&
!d.getUTCMode();
}
public ISO_timezone_hour_only() : boolean {
var s = "2010-06-08T14:45:34-02";
var d = new XDate(s);
return d.getUTCHours() == 16 &&
d.getUTCMinutes() == 45 &&
d.getUTCSeconds() == 34 &&
!d.getUTCMode();
}
public ISO_timezone_positive() : boolean {
var s = "2010-06-08T14:00:28+02:30";
var d = new XDate(s);
return d.getUTCHours() == 11 &&
d.getUTCMinutes() == 30 &&
d.getUTCSeconds() == 28 &&
!d.getUTCMode();
}
public ISO_with_Z() : boolean {
var d = new XDate('2011-06-08T00:00:00Z');
return d.getUTCFullYear() == 2011 &&
d.getUTCMonth() == 5 &&
d.getUTCDate() == 8 &&
!d.getUTCHours() && !d.getUTCMinutes() &&
!d.getUTCMode();
}
public ISO_no_timezone_utcMode_true() : boolean {
var s = "2010-06-08T14:30:28";
var d = new XDate(s, true);
return d.getFullYear() == 2010 && d.getUTCFullYear() == 2010 &&
d.getMonth() == 5 && d.getUTCMonth() == 5 &&
d.getDate() == 8 && d.getUTCDate() == 8 &&
d.getHours() == 14 && d.getUTCHours() == 14 &&
d.getMinutes() == 30 && d.getUTCMinutes() == 30 &&
d.getSeconds() == 28 && d.getUTCSeconds() == 28;
}
public in_and_out() : boolean {
var d = new XDate();
return +new XDate(d.toISOString()) == +d;
}
}
// based on xdate/test/setters.js
class setters extends test_base
{
public set_when_utcMode_false(): boolean{
var xdate = new XDate(2012, 0, 1);
var YEAR = 2011;
var MONTH = 5;
var DATE = 4;
var HOURS = 13;
var MINUTES = 45;
var SECONDS = 20;
var MILLISECONDS = 750;
xdate.setFullYear(YEAR)
.setMonth(MONTH)
.setDate(DATE)
.setHours(HOURS)
.setMinutes(MINUTES)
.setSeconds(SECONDS)
.setMilliseconds(MILLISECONDS);
return xdate.getFullYear() == YEAR &&
xdate.getMonth() == MONTH &&
xdate.getDate() == DATE &&
xdate.getHours() == HOURS &&
xdate.getMinutes() == MINUTES &&
xdate.getSeconds() == SECONDS &&
xdate.getMilliseconds() == MILLISECONDS;
}
public set_when_utcMode_true() : boolean{
var xdate = new XDate(2012, 0, 1, 0,0,0,0, true);
var YEAR = 2011;
var MONTH = 5;
var DATE = 4;
var HOURS = 13;
var MINUTES = 45;
var SECONDS = 20;
var MILLISECONDS = 750;
xdate.setFullYear(YEAR)
.setMonth(MONTH)
.setDate(DATE)
.setHours(HOURS)
.setMinutes(MINUTES)
.setSeconds(SECONDS)
.setMilliseconds(MILLISECONDS);
return xdate.getFullYear() == YEAR &&
xdate.getMonth() == MONTH &&
xdate.getDate() == DATE &&
xdate.getHours() == HOURS &&
xdate.getMinutes() == MINUTES &&
xdate.getSeconds() == SECONDS &&
xdate.getMilliseconds() == MILLISECONDS;
}
public setTime() : boolean {
var MS = 933490800000;
var xdate1 = new XDate();
var xdate2 = new XDate().setUTCMode(true);
xdate1.setTime(MS);
xdate2.setTime(MS);
return xdate1.getTime() == MS && xdate2.getTime() == MS;
}
public setFullYear_allow_overflow() : boolean {
var xdate1 = new XDate(2012, 1, 29);
var xdate2 = new XDate(2012, 1, 29);
xdate1.setFullYear(2013);
xdate2.setFullYear(2013, false);
return xdate1.getMonth() == 2 && xdate1.getDate() == 1 &&
xdate2.getMonth() == 2 && xdate2.getDate() == 1;
}
public setYear_prevent_overflow() : boolean {
var xdate = new XDate(2012, 1, 29);
xdate.setFullYear(2013, true);
return xdate.getMonth() == 1 && xdate.getDate() == 28;
}
public setMonth_allow_overflow() : boolean {
var xdate1 = new XDate(2010, 2, 31, 12);
var xdate2 = new XDate(2010, 2, 31, 12);
xdate1.setMonth(1);
xdate2.setMonth(1, false);
return xdate1.getMonth() == 2 && xdate1.getDate() == 3 &&
xdate2.getMonth() == 2 && xdate2.getDate() == 3
}
public setMonth_prevent_overflow() : boolean {
var d = new XDate(2010, 2, 31, 12);
d.setMonth(1, true);
return d.getMonth() == 1 && d.getDate() == 28;
}
public setUTC_with_utcMode_false() : boolean {
var xdate = new XDate(2012, 0, 1);
var YEAR = 2011;
var MONTH = 5;
var DATE = 4;
var HOURS = 13;
var MINUTES = 45;
var SECONDS = 20;
var MILLISECONDS = 750;
xdate.setUTCFullYear(YEAR)
.setUTCMonth(MONTH)
.setUTCDate(DATE)
.setUTCHours(HOURS)
.setUTCMinutes(MINUTES)
.setUTCSeconds(SECONDS)
.setUTCMilliseconds(MILLISECONDS);
return xdate.getUTCFullYear() == YEAR &&
xdate.getUTCMonth() == MONTH &&
xdate.getUTCDate() == DATE &&
xdate.getUTCHours() == HOURS &&
xdate.getUTCMinutes() == MINUTES &&
xdate.getUTCSeconds() == SECONDS &&
xdate.getUTCMilliseconds() == MILLISECONDS;
}
public setUTC_with_utcMode_true() : boolean {
var xdate = new XDate(2012, 0, 1,0,0,0,0, true);
var YEAR = 2011;
var MONTH = 5;
var DATE = 4;
var HOURS = 13;
var MINUTES = 45;
var SECONDS = 20;
var MILLISECONDS = 750;
xdate.setUTCFullYear(YEAR)
.setUTCMonth(MONTH)
.setUTCDate(DATE)
.setUTCHours(HOURS)
.setUTCMinutes(MINUTES)
.setUTCSeconds(SECONDS)
.setUTCMilliseconds(MILLISECONDS);
return xdate.getUTCFullYear() == YEAR &&
xdate.getUTCMonth() == MONTH &&
xdate.getUTCDate() == DATE &&
xdate.getUTCHours() == HOURS &&
xdate.getUTCMinutes() == MINUTES &&
xdate.getUTCSeconds() == SECONDS &&
xdate.getUTCMilliseconds() == MILLISECONDS;
}
//Deprecated
// public setYear() : boolean {
// var xdate = new XDate(2010, 0, 1);
// xdate.setYear(99);
// return xdate.getFullYear() == 1999;
// }
public setWeek() : boolean {
function test(xdate : XDate , n : number) {
var year = xdate.getFullYear();
xdate.setWeek(n);
return xdate.getWeek() == n &&
xdate.getFullYear() == year &&
xdate.getDay() == 1 && // monday
xdate.getHours() == 0 &&
xdate.getMinutes() == 0 &&
xdate.getSeconds() == 0 &&
xdate.getMilliseconds() == 0;
}
return test(new XDate(), 50) &&
test(new XDate(), 21) &&
test(new XDate(2011, 5, 5), 5) &&
test(new XDate(2009, 12, 12), 13);
}
public setWeek_with_year() : boolean {
function test(xdate : XDate , n : number , year : number) {
xdate.setWeek(n, year);
return xdate.getWeek() == n &&
xdate.getFullYear() == year &&
xdate.getDay() == 1 && // monday
xdate.getHours() == 0 &&
xdate.getMinutes() == 0 &&
xdate.getSeconds() == 0 &&
xdate.getMilliseconds() == 0;
}
return test(new XDate(), 50, 2013) &&
test(new XDate(), 21, 2014) &&
test(new XDate(2011, 5, 5), 5, 1999) &&
test(new XDate(2009, 12, 12), 13, 1995);
}
public setUTCWeek() : boolean {
function test(xdate : XDate , n : number) {
var year = xdate.getUTCFullYear();
xdate.setUTCWeek(n);
return xdate.getUTCWeek() == n &&
xdate.getUTCFullYear() == year &&
xdate.getUTCDay() == 1 && // monday
xdate.getUTCHours() == 0 &&
xdate.getUTCMinutes() == 0 &&
xdate.getUTCSeconds() == 0 &&
xdate.getUTCMilliseconds() == 0;
}
return test(new XDate(), 50) &&
test(new XDate(), 21) &&
test(new XDate(2011, 5, 5), 5) &&
test(new XDate(2009, 12, 12), 13);
}
public setUTCWeek_with_year() : boolean{
function test(xdate : XDate , n : number , year : number ) {
xdate.setUTCWeek(n, year);
return xdate.getUTCWeek() == n &&
xdate.getUTCFullYear() == year &&
xdate.getUTCDay() == 1 && // monday
xdate.getUTCHours() == 0 &&
xdate.getUTCMinutes() == 0 &&
xdate.getUTCSeconds() == 0 &&
xdate.getUTCMilliseconds() == 0;
}
return test(new XDate(), 50, 2013) &&
test(new XDate(), 21, 2014) &&
test(new XDate(2011, 5, 5), 5, 1999) &&
test(new XDate(2009, 12, 12), 13, 1995);
}
public setWeek_overflow() : boolean {
var xdate = new XDate(2012, 0, 3);
xdate.setWeek(54);
return xdate.getFullYear() == 2013 &&
xdate.getWeek() == 2 &&
xdate.getMonth() == 0 &&
xdate.getDate() == 7;
}
public setWeek_underflow() : boolean {
var xdate = new XDate(2012, 0, 2); // a monday
return +xdate.clone().setWeek(0) == +xdate.clone().addWeeks(-1) &&
+xdate.clone().setWeek(-1) == +xdate.clone().addWeeks(-2);
}
public setUTCWeek_correctly_handles_UTC_week_numbering_edge_case() : boolean{
var date = new XDate(Date.UTC(2010, 0, 3));
var wasWeek53 = date.getUTCWeek() === 53;
date.setUTCWeek(53);
return wasWeek53 && "Mon, 28 Dec 2009 00:00:00 GMT" === date.toUTCString();
}
}
// based on xdate/test/utc-mode.js
class utc_mode extends test_base
{
public identical_methods() : boolean {
var xdate = new XDate(true);
return xdate.getFullYear() == xdate.getUTCFullYear() &&
xdate.getMonth() == xdate.getUTCMonth() &&
xdate.getDate() == xdate.getUTCDate() &&
xdate.getHours() == xdate.getUTCHours() &&
xdate.getMinutes() == xdate.getUTCMinutes() &&
xdate.getSeconds() == xdate.getUTCSeconds() &&
xdate.getMilliseconds() == xdate.getUTCMilliseconds();
}
public getUTCMode() : boolean {
var xdate1 = new XDate(0, true);
var xdate2 = new XDate(0, false);
return xdate1.getUTCMode() && !xdate2.getUTCMode();
}
public setUTCMode_to_true() : boolean {
var xdate1 = new XDate();
var xdate2 = xdate1.clone().setUTCMode(true);
return !xdate1.getUTCMode() && xdate2.getUTCMode() && +xdate1 == +xdate2;
}
public setUTCMode_to_true_coerce() : boolean {
var xdate1 = new XDate();
var xdate2 = xdate1.clone().setUTCMode(true, true);
return !xdate1.getUTCMode() &&
xdate2.getUTCMode() &&
(!xdate1.getTimezoneOffset() || xdate1.getTime() != xdate2.getTime()) &&
xdate1.getDate() == xdate2.getDate() &&
xdate2.getDate() == xdate2.getUTCDate() &&
xdate1.getHours() == xdate2.getHours() &&
xdate2.getHours() == xdate2.getUTCHours();
}
public setUTCMode_to_false() : boolean {
var xdate1 = new XDate(2011, 5, 8, 0,0,0,0, true);
var xdate2 = xdate1.clone().setUTCMode(false);
return xdate1.getUTCMode() && !xdate2.getUTCMode() && +xdate1 == +xdate2;
}
public setUTCMode_to_false_coerce() : boolean {
var xdate1 = new XDate(2011, 7, 8, 0,0,0,0, true);
var xdate2 = xdate1.clone().setUTCMode(false, true);
return xdate1.getUTCMode() && !xdate2.getUTCMode() &&
(!xdate1.getTimezoneOffset() || xdate1.getTime() != xdate2.getTime()) &&
xdate1.getDate() == xdate2.getDate() &&
xdate1.getHours() == xdate1.getHours();
}
public getTimezoneOffset() : boolean {
var date = new Date();
var xdate1 = new XDate(+date);
var xdate2 = new XDate(+date, true);
return xdate1.getTimezoneOffset() == date.getTimezoneOffset() &&
!xdate2.getTimezoneOffset();
}
}
// bases on xdate/test/utilities.js
class utilities extends test_base
{
public clone() : boolean {
var d1 = new XDate();
var d2 = d1.clone();
d2.addMinutes(30);
return +d1 != +d2;
}
public clearTime() : boolean {
var d = new XDate(2010, 2, 5, 16, 15, 10, 100);
d.clearTime();
return !d.getHours() && !d.getMinutes() && !d.getSeconds() && !d.getMilliseconds();
}
public valid() : boolean {
var good = new XDate();
var bad = new XDate('asdf');
return good.valid() && !bad.valid();
}
public toDate_hasLocalTimezone_yes() : boolean {
var d = new Date(2012, 5, 8);
var xdate = new XDate(d);
return +xdate.toDate() == +d;
}
public toDate_hasLocalTimezone_no() : boolean {
var d = new Date(2012, 5, 8);
var xdate = new XDate(+d, false);
return +xdate.toDate() == +d;
}
public getDaysInMonth() : boolean {
return XDate.getDaysInMonth(2011, 1) == 28 && // feb
XDate.getDaysInMonth(2012, 1) == 29 && // feb, leap year
XDate.getDaysInMonth(2012, 8) == 30 && // sep
XDate.getDaysInMonth(2012, 6) == 31; // jul
}
public UTC_class_method() : boolean {
return Date.UTC(2011, 3, 20, 12, 30) == XDate.UTC(2011, 3, 20, 12, 30);
}
public parse_class_method() : boolean {
var s = "Sat Apr 23 2011 13:44:12 GMT-0700 (PDT)";
return Date.parse(s) == XDate.parse(s);
//&&
//isNaN(Date.parse()) && isNaN(XDate.parse());
}
public now_class_method() : boolean {
return Math.abs(+new Date() - XDate.now()) < 1000;
}
public today_class_method() : boolean {
var xdate = XDate.today();
var d = new Date();
return xdate.getFullYear() == d.getFullYear() &&
xdate.getMonth() == d.getMonth() &&
xdate.getDate() == d.getDate() &&
!xdate.getHours() &&
!xdate.getSeconds() &&
!xdate.getMilliseconds();
}
public toJSON() : boolean {
var realDate = new Date(2011, 3, 20, 12, 30);
var xdate = new Date(2011, 3, 20, 12, 30);
if (!realDate.toJSON) {
return false;
}
return realDate.toJSON() == xdate.toJSON();
}
public chaining() : boolean {
var d = new XDate()
// .setYear(99)
.setFullYear(2011)
.setWeek(50)
.setMonth(1)
.setDate(5)
.setHours(12)
.setMinutes(50)
.setSeconds(20)
.setMilliseconds(500)
.setTime(0)
.addYears(1)
.addMonths(1)
.addDays(1)
.addMinutes(1)
.addSeconds(1)
.addMilliseconds(1)
.clone()
.clearTime()
.setUTCFullYear(2010)
.setUTCMonth(6)
.setUTCWeek(5)
.setUTCDate(4)
.setUTCHours(12)
.setUTCMinutes(30)
.setUTCSeconds(30)
.setUTCMilliseconds(10)
.setUTCMode(true);
return d instanceof XDate;
}
}
} | the_stack |
import * as loginPage from '../../Base/pages/Login.po';
import { LoginPageData } from '../../Base/pagedata/LoginPageData';
import * as settingsFeaturesPage from '../../Base/pages/SettingsFeatures.po';
import { SettingsFeaturesPageData } from '../../Base/pagedata/SettingsFeaturesPageData';
import * as dashboardPage from '../../Base/pages/Dashboard.po';
import { CustomCommands } from '../../commands';
import { Given, Then, When, And } from 'cypress-cucumber-preprocessor/steps';
let checked = 'be.checked';
const pageLoadTimeout = Cypress.config('pageLoadTimeout');
// Login with email
Given('Login with default credentials and visit Settings features page', () => {
CustomCommands.login(loginPage, LoginPageData, dashboardPage);
cy.visit('/#/pages/settings/features/tenant', { timeout: pageLoadTimeout });
});
// Verify Tenant features
// Task Dashboard features
And('User can see tenant tab button', () => {
settingsFeaturesPage.tabButtonVisible();
});
When('User click on tenant tab button', () => {
settingsFeaturesPage.clickTabButton(0);
});
Then('User can see Task dashboard features', () => {
settingsFeaturesPage.verifySubheader(
SettingsFeaturesPageData.subheaderTextTenant
);
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.taskDashboard
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.teamTaskDashboard
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.myTaskDashboard
);
settingsFeaturesPage.verifyCheckboxState(0, checked);
settingsFeaturesPage.verifyCheckboxState(1, checked);
settingsFeaturesPage.verifyCheckboxState(2, checked);
});
// Payment features
And('User can verify Payment features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.managePayment
);
settingsFeaturesPage.verifyCheckboxState(3, checked);
});
// Proposal features
And('User can verify Proposal features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageProposal
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.proposalTemplate
);
settingsFeaturesPage.verifyCheckboxState(4, checked);
settingsFeaturesPage.verifyCheckboxState(5, checked);
});
// Expense features
And('User can verify Expense features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.createFirstExpense
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.employeeRecurringExpense
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.organizationRecurringExpenses
);
settingsFeaturesPage.verifyCheckboxState(6, checked);
settingsFeaturesPage.verifyCheckboxState(7, checked);
settingsFeaturesPage.verifyCheckboxState(8, checked);
});
// Invoice features
And('User can verify Invoice features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageInvoice
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.invoiceReceived
);
settingsFeaturesPage.verifyCheckboxState(9, checked);
settingsFeaturesPage.verifyCheckboxState(10, checked);
});
// Jobs features
And('User can verify Jobs features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.jobSearch
);
settingsFeaturesPage.verifyCheckboxState(11, checked);
});
// Time Activity features
And('user can verify Time Activity features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageTimeActivity
);
settingsFeaturesPage.verifyCheckboxState(12, checked);
});
// Appointment and Schedule features
And('User can verify Appointment and Schedule features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.employeeAppointment
);
settingsFeaturesPage.verifyCheckboxState(13, checked);
});
// Manage Organization features
And('User can verify Manage Organization features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageOrganizationDetails
);
settingsFeaturesPage.verifyTextExist(SettingsFeaturesPageData.helpCenter);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.organizationEmploymentType
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.organizationDepartment
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.organizationVendor
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.organizationEquipment
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.organizationTag
);
settingsFeaturesPage.verifyCheckboxState(14, checked);
settingsFeaturesPage.verifyCheckboxState(15, checked);
settingsFeaturesPage.verifyCheckboxState(16, checked);
settingsFeaturesPage.verifyCheckboxState(17, checked);
settingsFeaturesPage.verifyCheckboxState(18, checked);
settingsFeaturesPage.verifyCheckboxState(19, checked);
settingsFeaturesPage.verifyCheckboxState(20, checked);
});
// Project features
And('User can verify Project features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageProject
);
settingsFeaturesPage.verifyCheckboxState(21, checked);
});
// Organization Document features
And('User can verify Organization Document features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageOrganizationDocument
);
settingsFeaturesPage.verifyCheckboxState(22, checked);
});
// Goal and Objective features
And('User can verify Goal and Objective features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageGoals
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.goalTimeFrame
);
settingsFeaturesPage.verifyCheckboxState(23, checked);
settingsFeaturesPage.verifyCheckboxState(24, checked);
});
// Users features
And('User can verify Users features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageTenantUsers
);
settingsFeaturesPage.verifyCheckboxState(25, checked);
});
// Apps and Integrations features
And('User can verify Apps and Integrations features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageAvailableApps
);
settingsFeaturesPage.verifyCheckboxState(26, checked);
});
// Setting features
And('User can verify Setting features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageSetting
);
settingsFeaturesPage.verifyTextExist(SettingsFeaturesPageData.fileStorage);
settingsFeaturesPage.verifyTextExist(SettingsFeaturesPageData.SMSGateway);
settingsFeaturesPage.verifyCheckboxState(27, checked);
settingsFeaturesPage.verifyCheckboxState(28, checked);
settingsFeaturesPage.verifyCheckboxState(29, checked);
});
// Custom SMTP features
And('User can verify Custom SMTP features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageTenant
);
settingsFeaturesPage.verifyCheckboxState(30, checked);
});
// Time Tracking features
And('User can verify Time Tracking features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.downloadDesktopApp
);
settingsFeaturesPage.verifyCheckboxState(31, checked);
});
// Estimate features
And('User can verify Estimate features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageEstimate
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.estimateReceived
);
settingsFeaturesPage.verifyCheckboxState(32, checked);
settingsFeaturesPage.verifyCheckboxState(33, checked);
});
// Income features
And('User can verify Income features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.createFirstIncome
);
settingsFeaturesPage.verifyCheckboxState(34, checked);
});
// Dashboard features
And('User can verify Dashboard features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.goToDashboard
);
settingsFeaturesPage.verifyCheckboxState(35, checked);
});
// Sales Pipeline features
And('User can verify Sales Pipeline features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.createSalesPipeline
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.salesPipelineDeal
);
settingsFeaturesPage.verifyCheckboxState(36, checked);
settingsFeaturesPage.verifyCheckboxState(37, checked);
});
// Employees features
And('User can verify Employees features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageEmployees
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.employeeApproval
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.employeeLevel
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.employeePosition
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.employeeTimeOff
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.employeeApprovalPolicy
);
settingsFeaturesPage.verifyCheckboxState(38, checked);
settingsFeaturesPage.verifyCheckboxState(39, checked);
settingsFeaturesPage.verifyCheckboxState(40, checked);
settingsFeaturesPage.verifyCheckboxState(41, checked);
settingsFeaturesPage.verifyCheckboxState(42, checked);
settingsFeaturesPage.verifyCheckboxState(43, checked);
});
// Timesheet features
And('User can verify Timesheet features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageEmployeeTimesheetDaily
);
settingsFeaturesPage.verifyCheckboxState(44, checked);
});
// Candidate features
And('User can verify Candidate features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageCandidates
);
settingsFeaturesPage.verifyTextExist(SettingsFeaturesPageData.manageInvite);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.manageInterview
);
settingsFeaturesPage.verifyCheckboxState(45, checked);
settingsFeaturesPage.verifyCheckboxState(46, checked);
settingsFeaturesPage.verifyCheckboxState(47, checked);
});
// Product Inventory features
And('User can verify Product Inventory features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageProductInventory
);
settingsFeaturesPage.verifyCheckboxState(48, checked);
});
// Organization Team features
And('User can verify Organization Team features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageOrganizationTeam
);
settingsFeaturesPage.verifyCheckboxState(49, checked);
});
// Lead, Customer and Client features
And('User can verify Lead, Customer and Client features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageLeads
);
settingsFeaturesPage.verifyCheckboxState(50, checked);
});
// All Report features
And('User can verify All Report features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageExpense
);
settingsFeaturesPage.verifyCheckboxState(51, checked);
});
// Organizations features
And('User can verify Organizations features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageTenantOrganizations
);
settingsFeaturesPage.verifyCheckboxState(52, checked);
});
// Email History features
And('User can verify Email History features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageEmailHistory
);
settingsFeaturesPage.verifyTextExist(
SettingsFeaturesPageData.customEmailTemplate
);
settingsFeaturesPage.verifyCheckboxState(53, checked);
settingsFeaturesPage.verifyCheckboxState(54, checked);
});
// Entity Import and Export features
And('User can verify Entity Import and Export features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageEntity
);
settingsFeaturesPage.verifyCheckboxState(55, checked);
});
// Roles and Permissions features
And('User can verify Roles and Permissions features', () => {
settingsFeaturesPage.verifyMainTextExist(
SettingsFeaturesPageData.manageRoles
);
settingsFeaturesPage.verifyCheckboxState(56, checked);
}); | the_stack |
import {act, fireEvent, render} from '@testing-library/react';
import {ColorSlider} from '../';
import {installMouseEvent, installPointerEvent} from '@react-spectrum/test-utils';
import {parseColor} from '@react-stately/color';
import React from 'react';
import userEvent from '@testing-library/user-event';
describe('ColorSlider', () => {
let onChangeSpy = jest.fn();
afterEach(() => {
onChangeSpy.mockClear();
});
beforeAll(() => {
jest.spyOn(window.HTMLElement.prototype, 'offsetWidth', 'get').mockImplementation(() => 100);
jest.spyOn(window.HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(() => 100);
// @ts-ignore
jest.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => cb());
jest.useFakeTimers();
});
afterAll(() => {
// @ts-ignore
window.HTMLElement.prototype.offsetWidth.mockReset();
// @ts-ignore
window.HTMLElement.prototype.offsetHeight.mockReset();
jest.useRealTimers();
// @ts-ignore
window.requestAnimationFrame.mockReset();
});
afterEach(() => {
// for restoreTextSelection
jest.runAllTimers();
});
it('sets input props', () => {
let {getByRole} = render(<ColorSlider defaultValue="#000000" channel="red" />);
let slider = getByRole('slider');
expect(slider).toHaveAttribute('type', 'range');
expect(slider).toHaveAttribute('min', '0');
expect(slider).toHaveAttribute('max', '255');
expect(slider).toHaveAttribute('step', '1');
expect(slider).toHaveAttribute('aria-valuetext', '0');
});
it('sets aria-valuetext to formatted value', () => {
let {getByRole} = render(<ColorSlider defaultValue="hsl(10, 50%, 50%)" channel="hue" />);
let slider = getByRole('slider');
expect(slider).toHaveAttribute('type', 'range');
expect(slider).toHaveAttribute('min', '0');
expect(slider).toHaveAttribute('max', '360');
expect(slider).toHaveAttribute('step', '1');
expect(slider).toHaveAttribute('aria-valuetext', '10°');
});
describe('labeling', () => {
it('defaults to showing the channel as a label', () => {
let {getByRole} = render(<ColorSlider defaultValue="#000000" channel="red" />);
let slider = getByRole('slider');
let group = getByRole('group');
expect(slider).toHaveAttribute('aria-labelledby');
expect(slider).not.toHaveAttribute('aria-label');
let label = document.getElementById(slider.getAttribute('aria-labelledby'));
expect(label).toHaveTextContent('Red');
expect(label).toHaveAttribute('id');
expect(group).toHaveAttribute('aria-labelledby', label.id);
expect(group).not.toHaveAttribute('aria-label');
});
it('sets a default aria-label when label={null}', () => {
let {getByRole} = render(<ColorSlider defaultValue="#000000" channel="red" label={null} />);
let slider = getByRole('slider');
let group = getByRole('group');
expect(group).toHaveAttribute('aria-label', 'Red');
expect(group).not.toHaveAttribute('aria-labelledby');
expect(group).toHaveAttribute('id');
expect(slider).toHaveAttribute('aria-labelledby', group.id);
});
it('allows a custom label', () => {
let {getByRole} = render(<ColorSlider defaultValue="#000000" channel="red" label="Test" />);
let slider = getByRole('slider');
let group = getByRole('group');
expect(slider).toHaveAttribute('aria-labelledby');
expect(slider).not.toHaveAttribute('aria-label');
let label = document.getElementById(slider.getAttribute('aria-labelledby'));
expect(label).toHaveTextContent('Test');
expect(label).toHaveAttribute('id');
expect(group).toHaveAttribute('aria-labelledby', label.id);
expect(group).not.toHaveAttribute('aria-label');
});
it('allows a custom aria-label', () => {
let {getByRole} = render(<ColorSlider defaultValue="#000000" channel="red" aria-label="Test" />);
let slider = getByRole('slider');
let group = getByRole('group');
expect(group).toHaveAttribute('aria-label', 'Test');
expect(group).not.toHaveAttribute('aria-labelledby');
expect(group).toHaveAttribute('id');
expect(slider).toHaveAttribute('aria-labelledby', group.id);
});
it('allows a custom aria-labelledby', () => {
let {getByRole} = render(<ColorSlider defaultValue="#000000" channel="red" aria-labelledby="label-id" />);
let slider = getByRole('slider');
let group = getByRole('group');
expect(group).not.toHaveAttribute('aria-label');
expect(group).toHaveAttribute('aria-labelledby', 'label-id');
expect(group).toHaveAttribute('id');
expect(slider).toHaveAttribute('aria-labelledby', group.id);
});
it('clicking on label should focus input', () => {
let {getByRole, getByText} = render(<ColorSlider defaultValue="#000000" channel="red" />);
let label = getByText('Red');
let slider = getByRole('slider');
act(() => label.click());
expect(document.activeElement).toBe(slider);
});
it('shows value label by default', () => {
let {getByRole} = render(<ColorSlider defaultValue="#7f0000" channel="red" />);
let output = getByRole('status');
expect(output).toHaveTextContent('127');
expect(output).toHaveAttribute('for', getByRole('slider').id);
expect(output).not.toHaveAttribute('aria-labelledby');
expect(output).toHaveAttribute('aria-live', 'off');
});
it('shows value label with custom label', () => {
let {getByRole} = render(<ColorSlider defaultValue="#7f0000" channel="red" label="Test" />);
let output = getByRole('status');
expect(output).toHaveTextContent('127');
expect(output).toHaveAttribute('for', getByRole('slider').id);
expect(output).not.toHaveAttribute('aria-labelledby');
expect(output).toHaveAttribute('aria-live', 'off');
});
it('hides value label with showValueLabel=false', () => {
let {queryByRole} = render(<ColorSlider defaultValue="#7f0000" channel="red" showValueLabel={false} />);
expect(queryByRole('status')).toBeNull();
});
it('hides value label when no visible label', () => {
let {queryByRole} = render(<ColorSlider defaultValue="#7f0000" channel="red" label={null} />);
expect(queryByRole('status')).toBeNull();
});
it('hides value label when aria-label is specified', () => {
let {queryByRole} = render(<ColorSlider defaultValue="#7f0000" channel="red" aria-label="Test" />);
expect(queryByRole('status')).toBeNull();
});
it('hides value label when aria-labelledby is specified', () => {
let {queryByRole} = render(<ColorSlider defaultValue="#7f0000" channel="red" aria-labelledby="label-id" />);
expect(queryByRole('status')).toBeNull();
});
it('hides label and value label and has default aria-label when orientation=vertical', () => {
let {getByRole, queryByRole} = render(<ColorSlider defaultValue="#000000" channel="red" orientation="vertical" />);
let slider = getByRole('slider');
let group = getByRole('group');
expect(group).toHaveAttribute('aria-label', 'Red');
expect(group).not.toHaveAttribute('aria-labelledby');
expect(group).toHaveAttribute('id');
expect(slider).toHaveAttribute('aria-labelledby', group.id);
expect(queryByRole('status')).toBeNull();
});
it('uses custom label as aria-label orientation=vertical', () => {
let {getByRole, queryByRole} = render(<ColorSlider defaultValue="#000000" channel="red" label="Test" orientation="vertical" />);
let slider = getByRole('slider');
let group = getByRole('group');
expect(group).toHaveAttribute('aria-label', 'Test');
expect(group).not.toHaveAttribute('aria-labelledby');
expect(group).toHaveAttribute('id');
expect(slider).toHaveAttribute('aria-labelledby', group.id);
expect(queryByRole('status')).toBeNull();
});
it('supports custom aria-label with orientation=vertical', () => {
let {getByRole, queryByRole} = render(<ColorSlider defaultValue="#000000" channel="red" aria-label="Test" orientation="vertical" />);
let slider = getByRole('slider');
let group = getByRole('group');
expect(group).toHaveAttribute('aria-label', 'Test');
expect(group).not.toHaveAttribute('aria-labelledby');
expect(group).toHaveAttribute('id');
expect(slider).toHaveAttribute('aria-labelledby', group.id);
expect(queryByRole('status')).toBeNull();
});
it('supports custom aria-labelledby with orientation=vertical', () => {
let {getByRole, queryByRole} = render(<ColorSlider defaultValue="#000000" channel="red" aria-labelledby="label-id" orientation="vertical" />);
let slider = getByRole('slider');
let group = getByRole('group');
expect(group).not.toHaveAttribute('aria-label');
expect(group).toHaveAttribute('aria-labelledby', 'label-id');
expect(group).toHaveAttribute('id');
expect(slider).toHaveAttribute('aria-labelledby', group.id);
expect(queryByRole('status')).toBeNull();
});
});
it('the slider is focusable', () => {
let {getAllByRole, getByRole} = render(<div>
<button>A</button>
<ColorSlider defaultValue="#000000" channel="red" />
<button>B</button>
</div>);
let slider = getByRole('slider');
let [buttonA, buttonB] = getAllByRole('button');
userEvent.tab();
expect(document.activeElement).toBe(buttonA);
userEvent.tab();
expect(document.activeElement).toBe(slider);
userEvent.tab();
expect(document.activeElement).toBe(buttonB);
userEvent.tab({shift: true});
expect(document.activeElement).toBe(slider);
});
it('disabled', () => {
let {getAllByRole, getByRole} = render(<div>
<button>A</button>
<ColorSlider defaultValue="#000000" channel="red" isDisabled />
<button>B</button>
</div>);
let slider = getByRole('slider');
let [buttonA, buttonB] = getAllByRole('button');
expect(slider).toHaveAttribute('disabled');
userEvent.tab();
expect(document.activeElement).toBe(buttonA);
userEvent.tab();
expect(document.activeElement).toBe(buttonB);
userEvent.tab({shift: true});
expect(document.activeElement).toBe(buttonA);
});
describe('keyboard events', () => {
it('works', () => {
let defaultColor = parseColor('#000000');
let {getByRole} = render(<ColorSlider defaultValue={defaultColor} onChange={onChangeSpy} channel="red" />);
let slider = getByRole('slider');
act(() => {slider.focus();});
fireEvent.keyDown(slider, {key: 'Right'});
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(onChangeSpy.mock.calls[0][0].toString('hexa')).toBe(defaultColor.withChannelValue('red', 1).toString('hexa'));
fireEvent.keyDown(slider, {key: 'Left'});
expect(onChangeSpy).toHaveBeenCalledTimes(2);
expect(onChangeSpy.mock.calls[1][0].toString('hexa')).toBe(defaultColor.withChannelValue('red', 0).toString('hexa'));
});
it('doesn\'t work when disabled', () => {
let defaultColor = parseColor('#000000');
let {getByRole} = render(<ColorSlider defaultValue={defaultColor} onChange={onChangeSpy} channel="red" isDisabled />);
let slider = getByRole('slider');
act(() => {slider.focus();});
fireEvent.keyDown(slider, {key: 'Right'});
expect(onChangeSpy).toHaveBeenCalledTimes(0);
fireEvent.keyDown(slider, {key: 'Left'});
expect(onChangeSpy).toHaveBeenCalledTimes(0);
});
it('respects step', () => {
let defaultColor = parseColor('#000000');
let {getByRole} = render(<ColorSlider defaultValue={defaultColor} onChange={onChangeSpy} channel="red" step={10} />);
let slider = getByRole('slider');
act(() => {slider.focus();});
fireEvent.keyDown(slider, {key: 'Right'});
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(onChangeSpy.mock.calls[0][0].toString('hexa')).toBe(defaultColor.withChannelValue('red', 10).toString('hexa'));
fireEvent.keyDown(slider, {key: 'Left'});
expect(onChangeSpy).toHaveBeenCalledTimes(2);
expect(onChangeSpy.mock.calls[1][0].toString('hexa')).toBe(defaultColor.withChannelValue('red', 0).toString('hexa'));
});
});
describe.each`
type | prepare | actions
${'Mouse Events'} | ${installMouseEvent} | ${[
(el, {pageX, pageY}) => fireEvent.mouseDown(el, {button: 0, pageX, clientX: pageX, pageY, clientY: pageY}),
(el, {pageX, pageY}) => fireEvent.mouseMove(el, {button: 0, pageX, clientX: pageX, pageY, clientY: pageY}),
(el, {pageX, pageY}) => fireEvent.mouseUp(el, {button: 0, pageX, clientX: pageX, pageY, clientY: pageY})
]}
${'Pointer Events'} | ${installPointerEvent}| ${[
(el, {pageX, pageY}) => fireEvent.pointerDown(el, {button: 0, pointerId: 1, pageX, clientX: pageX, pageY, clientY: pageY}),
(el, {pageX, pageY}) => fireEvent.pointerMove(el, {button: 0, pointerId: 1, pageX, clientX: pageX, pageY, clientY: pageY}),
(el, {pageX, pageY}) => fireEvent.pointerUp(el, {button: 0, pointerId: 1, pageX, clientX: pageX, pageY, clientY: pageY})
]}
${'Touch Events'} | ${() => {}} | ${[
(el, {pageX, pageY}) => fireEvent.touchStart(el, {changedTouches: [{identifier: 1, pageX, clientX: pageX, pageY, clientY: pageY}]}),
(el, {pageX, pageY}) => fireEvent.touchMove(el, {changedTouches: [{identifier: 1, pageX, clientX: pageX, pageY, clientY: pageY}]}),
(el, {pageX, pageY}) => fireEvent.touchEnd(el, {changedTouches: [{identifier: 1, pageX, clientX: pageX, pageY, clientY: pageY}]})
]}
`('$type', ({actions: [start, move, end], prepare}) => {
prepare();
it('dragging the thumb works', () => {
let defaultColor = parseColor('hsl(0, 100%, 50%)');
let {getByRole} = render(<ColorSlider channel="hue" defaultValue={defaultColor} onChange={onChangeSpy} />);
let slider = getByRole('slider');
let thumb = slider.parentElement;
expect(document.activeElement).not.toBe(slider);
start(thumb, {pageX: 0});
expect(onChangeSpy).toHaveBeenCalledTimes(0);
expect(document.activeElement).toBe(slider);
move(thumb, {pageX: 40});
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(onChangeSpy.mock.calls[0][0].toString('hsla')).toBe(defaultColor.withChannelValue('hue', 144).toString('hsla'));
expect(document.activeElement).toBe(slider);
end(thumb, {pageX: 40});
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(document.activeElement).toBe(slider);
});
it('dragging the thumb works when vertical', () => {
let defaultColor = parseColor('hsl(0, 100%, 50%)');
let {getByRole} = render(<ColorSlider channel="hue" defaultValue={defaultColor} onChange={onChangeSpy} orientation="vertical" />);
let slider = getByRole('slider');
let thumb = slider.parentElement;
expect(document.activeElement).not.toBe(slider);
start(thumb, {pageY: 100});
expect(onChangeSpy).toHaveBeenCalledTimes(0);
expect(document.activeElement).toBe(slider);
move(thumb, {pageY: 60});
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(onChangeSpy.mock.calls[0][0].toString('hsla')).toBe(defaultColor.withChannelValue('hue', 144).toString('hsla'));
expect(document.activeElement).toBe(slider);
end(thumb, {pageY: 60});
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(document.activeElement).toBe(slider);
});
it('dragging the thumb doesn\'t works when disabled', () => {
let defaultColor = parseColor('hsl(0, 100%, 50%)');
let {getByRole} = render(<ColorSlider channel="hue" isDisabled defaultValue={defaultColor} onChange={onChangeSpy} />);
let slider = getByRole('slider');
let thumb = slider.parentElement;
expect(document.activeElement).not.toBe(slider);
start(thumb, {pageX: 0});
expect(onChangeSpy).toHaveBeenCalledTimes(0);
expect(document.activeElement).not.toBe(slider);
move(thumb, {pageX: 40});
expect(onChangeSpy).toHaveBeenCalledTimes(0);
expect(document.activeElement).not.toBe(slider);
end(thumb, {pageX: 40});
expect(onChangeSpy).toHaveBeenCalledTimes(0);
expect(document.activeElement).not.toBe(slider);
});
it('dragging the thumb respects the step', () => {
let defaultColor = parseColor('hsl(0, 100%, 50%)');
let {getByRole} = render(<ColorSlider channel="hue" defaultValue={defaultColor} onChange={onChangeSpy} step={120} />);
let slider = getByRole('slider');
let thumb = slider.parentElement;
start(thumb, {pageX: 0});
expect(onChangeSpy).toHaveBeenCalledTimes(0);
move(thumb, {pageX: 20});
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(onChangeSpy.mock.calls[0][0].toString('hsla')).toBe(defaultColor.withChannelValue('hue', 120).toString('hsla'));
end(thumb, {pageX: 20});
expect(onChangeSpy).toHaveBeenCalledTimes(1);
});
it('clicking and dragging on the track works', () => {
let defaultColor = parseColor('hsl(0, 100%, 50%)');
let {getByRole} = render(<ColorSlider channel="hue" defaultValue={defaultColor} onChange={onChangeSpy} />);
let slider = getByRole('slider');
let thumb = slider.parentElement;
let container = getByRole('group');
expect(document.activeElement).not.toBe(slider);
start(container, {pageX: 50});
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(onChangeSpy.mock.calls[0][0].toString('hsla')).toBe(defaultColor.withChannelValue('hue', 180).toString('hsla'));
expect(document.activeElement).toBe(slider);
move(thumb, {pageX: 70});
expect(onChangeSpy).toHaveBeenCalledTimes(2);
expect(onChangeSpy.mock.calls[1][0].toString('hsla')).toBe(defaultColor.withChannelValue('hue', 252).toString('hsla'));
expect(document.activeElement).toBe(slider);
end(thumb, {pageX: 70});
expect(onChangeSpy).toHaveBeenCalledTimes(2);
expect(document.activeElement).toBe(slider);
});
it('clicking and dragging on the track works when vertical', () => {
let defaultColor = parseColor('hsl(0, 100%, 50%)');
let {getByRole} = render(<ColorSlider channel="hue" defaultValue={defaultColor} onChange={onChangeSpy} orientation="vertical" />);
let slider = getByRole('slider');
let thumb = slider.parentElement;
let container = getByRole('group');
expect(document.activeElement).not.toBe(slider);
start(container, {pageY: 50});
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(onChangeSpy.mock.calls[0][0].toString('hsla')).toBe(defaultColor.withChannelValue('hue', 180).toString('hsla'));
expect(document.activeElement).toBe(slider);
move(thumb, {pageY: 30});
expect(onChangeSpy).toHaveBeenCalledTimes(2);
expect(onChangeSpy.mock.calls[1][0].toString('hsla')).toBe(defaultColor.withChannelValue('hue', 252).toString('hsla'));
expect(document.activeElement).toBe(slider);
end(thumb, {pageY: 30});
expect(onChangeSpy).toHaveBeenCalledTimes(2);
expect(document.activeElement).toBe(slider);
});
it('clicking and dragging on the track doesn\'t work when disabled', () => {
let defaultColor = parseColor('hsl(0, 100%, 50%)');
let {getByRole} = render(<ColorSlider channel="hue" defaultValue={defaultColor} onChange={onChangeSpy} isDisabled />);
let slider = getByRole('slider');
let container = getByRole('group');
expect(document.activeElement).not.toBe(slider);
start(container, {pageX: 50});
expect(onChangeSpy).toHaveBeenCalledTimes(0);
expect(document.activeElement).not.toBe(slider);
move(container, {pageX: 70});
expect(onChangeSpy).toHaveBeenCalledTimes(0);
expect(document.activeElement).not.toBe(slider);
end(container, {pageX: 70});
expect(onChangeSpy).toHaveBeenCalledTimes(0);
expect(document.activeElement).not.toBe(slider);
});
it('clicking and dragging on the track respects the step', () => {
let defaultColor = parseColor('hsl(0, 100%, 50%)');
let {getByRole} = render(<ColorSlider channel="saturation" defaultValue={defaultColor} onChange={onChangeSpy} step={25} />);
let slider = getByRole('slider');
let thumb = slider.parentElement;
let container = getByRole('group');
start(container, {pageX: 30});
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(onChangeSpy.mock.calls[0][0].toString('hsla')).toBe(defaultColor.withChannelValue('saturation', 25).toString('hsla'));
move(thumb, {pageX: 50});
expect(onChangeSpy).toHaveBeenCalledTimes(2);
expect(onChangeSpy.mock.calls[1][0].toString('hsla')).toBe(defaultColor.withChannelValue('saturation', 50).toString('hsla'));
end(thumb, {pageX: 50});
expect(onChangeSpy).toHaveBeenCalledTimes(2);
});
});
}); | the_stack |
import {Mutable, FromAny} from "@swim/util";
import {Affinity, FastenerOwner, FastenerFlags, AnimatorInit, AnimatorClass, Animator} from "@swim/component";
import {ConstraintId} from "./ConstraintId";
import {ConstraintMap} from "./ConstraintMap";
import {AnyConstraintExpression, ConstraintExpression} from "./ConstraintExpression";
import type {ConstraintTerm} from "./ConstraintTerm";
import type {ConstraintVariable} from "./ConstraintVariable";
import {AnyConstraintStrength, ConstraintStrength} from "./"; // forward import
import type {Constraint} from "./Constraint";
import {ConstraintScope} from "./"; // forward import
import type {ConstraintSolver} from "./ConstraintSolver";
/** @public */
export interface ConstraintAnimatorInit<T = unknown, U = T> extends AnimatorInit<T, U> {
extends?: {prototype: ConstraintAnimator<any, any>} | string | boolean | null;
constrain?: boolean;
strength?: AnyConstraintStrength;
willStartConstraining?(): void;
didStartConstraining?(): void;
willStopConstraining?(): void;
didStopConstraining?(): void;
toNumber?(value: T): number;
}
/** @public */
export type ConstraintAnimatorDescriptor<O = unknown, T = unknown, U = T, I = {}> = ThisType<ConstraintAnimator<O, T, U> & I> & ConstraintAnimatorInit<T, U> & Partial<I>;
/** @public */
export interface ConstraintAnimatorClass<A extends ConstraintAnimator<any, any> = ConstraintAnimator<any, any>> extends AnimatorClass<A> {
/** @internal */
readonly ConstrainedFlag: FastenerFlags;
/** @internal */
readonly ConstrainingFlag: FastenerFlags;
/** @internal @override */
readonly FlagShift: number;
/** @internal @override */
readonly FlagMask: FastenerFlags;
}
/** @public */
export interface ConstraintAnimatorFactory<A extends ConstraintAnimator<any, any> = ConstraintAnimator<any, any>> extends ConstraintAnimatorClass<A> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): ConstraintAnimatorFactory<A> & I;
specialize(type: unknown): ConstraintAnimatorFactory | null;
define<O, T, U = T>(className: string, descriptor: ConstraintAnimatorDescriptor<O, T, U>): ConstraintAnimatorFactory<ConstraintAnimator<any, T, U>>;
define<O, T, U = T, I = {}>(className: string, descriptor: {implements: unknown} & ConstraintAnimatorDescriptor<O, T, U, I>): ConstraintAnimatorFactory<ConstraintAnimator<any, T, U> & I>;
<O, T extends number | undefined = number | undefined, U extends number | string | undefined = number | string | undefined>(descriptor: {type: typeof Number} & ConstraintAnimatorDescriptor<O, T, U>): PropertyDecorator;
<O, T, U = T>(descriptor: ({type: FromAny<T, U>} | {fromAny(value: T | U): T}) & ConstraintAnimatorDescriptor<O, T, U>): PropertyDecorator;
<O, T, U = T>(descriptor: ConstraintAnimatorDescriptor<O, T, U>): PropertyDecorator;
<O, T, U = T, I = {}>(descriptor: {implements: unknown} & ConstraintAnimatorDescriptor<O, T, U, I>): PropertyDecorator;
}
/** @public */
export interface ConstraintAnimator<O = unknown, T = unknown, U = T> extends Animator<O, T, U>, ConstraintVariable {
/** @internal @override */
readonly id: number;
/** @internal @override */
isExternal(): boolean;
/** @internal @override */
isDummy(): boolean;
/** @internal @override */
isInvalid(): boolean;
/** @override */
isConstant(): boolean;
/** @internal @override */
evaluateConstraintVariable(): void;
/** @internal @override */
updateConstraintSolution(value: number): void;
/** @override */
readonly strength: ConstraintStrength;
setStrength(strength: AnyConstraintStrength): void;
/** @override */
get coefficient(): number;
/** @override */
get variable(): ConstraintVariable | null;
/** @override */
get terms(): ConstraintMap<ConstraintVariable, number>;
/** @override */
get constant(): number;
/** @override */
plus(that: AnyConstraintExpression): ConstraintExpression;
/** @override */
negative(): ConstraintTerm;
/** @override */
minus(that: AnyConstraintExpression): ConstraintExpression;
/** @override */
times(scalar: number): ConstraintExpression;
/** @override */
divide(scalar: number): ConstraintExpression;
get constrained(): boolean;
constrain(constrained?: boolean): this;
/** @internal */
readonly conditionCount: number;
/** @internal @override */
addConstraintCondition(constraint: Constraint, solver: ConstraintSolver): void;
/** @internal @override */
removeConstraintCondition(constraint: Constraint, solver: ConstraintSolver): void;
/** @internal */
get constraining(): boolean;
/** @internal */
startConstraining(): void;
/** @protected */
willStartConstraining(): void;
/** @protected */
onStartConstraining(): void;
/** @protected */
didStartConstraining(): void;
/** @internal */
stopConstraining(): void;
/** @protected */
willStopConstraining(): void;
/** @protected */
onStopConstraining(): void;
/** @protected */
didStopConstraining(): void;
/** @internal */
updateConstraintVariable(): void;
/** @protected @override */
onSetValue(newValue: T, oldValue: T): void;
/** @protected @override */
onMount(): void;
/** @protected @override */
onUnmount(): void;
/** @override */
fromAny(value: T | U): T;
/** @internal @protected */
toNumber(value: T): number;
}
/** @public */
export const ConstraintAnimator = (function (_super: typeof Animator) {
const ConstraintAnimator: ConstraintAnimatorFactory = _super.extend("ConstraintAnimator");
ConstraintAnimator.prototype.isExternal = function (this: ConstraintAnimator): boolean {
return true;
};
ConstraintAnimator.prototype.isDummy = function (this: ConstraintAnimator): boolean {
return false;
};
ConstraintAnimator.prototype.isInvalid = function (this: ConstraintAnimator): boolean {
return false;
};
ConstraintAnimator.prototype.isConstant = function (this: ConstraintAnimator): boolean {
return false;
};
ConstraintAnimator.prototype.evaluateConstraintVariable = function <T>(this: ConstraintAnimator<unknown, T>): void {
// hook
};
ConstraintAnimator.prototype.updateConstraintSolution = function <T>(this: ConstraintAnimator<unknown, T>, state: number): void {
if (this.constrained && this.toNumber(this.state) !== state) {
this.setState(state as unknown as T, Affinity.Reflexive);
}
};
ConstraintAnimator.prototype.setStrength = function (this: ConstraintAnimator, strength: AnyConstraintStrength): void {
(this as Mutable<typeof this>).strength = ConstraintStrength.fromAny(strength);
};
Object.defineProperty(ConstraintAnimator.prototype, "coefficient", {
get(this: ConstraintAnimator): number {
return 1;
},
configurable: true,
});
Object.defineProperty(ConstraintAnimator.prototype, "variable", {
get(this: ConstraintAnimator): ConstraintVariable {
return this;
},
configurable: true,
});
Object.defineProperty(ConstraintAnimator.prototype, "terms", {
get(this: ConstraintAnimator): ConstraintMap<ConstraintVariable, number> {
const terms = new ConstraintMap<ConstraintVariable, number>();
terms.set(this, 1);
return terms;
},
configurable: true,
});
Object.defineProperty(ConstraintAnimator.prototype, "constant", {
get(this: ConstraintAnimator): number {
return 0;
},
configurable: true,
});
ConstraintAnimator.prototype.plus = function (this: ConstraintAnimator, that: AnyConstraintExpression): ConstraintExpression {
that = ConstraintExpression.fromAny(that);
if (this === that) {
return ConstraintExpression.product(2, this);
} else {
return ConstraintExpression.sum(this, that);
}
};
ConstraintAnimator.prototype.negative = function (this: ConstraintAnimator): ConstraintTerm {
return ConstraintExpression.product(-1, this);
};
ConstraintAnimator.prototype.minus = function (this: ConstraintAnimator, that: AnyConstraintExpression): ConstraintExpression {
that = ConstraintExpression.fromAny(that);
if (this === that) {
return ConstraintExpression.zero;
} else {
return ConstraintExpression.sum(this, that.negative());
}
};
ConstraintAnimator.prototype.times = function (this: ConstraintAnimator, scalar: number): ConstraintExpression {
return ConstraintExpression.product(scalar, this);
};
ConstraintAnimator.prototype.divide = function (this: ConstraintAnimator, scalar: number): ConstraintExpression {
return ConstraintExpression.product(1 / scalar, this);
};
Object.defineProperty(ConstraintAnimator.prototype, "constrained", {
get(this: ConstraintAnimator): boolean {
return (this.flags & ConstraintAnimator.ConstrainedFlag) !== 0;
},
configurable: true,
});
ConstraintAnimator.prototype.constrain = function (this: ConstraintAnimator<unknown, unknown, unknown>, constrained?: boolean): typeof this {
if (constrained === void 0) {
constrained = true;
}
const flags = this.flags;
if (constrained && (flags & ConstraintAnimator.ConstrainedFlag) === 0) {
this.setFlags(flags | ConstraintAnimator.ConstrainedFlag);
if (this.conditionCount !== 0 && this.mounted) {
this.stopConstraining();
}
} else if (!constrained && (flags & ConstraintAnimator.ConstrainedFlag) !== 0) {
this.setFlags(flags & ~ConstraintAnimator.ConstrainedFlag);
if (this.conditionCount !== 0 && this.mounted) {
this.startConstraining();
this.updateConstraintVariable();
}
}
return this;
};
ConstraintAnimator.prototype.addConstraintCondition = function (this: ConstraintAnimator, constraint: Constraint, solver: ConstraintSolver): void {
(this as Mutable<typeof this>).conditionCount += 1;
if (!this.constrained && this.conditionCount === 1 && this.mounted) {
this.startConstraining();
this.updateConstraintVariable();
}
};
ConstraintAnimator.prototype.removeConstraintCondition = function (this: ConstraintAnimator, constraint: Constraint, solver: ConstraintSolver): void {
(this as Mutable<typeof this>).conditionCount -= 1;
if (!this.constrained && this.conditionCount === 0 && this.mounted) {
this.stopConstraining();
}
};
Object.defineProperty(ConstraintAnimator.prototype, "constraining", {
get(this: ConstraintAnimator): boolean {
return (this.flags & ConstraintAnimator.ConstrainingFlag) !== 0;
},
configurable: true,
});
ConstraintAnimator.prototype.startConstraining = function (this: ConstraintAnimator): void {
if ((this.flags & ConstraintAnimator.ConstrainingFlag) === 0) {
this.willStartConstraining();
this.setFlags(this.flags | ConstraintAnimator.ConstrainingFlag);
this.onStartConstraining();
this.didStartConstraining();
}
};
ConstraintAnimator.prototype.willStartConstraining = function (this: ConstraintAnimator): void {
// hook
};
ConstraintAnimator.prototype.onStartConstraining = function (this: ConstraintAnimator): void {
const constraintScope = this.owner;
if (ConstraintScope.is(constraintScope)) {
constraintScope.addConstraintVariable(this);
}
};
ConstraintAnimator.prototype.didStartConstraining = function (this: ConstraintAnimator): void {
// hook
};
ConstraintAnimator.prototype.stopConstraining = function (this: ConstraintAnimator): void {
if ((this.flags & ConstraintAnimator.ConstrainingFlag) !== 0) {
this.willStopConstraining();
this.setFlags(this.flags & ~ConstraintAnimator.ConstrainingFlag);
this.onStopConstraining();
this.didStopConstraining();
}
};
ConstraintAnimator.prototype.willStopConstraining = function (this: ConstraintAnimator): void {
// hook
};
ConstraintAnimator.prototype.onStopConstraining = function (this: ConstraintAnimator): void {
const constraintScope = this.owner;
if (ConstraintScope.is(constraintScope)) {
constraintScope.removeConstraintVariable(this);
}
};
ConstraintAnimator.prototype.didStopConstraining = function (this: ConstraintAnimator): void {
// hook
};
ConstraintAnimator.prototype.updateConstraintVariable = function (this: ConstraintAnimator): void {
const constraintScope = this.owner;
const value = this.value;
if (value !== void 0 && ConstraintScope.is(constraintScope)) {
constraintScope.setConstraintVariable(this, this.toNumber(value));
}
};
ConstraintAnimator.prototype.onSetValue = function <T>(this: ConstraintAnimator<unknown, T>, newValue: T, oldValue: T): void {
_super.prototype.onSetValue.call(this, newValue, oldValue);
const constraintScope = this.owner;
if (this.constraining && ConstraintScope.is(constraintScope)) {
constraintScope.setConstraintVariable(this, newValue !== void 0 && newValue !== null ? this.toNumber(newValue) : 0);
}
};
ConstraintAnimator.prototype.onMount = function <T>(this: ConstraintAnimator<unknown, T>): void {
_super.prototype.onMount.call(this);
if (!this.constrained && this.conditionCount !== 0) {
this.startConstraining();
}
};
ConstraintAnimator.prototype.onUnmount = function <T>(this: ConstraintAnimator<unknown, T>): void {
if (!this.constrained && this.conditionCount !== 0) {
this.stopConstraining();
}
_super.prototype.onUnmount.call(this);
};
ConstraintAnimator.prototype.fromAny = function <T, U>(this: ConstraintAnimator<unknown, T, U>, value: T | U): T {
if (typeof value === "string") {
const number = +value;
if (isFinite(number)) {
return number as unknown as T;
}
}
return value as T;
};
ConstraintAnimator.prototype.toNumber = function <T>(this: ConstraintAnimator<unknown, T>, value: T): number {
return value !== void 0 && value !== null ? +value : 0;
};
ConstraintAnimator.construct = function <A extends ConstraintAnimator<any, any>>(animatorClass: {prototype: A}, animator: A | null, owner: FastenerOwner<A>): A {
animator = _super.construct(animatorClass, animator, owner) as A;
(animator as Mutable<typeof animator>).id = ConstraintId.next();
(animator as Mutable<typeof animator>).strength = ConstraintStrength.Strong;
(animator as Mutable<typeof animator>).conditionCount = 0;
return animator;
};
ConstraintAnimator.specialize = function (type: unknown): ConstraintAnimatorFactory | null {
return null;
};
ConstraintAnimator.define = function <O, T, U>(className: string, descriptor: ConstraintAnimatorDescriptor<O, T, U>): ConstraintAnimatorFactory<ConstraintAnimator<any, T, U>> {
let superClass = descriptor.extends as ConstraintAnimatorFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
const strength = descriptor.strength !== void 0 ? ConstraintStrength.fromAny(descriptor.strength) : void 0;
const constrain = descriptor.constrain;
const value = descriptor.value;
const initValue = descriptor.initValue;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
delete descriptor.strength;
delete descriptor.constrain;
delete descriptor.value;
delete descriptor.initValue;
if (superClass === void 0 || superClass === null) {
superClass = this.specialize(descriptor.type);
}
if (superClass === null) {
superClass = this;
if (descriptor.fromAny === void 0 && FromAny.is<T, U>(descriptor.type)) {
descriptor.fromAny = descriptor.type.fromAny;
}
}
const animatorClass = superClass.extend(className, descriptor);
animatorClass.construct = function (animatorClass: {prototype: ConstraintAnimator<any, any>}, animator: ConstraintAnimator<O, T, U> | null, owner: O): ConstraintAnimator<O, T, U> {
animator = superClass!.construct(animatorClass, animator, owner);
if (affinity !== void 0) {
animator.initAffinity(affinity);
}
if (inherits !== void 0) {
animator.initInherits(inherits);
}
if (strength !== void 0) {
(animator as Mutable<typeof animator>).strength = strength;
}
if (initValue !== void 0) {
(animator as Mutable<typeof animator>).value = animator.fromAny(initValue());
(animator as Mutable<typeof animator>).state = animator.value;
} else if (value !== void 0) {
(animator as Mutable<typeof animator>).value = animator.fromAny(value);
(animator as Mutable<typeof animator>).state = animator.value;
}
if (constrain === true) {
animator.constrain();
}
return animator;
};
return animatorClass;
};
(ConstraintAnimator as Mutable<typeof ConstraintAnimator>).ConstrainedFlag = 1 << (_super.FlagShift + 0);
(ConstraintAnimator as Mutable<typeof ConstraintAnimator>).ConstrainingFlag = 1 << (_super.FlagShift + 1);
(ConstraintAnimator as Mutable<typeof ConstraintAnimator>).FlagShift = _super.FlagShift + 2;
(ConstraintAnimator as Mutable<typeof ConstraintAnimator>).FlagMask = (1 << ConstraintAnimator.FlagShift) - 1;
return ConstraintAnimator;
})(Animator); | the_stack |
import { ConnectionType } from './types';
/**
* The name of the place based on the locales list passed to the
* `WebServiceClient` constructor. Don't use any of these names as a database or
* dictionary key. Use the ID or relevant code instead.
*/
export interface Names {
readonly de?: string;
readonly en: string;
readonly es?: string;
readonly fr?: string;
readonly ja?: string;
readonly 'pt-BR'?: string;
readonly ru?: string;
readonly 'zh-CN'?: string;
}
/**
* Contains data related to your MaxMind account.
*/
export interface MaxMindRecord {
/**
* The number of remaining queries in your account for the web service end
* point. This will be null when using a local database.
*/
queriesRemaining: number;
}
/**
* City-level data associated with an IP address.
*/
export interface CityRecord {
/**
* A value from 0-100 indicating MaxMind's confidence that the city is
* correct. This value is only set when using the Insights web service or the
* Enterprise database.
*/
readonly confidence?: number;
/**
* The GeoName ID for the city.
*/
readonly geonameId: number;
/**
* An object of locale codes to the name in that locale. Don't use any of
* these names as a database or dictionary key. Use the ID or relevant code
* instead.
*/
readonly names: Names;
}
/**
* Contains data for the continent record associated with an IP address. Do not
* use any of the continent names as a database or dictionary key. Use the ID or
* relevant code instead.
*/
export interface ContinentRecord {
/**
* A two character continent code like "NA" (North America) or "OC" (Oceania).
*/
readonly code: 'AF' | 'AN' | 'AS' | 'EU' | 'NA' | 'OC' | 'SA';
/**
* The GeoName ID for the continent.
*/
readonly geonameId: number;
/**
* An object of locale codes to the name in that locale. Don't use any of
* these names as a database or dictionary key. Use the ID or relevant code
* instead.
*/
readonly names: Names;
}
/**
* Contains data for the registered country record associated with an IP address. Do not
* use any of the country names as a database or dictionary key. Use the ID or
* relevant code instead.
*/
export interface RegisteredCountryRecord {
/**
* The GeoName ID for the country.
*/
readonly geonameId: number;
/**
* This is true if the country is a member state of the European Union. This is available from all location services and databases.
*/
readonly isInEuropeanUnion?: boolean;
/**
* The two-character ISO 3166-1 alpha code for the country.
*/
readonly isoCode: string;
/**
* An object of locale codes to the name in that locale. Don't use any of
* these names as a database or dictionary key. Use the ID or relevant code
* instead.
*/
readonly names: Names;
}
/**
* Contains data for the country record associated with an IP address. Do not
* use any of the country names as a database or dictionary key. Use the ID or
* relevant code instead.
*/
export interface CountryRecord extends RegisteredCountryRecord {
/**
* A value from 0-100 indicating MaxMind's confidence that the country is
* correct. This value is only set when using the Insights web service or the
* Enterprise database.
*/
readonly confidence?: number;
}
/**
* Contains data for the location record associated with an IP address.
*/
export interface LocationRecord {
/**
* The approximate accuracy radius in kilometers around the latitude and
* longitude for the IP address. This is the radius where we have a 67%
* confidence that the device using the IP address resides within the circle
* centered at the latitude and longitude with the provided radius.
*/
readonly accuracyRadius: number;
/**
* The average income in US dollars associated with the IP address.
*/
readonly averageIncome?: number;
/**
* The approximate latitude of the location associated with the IP address.
* This value is not precise and should not be used to identify a particular
* address or household.
*/
readonly latitude: number;
/**
* The approximate longitude of the location associated with the IP address.
* This value is not precise and should not be used to identify a particular
* address or household.
*/
readonly longitude: number;
/**
* The metro code of the location if the location is in the US. MaxMind
* returns the same metro codes as the Google AdWords API.
*/
readonly metroCode?: number;
/**
* The estimated number of people per square kilometer.
*/
readonly populationDensity?: number;
/**
* The time zone associated with location, as specified by the IANA Time Zone
* Database , e.g., "America/New_York".
*/
readonly timeZone?: string;
}
/**
* Contains data for the postal record associated with an IP address.
*/
export interface PostalRecord {
/**
* The postal code of the location. Postal codes are not available for all
* countries. In some countries, this will only contain part of the postal
* code.
*/
readonly code: string;
/**
* A value from 0-100 indicating MaxMind's confidence that the postal code is
* correct. This value is only set when using the Insights web service or the
* Enterprise database.
*/
readonly confidence?: number;
}
/**
* Contains data for the represented country associated with an IP address.
* This class contains the country-level data associated with an IP address for
* the IP's represented country. The represented country is the country
* represented by something like a military base. Do not use any of the country
* names as a database or dictionary key. Use the ID or relevant instead.
*/
export interface RepresentedCountryRecord extends RegisteredCountryRecord {
/**
* A string indicating the type of entity that is representing the country.
* Currently we only return military but this could expand to include other
* types in the future.
*/
readonly type: string;
}
/**
* Contains data for the subdivisions associated with an IP address. Do not use
* any of the subdivision names as a database or dictionary key. Use the ID or
* relevant instead.
*/
export interface SubdivisionsRecord {
/**
* This is a value from 0-100 indicating MaxMind's confidence that the
* subdivision is correct. This value is only set when using the Insights web
* service or the Enterprise database.
*/
readonly confidence?: number;
/**
* The GeoName ID for the subdivision.
*/
readonly geonameId: number;
/**
* This is a string up to three characters long contain the subdivision portion of the code.
*/
readonly isoCode: string;
/**
* An object of locale codes to the name in that locale. Don't use any of
* these names as a database or dictionary key. Use the ID or relevant code
* instead.
*/
readonly names: Names;
}
/**
* Contains data for the traits record associated with an IP address.
*/
export interface TraitsRecord {
/**
* The autonomous system number associated with the IP address. This value is
* only set when using the City or Insights web service or the Enterprise
* database.
*/
readonly autonomousSystemNumber?: number;
/**
* The organization associated with the registered autonomous system number
* for the IP address. This value is only set when using the City or Insights
* web service or the Enterprise database.
*/
readonly autonomousSystemOrganization?: string;
/**
* The connection type may take the following values:
* "Dialup", "Cable/DSL", "Corporate", "Cellular".
* Additional values may be added in the future.
*/
readonly connectionType?: ConnectionType;
/**
* The second level domain associated with the IP address. This will be
* something like "example.com" or "example.co.uk", not "foo.example.com".
* This value is only set when using the City or Insights web service or the
* Enterprise database.
*/
readonly domain?: string;
/**
* The IP address that the data in the model is for. If you performed a "me"
* lookup against the web service, this will be the externally routable IP
* address for the system the code is running on. If the system is behind a
* NAT, this may differ from the IP address locally assigned to it.
*/
ipAddress?: string;
/**
* This is true if the IP address belongs to any sort of anonymous network.
* This value is only available from GeoIP2 Precision Insights.
*/
readonly isAnonymous?: boolean;
/**
* This is true if the IP is an anonymous proxy. See MaxMind's GeoIP FAQ
* @category deprecated
* @deprecated
*/
readonly isAnonymousProxy?: boolean;
/**
* This is true if the IP address is registered to an anonymous VPN provider.
* This value is only available from GeoIP2 Precision Insights.
*/
readonly isAnonymousVpn?: boolean;
/**
* This is true if the IP address belongs to a hosting or VPN provider (see
* description of `IsAnonymousVpn` property). This value is only available from
* GeoIP2 Precision Insights.
*/
readonly isHostingProvider?: boolean;
/**
* True if MaxMind believes this IP address to be a legitimate proxy, such as
* an internal VPN used by a corporation. This is only available in the
* GeoIP2 Enterprise database.
*/
readonly isLegitimateProxy?: boolean;
/**
* This is true if the IP address belongs to a public proxy. This value is
* only available from GeoIP2 Precision Insights.
*/
readonly isPublicProxy?: boolean;
/**
* This is true if the IP address is on a suspected anonymizing network and
* belongs to a residential ISP. This value is only available from GeoIP2
* Precision Insights.
*/
readonly isResidentialProxy?: boolean;
/**
* This is true if the IP belong to a satellite Internet provider.
* @category deprecated
* @deprecated
*/
readonly isSatelliteProvider?: boolean;
/**
* This is true if the IP address belongs to a Tor exit node. This value is
* only available from GeoIP2 Precision Insights.
*/
readonly isTorExitNode?: boolean;
/**
* The network associated with the record. In particular, this is the largest
* network where all of the fields besides `ipAddress` have the same value.
*/
network?: string;
/**
* The name of the ISP associated with the IP address. This value is only set
* when using the City or Insights web service or the Enterprise database.
*/
readonly isp?: string;
/**
* The name of the organization associated with the IP address. This value is
* only set when using the City or Insights web service or the Enterprise
* database.
*/
readonly organization?: string;
/**
* An indicator of how static or dynamic an IP address is. The value ranges
* from 0 to 99.99 with higher values meaning a greater static association.
* For example, many IP addresses with a `userType` of `cellular` have a lifetime
* under one. Static Cable/DSL IPs typically have a lifetime above thirty.
*/
readonly staticIpScore?: number;
/**
* The estimated number of users sharing the IP/network during the past 24
* hours. For IPv4, the count is for the individual IP. For IPv6, the count
* is for the /64 network. This value is only available from GeoIP2 Precision
* Insights.
*/
readonly userCount?: number;
/**
* The user type associated with the IP address. This value is only set when
* using the City or Insights web service or the Enterprise database.
*/
readonly userType?:
| 'business'
| 'cafe'
| 'cellular'
| 'college'
| 'content_delivery_network'
| 'dialup'
| 'government'
| 'hosting'
| 'library'
| 'military'
| 'residential'
| 'router'
| 'school'
| 'search_engine_spider'
| 'traveler';
} | the_stack |
import * as React from "react";
import {
css,
keyframes,
injectGlobal,
isStyledComponent,
consolidateStreamedStyles,
ThemeProvider,
withTheme,
ServerStyleSheet,
StyleSheetManager,
ThemedStyledFunction,
StyledComponentClass,
} from "styled-components";
// #region xhtmltypes
export interface XHTMLElements {
a: React.DetailedHTMLProps<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
HTMLAnchorElement
>;
abbr: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
acronym: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
address: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
applet: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
area: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLAreaElement>,
HTMLAreaElement
>;
b: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
base: React.DetailedHTMLProps<
React.BaseHTMLAttributes<HTMLBaseElement>,
HTMLBaseElement
>;
basefont: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
bdo: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
big: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
blockquote: React.DetailedHTMLProps<
React.BlockquoteHTMLAttributes<HTMLElement>,
HTMLElement
>;
body: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLBodyElement>,
HTMLBodyElement
>;
br: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLBRElement>,
HTMLBRElement
>;
button: React.DetailedHTMLProps<
React.ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement
>;
caption: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
center: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
cite: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
code: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
col: React.DetailedHTMLProps<
React.ColHTMLAttributes<HTMLTableColElement>,
HTMLTableColElement
>;
colgroup: React.DetailedHTMLProps<
React.ColgroupHTMLAttributes<HTMLTableColElement>,
HTMLTableColElement
>;
dd: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
del: React.DetailedHTMLProps<
React.DelHTMLAttributes<HTMLElement>,
HTMLElement
>;
dfn: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
dir: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
div: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLDivElement>,
HTMLDivElement
>;
dl: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLDListElement>,
HTMLDListElement
>;
dt: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
em: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
fieldset: React.DetailedHTMLProps<
React.FieldsetHTMLAttributes<HTMLFieldSetElement>,
HTMLFieldSetElement
>;
font: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLFontElement>,
HTMLFontElement
>;
form: React.DetailedHTMLProps<
React.FormHTMLAttributes<HTMLFormElement>,
HTMLFormElement
>;
h1: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>;
h2: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>;
h3: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>;
h4: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>;
h5: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>;
h6: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>;
head: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLHeadElement>,
HTMLHeadElement
>;
hr: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLHRElement>,
HTMLHRElement
>;
html: React.DetailedHTMLProps<
React.HtmlHTMLAttributes<HTMLHtmlElement>,
HTMLHtmlElement
>;
i: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
iframe: React.DetailedHTMLProps<
React.IframeHTMLAttributes<HTMLIFrameElement>,
HTMLIFrameElement
>;
img: React.DetailedHTMLProps<
React.ImgHTMLAttributes<HTMLImageElement>,
HTMLImageElement
>;
input: React.DetailedHTMLProps<
React.InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>;
ins: React.DetailedHTMLProps<
React.InsHTMLAttributes<HTMLModElement>,
HTMLModElement
>;
isindex: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
kbd: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
label: React.DetailedHTMLProps<
React.LabelHTMLAttributes<HTMLLabelElement>,
HTMLLabelElement
>;
legend: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLLegendElement>,
HTMLLegendElement
>;
li: React.DetailedHTMLProps<
React.LiHTMLAttributes<HTMLLIElement>,
HTMLLIElement
>;
link: React.DetailedHTMLProps<
React.LinkHTMLAttributes<HTMLLinkElement>,
HTMLLinkElement
>;
map: React.DetailedHTMLProps<
React.MapHTMLAttributes<HTMLMapElement>,
HTMLMapElement
>;
menu: React.DetailedHTMLProps<
React.MenuHTMLAttributes<HTMLElement>,
HTMLElement
>;
meta: React.DetailedHTMLProps<
React.MetaHTMLAttributes<HTMLMetaElement>,
HTMLMetaElement
>;
noframes: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
noscript: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
object: React.DetailedHTMLProps<
React.ObjectHTMLAttributes<HTMLObjectElement>,
HTMLObjectElement
>;
ol: React.DetailedHTMLProps<
React.OlHTMLAttributes<HTMLOListElement>,
HTMLOListElement
>;
optgroup: React.DetailedHTMLProps<
React.OptgroupHTMLAttributes<HTMLOptGroupElement>,
HTMLOptGroupElement
>;
option: React.DetailedHTMLProps<
React.OptionHTMLAttributes<HTMLOptionElement>,
HTMLOptionElement
>;
p: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLParagraphElement>,
HTMLParagraphElement
>;
param: React.DetailedHTMLProps<
React.ParamHTMLAttributes<HTMLParamElement>,
HTMLParamElement
>;
pre: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLPreElement>,
HTMLPreElement
>;
q: React.DetailedHTMLProps<
React.QuoteHTMLAttributes<HTMLQuoteElement>,
HTMLQuoteElement
>;
s: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
samp: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
script: React.DetailedHTMLProps<
React.ScriptHTMLAttributes<HTMLScriptElement>,
HTMLScriptElement
>;
select: React.DetailedHTMLProps<
React.SelectHTMLAttributes<HTMLSelectElement>,
HTMLSelectElement
>;
small: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
span: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLSpanElement>,
HTMLSpanElement
>;
strike: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
strong: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
style: React.DetailedHTMLProps<
React.StyleHTMLAttributes<HTMLStyleElement>,
HTMLStyleElement
>;
sub: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
sup: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
table: React.DetailedHTMLProps<
React.TableHTMLAttributes<HTMLTableElement>,
HTMLTableElement
>;
tbody: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLTableSectionElement>,
HTMLTableSectionElement
>;
td: React.DetailedHTMLProps<
React.TdHTMLAttributes<HTMLTableDataCellElement>,
HTMLTableDataCellElement
>;
textarea: React.DetailedHTMLProps<
React.TextareaHTMLAttributes<HTMLTextAreaElement>,
HTMLTextAreaElement
>;
tfoot: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLTableSectionElement>,
HTMLTableSectionElement
>;
th: React.DetailedHTMLProps<
React.ThHTMLAttributes<HTMLTableHeaderCellElement>,
HTMLTableHeaderCellElement
>;
thead: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLTableSectionElement>,
HTMLTableSectionElement
>;
title: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLTitleElement>,
HTMLTitleElement
>;
tr: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLTableRowElement>,
HTMLTableRowElement
>;
tt: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
u: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
ul: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLUListElement>,
HTMLUListElement
>;
var: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
}
// #endregion
// #region vmlelements
export type VMLAttrs = { [attr: string]: any };
export interface VMLElements {
shape: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
shapetype: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
group: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
background: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
path: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
formulas: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
handles: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
fill: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
stroke: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
shadow: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
textbox: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
textpath: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
imagedata: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
line: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
polyline: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
curve: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
roundrect: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
oval: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
arc: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
image: React.DetailedHTMLProps<VMLAttrs, HTMLElement>;
}
// #endregion
// Helpers, copied from styled-components.d.ts
type KeyofBase = keyof any;
type Diff<T extends KeyofBase, U extends KeyofBase> = ({ [P in T]: P } &
{ [P in U]: never })[T];
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>;
type WithOptionalTheme<P extends { theme?: T }, T> = Omit<P, "theme"> & {
theme?: T;
};
// Re-define all types with XHTML elements
type ThemedStyledComponentFactories<T> = {
[TTag in keyof XHTMLElements]: ThemedStyledFunction<XHTMLElements[TTag], T>;
};
export interface ThemedBaseStyledInterface<T>
extends ThemedStyledComponentFactories<T> {
<P, TTag extends keyof XHTMLElements>(tag: TTag): ThemedStyledFunction<
P,
T,
P & XHTMLElements[TTag]
>;
<P, O>(component: StyledComponentClass<P, T, O>): ThemedStyledFunction<
P,
T,
O
>;
<P extends { [prop: string]: any; theme?: T }>(
component: React.ComponentType<P>
): ThemedStyledFunction<P, T, WithOptionalTheme<P, T>>;
}
export type BaseStyledInterface = ThemedBaseStyledInterface<any>;
export type ThemedStyledInterface<T> = ThemedBaseStyledInterface<T>;
// Define vml.*, wml.* and office.* proxy
type AnyAttrs<T> = { [attr: string]: T };
type NamespacedElementFactory<T> = {
[tag: string]: ThemedStyledFunction<
React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement> & AnyAttrs<any>,
HTMLElement
>,
T
>;
};
type VMLNamespaceFactory<T> = {
[TTag in keyof VMLElements]: ThemedStyledFunction<VMLElements[TTag], T>;
};
type WMLNamespaceFactory<T> = {
[tag: string]: ThemedStyledFunction<any, T>;
};
type OfficeNamespaceFactory<T> = {
[tag: string]: ThemedStyledFunction<any, T>;
};
interface NamespacedStyledInterface<T> extends ThemedStyledInterface<T> {
vml: VMLNamespaceFactory<any>;
wml: WMLNamespaceFactory<any>;
office: OfficeNamespaceFactory<any>;
}
// Re-export it
export type StyledInterface = NamespacedStyledInterface<any>;
declare const styled: StyledInterface;
export * from "styled-components";
export default styled; | the_stack |
import * as workerFarm from 'worker-farm';
import { ProcessedPackageConfig, Conditional, serializePackageConfig, PackageTarget } from '../install/package';
import { Logger } from '../project';
import { JspmUserError } from '../utils/common';
import * as fs from 'graceful-fs';
import * as path from 'path';
import { writeJSONStyled, readJSONStyled, defaultStyle } from '../config/config-file';
import { resolveFile, resolveDir, toDew, toDewPlain, pcfgToDeps, isESM } from './dew-resolve';
import { builtins } from '@jspm/resolve';
const nodeBuiltinsTarget = new PackageTarget('npm', '@jspm/core', '^1.0.0');
let convertWorker: any;
let initCnt = 0;
export function init () {
if (initCnt++ === 0) {
convertWorker = workerFarm(<any>{
workerOptions: {
execArgv: process.execArgv.concat(['--max_old_space_size=4096'])
},
maxConcurrentWorkers: Math.max(require('os').cpus().length / 2, 4),
maxConcurrentCallsPerWorker: 1,
autoStart: true
}, require.resolve('./dew-worker'));
}
}
export async function dispose () {
if (--initCnt <= 0) {
initCnt = 0;
await new Promise((resolve, reject) => (<any>workerFarm).end(convertWorker, err => err ? reject(err) : resolve()));
}
}
/*
* Internal map dew handling
*
* - We add custom condition mains as "map": { "./index.dew.js" condition maps }.
* That is, we effectively copy the "main" map entry (copy map[main]) to map[./index.dew.js] with targets rewritten for dew)
* - Internal maps do the same thing - "map": { "./x": "./y" } -> "map": { "./x.dew.js" -> "./y.dew.js" }
* - We still keep the original map, so the folder form still applies
* - External maps also dew - "map": { "x": "y/z" } -> "map": { "x": "y/z", "x/index.dew.js": "y/z.dew.js" }
* plus handling for subpath - "map": { "x/y": "z" } -> "map": { "x/y": "./z", "x/y.dew.js": "./z.dew.js" }
*/
export function convertCJSConfig (pcfg: ProcessedPackageConfig) {
let newMap;
if (pcfg.type === 'module')
return;
if (!pcfg.peerDependencies)
pcfg.peerDependencies = {};
pcfg.peerDependencies['@jspm/core'] = nodeBuiltinsTarget;
if (pcfg.main) {
if (pcfg.map && pcfg.map['./' + pcfg.main]) {
if (!newMap)
newMap = {};
newMap['./' + pcfg.main] = pcfg.map['./' + pcfg.main];
newMap['./' + toDew(pcfg.main)] = newMap['./index.dew.js'] = convertMappingToDew(pcfg.map['./' + pcfg.main], undefined);
}
}
// no main -> create index.js as the default main
else {
pcfg.main = 'index.js';
}
if (pcfg.map) {
const deps = pcfgToDeps(pcfg);
for (const match of Object.keys(pcfg.map)) {
if (!newMap)
newMap = {};
let mapping = pcfg.map[match];
newMap[match] = mapping;
const isRel = match.startsWith('./');
if (isESM(match, deps))
continue;
newMap[isRel ? toDew(match) : toDewPlain(match)] = convertMappingToDew(mapping, !isRel);
}
}
// TODO: bin may need resolution
/*if (pcfg.bin) {
let newBin;
for (const bin of Object.keys(pcfg.bin)) {
if (!newBin)
newBin = {};
const target = pcfg.bin[bin];
newBin[bin] = toDew(target);
}
if (newBin)
pcfg.bin = newBin;
}*/
if (newMap)
pcfg.map = newMap;
}
function convertMappingToDew (mapping: string | Conditional, plain: boolean): string | Conditional {
if (typeof mapping === 'string') {
if (mapping === '@empty')
return '@empty.dew';
return plain ? (builtins[mapping] ? mapping : toDewPlain(mapping)) : toDew(mapping);
}
const newMap = {};
for (const condition of Object.keys(mapping))
newMap[condition] = convertMappingToDew(mapping[condition], plain);
return newMap;
}
/*
* Conversion process:
* - Internal resolutions are resolved, with toDew applied.
*
* External resolutions get toDew applied, with main adding for package matches
* require('x') -> require('x/index.dew.js');
* require('x/y') -> require('x/y.dew.js')
*
* (except for builtins which are ESM)
*
* - All .js files get a .dew and the .js version becomes the ESM wrapper
*
* - All .json files get a ".dew.json", and a ".dew.js" if there is no other resolution at the extensionless
* No entry is created for ".json" files though because ESM cannot import JSON, and the JSON must remain transparent.
*
* - The main entry point of the package is reflected through pkg/index.dew.js
* This handles all forms of main entry point from directory index to JSON files. It is always this file.
*
* - All extension and index files get a corresponding dew made
* x.json -> x.dew.json + x.dew.js
* x/index.js -> x.dew.js + x/index.dew.js
* x.json + x.js -> x.js wins the x.dew.js, x.dew.json still exists, similarly for index lookups winning
* dew aliases are simply: export { dew } from './actual.dew.js';
*
* Extensionless files that are valid JS are overwritten with their ESM entry
*
* - We skip files that are in subfolders of "type": "module" (up to next cancelling subfolder), or files that are in the noModuleConversion array
* Such files will simply break if loaded as entries or dew requires. There might possibly be a way to skip the ".js" entry, but keep the ".dew". Perhaps this goes with entry point lock downs -> "sealed": true kind of thing.
*/
export async function convertCJSPackage (log: Logger, dir: string, pkgName: string, pcfg: ProcessedPackageConfig, defaultRegistry: string) {
log.debug(`Converting CJS package ${pkgName}`);
if (pcfg.noModuleConversion === true)
return;
let filePool = await listAllFiles(dir);
const convertFiles: { [filename: string]: boolean } = Object.create(null);
for (const file of filePool)
convertFiles[file] = false;
// determine which files match the cjs conversion boundary
// since we are loading package.json files, at the same time record folder mains
const folderMains: { [dir: string]: string } = Object.create(null);
for (const pjsonFile of filePool.filter(file => file.endsWith('/package.json')).sort((a, b) => a.split('/').length < b.split('/').length ? 1 : -1)) {
const boundary = pjsonFile.substr(0, pjsonFile.lastIndexOf('/'));
const pjson = await new Promise<string>((resolve, reject) => fs.readFile(path.resolve(dir, pjsonFile), (err, source) => err ? reject(err) : resolve(source.toString())));
try {
const parsed = JSON.parse(pjson);
if (typeof parsed.main === 'string')
folderMains[boundary] = parsed.main.startsWith('./') ? parsed.main.substr(2) : parsed.main;
var type = parsed.type;
}
catch (e) {
continue;
}
// module type scope -> filter out from the file pool
if (type === 'module')
filePool = filePool.filter(file => !file.startsWith(boundary) || file[boundary.length] !== '/');
// cjs mode boundary -> add to the conversion list
else
filePool = filePool.filter(file => {
const filtered = file.startsWith(boundary) && file[boundary.length] === '/';
if (filtered)
convertFiles[file] = true;
return !filtered;
});
}
if (pcfg.type !== 'module')
for (const file of filePool)
convertFiles[file] = true;
// populate index.js, index.json as folder mains
for (const file of Object.keys(convertFiles)) {
if (file.endsWith('/index.js') || file.endsWith('/index.json') || file.endsWith('/index.node')) {
const folderName = file.substr(0, file.lastIndexOf('/'));
if (!folderMains[folderName])
folderMains[folderName] = file.substr(folderName.length + 1);
}
}
let main;
if (pcfg.main)
main = resolveFile(pcfg.main, convertFiles) || resolveDir(pcfg.main, convertFiles, folderMains);
else
main = resolveDir('index', convertFiles, folderMains);
// dont convert the noModuleConversion files
const skipFiles = <string[]>pcfg.noModuleConversion;
if (skipFiles)
Object.keys(convertFiles).forEach(file => {
if (skipFiles.some(skipFile =>
file.startsWith(skipFile) && (file.length === skipFile.length || file[skipFile.length] === '/' || file[skipFile.length - 1] === '/')
))
convertFiles[file] = false;
});
// we are now left with just those files that need .dew.js conversion
// the worker will also write over the original file with the ESM wrapper
log.debug(`Sending conversion manifest to process worker for ${pkgName}...`);
await new Promise<string[]>((resolve, reject) => {
convertWorker(pcfg.name, dir, convertFiles, main, folderMains, pcfg.namedExports, getLocalMaps(pcfg), pcfgToDeps(pcfg, true), (err, convertedFiles) => {
if (err)
reject(new JspmUserError(`Error converting ${pkgName}${err.filename ? ` file ${err.filename}` : ''}. This package may not load correctly in jspm. Please post a bug!\n${err.stack || err.toString()}`, 'ESM_CONVERSION_ERROR'));
else
resolve(convertedFiles);
});
});
/*
* Dew Aliasing cases:
* These are for require('x/y') cases that are resolved to x/y.dew.js that in turn needs to alias the exact resolution
*
* - x.dew.js -> x.json.dew.js if x.js or x doesn't already have a dew
* - for each folder with a package.json, where the folder.js does not exists, we determine if that folder has a main
* and if so, we create the folder.dew.js file
* - index.dew.js is created pointing to the file corresponding to the actual main
*
* All aliases are simply of the form:
* export { dew } from './alias.of.dew.js'
* since they are aliases of existing dew files only
*
* Note that we don't need to create a x.js.dew.js file for each extension and non-extension variation
* because of the fact that we automatically assume the js extension for requires from other packages
* this has the potential to conflict x and x.js, but the cases is deemed rare enough to be worth the simplification
*
* We don't worry about aliases of ESM imports, because:
* - JSON imports are not supported from ESM
* - the file.js file is the ESM wrapper
* - other default behaviours are not provided by ESM
* - map is supported fine with just the above
*/
const aliasPromises = [];
function writeDewAlias (filePath: string, dewName: string) {
aliasPromises.push(new Promise((resolve, reject) =>
fs.writeFile(path.resolve(dir, filePath), `export { dew } from './${dewName}';\n`, err => err ? reject(err) : resolve())
).catch(() => {}));
}
function writeNodeAlias (filePath: string, nodeName: string) {
aliasPromises.push(new Promise((resolve, reject) =>
fs.writeFile(path.resolve(dir, filePath), `import m from './${nodeName}';\nexport function dew () { return m; }`, err => err ? reject(err) : resolve())
).catch(() => {}));
}
function writeJsAlias (filePath: string, jsName: string, hasDefault: boolean, hasNames: boolean) {
let aliasSource = '';
if (!hasDefault && !hasNames) {
aliasSource += `import './${jsName}';\n`;
}
else {
if (hasDefault) aliasSource += `export { default } from './${jsName}';\n`;
if (hasNames) aliasSource += `export * from './${jsName}';\n`;
}
aliasPromises.push(new Promise((resolve, reject) =>
fs.writeFile(path.resolve(dir, filePath), aliasSource, err => err ? reject(err) : resolve())
).catch(() => {}));
}
// json dew aliases (.dew.js -> .json.dew.js)
for (const file of Object.keys(convertFiles).filter(file => file.endsWith('.json') && convertFiles[file] === true)) {
if (!Object.hasOwnProperty.call(convertFiles, file.substr(0, file.length - 5)) && !(file.substr(0, file.length - 5) + '.js' in convertFiles))
writeDewAlias(file.substr(0, file.length - 5) + '.dew.js', file.slice(file.lastIndexOf('/') + 1) + '.dew.js');
}
// folder mains (.dew.js -> folder/index.dew.js)
for (const folderPath of Object.keys(folderMains)) {
const resolved = resolveFile(folderPath, convertFiles) || resolveDir(folderPath, convertFiles, folderMains);
// folder mains can be overridden by files of the same name
if (!resolved || resolved[folderPath.length] !== '/')
continue;
if (resolved.endsWith('.node')) {
writeNodeAlias(folderPath + '.dew.js', resolved.substr(folderPath.lastIndexOf('/') + 1));
}
else if (convertFiles[resolved]) {
writeJsAlias(folderPath + '.js', resolved.substr(folderPath.lastIndexOf('/') + 1), true, false);
writeDewAlias(folderPath + '.dew.js', toDew(resolved.substr(folderPath.lastIndexOf('/') + 1)));
}
}
// main main
if (pcfg.main && pcfg.main !== 'index' && pcfg.main !== 'index.js' && pcfg.main !== 'index.json') {
const resolved = resolveFile(pcfg.main, convertFiles) || resolveDir(pcfg.main, convertFiles, folderMains);
if (resolved) {
if (resolved.endsWith('.node'))
writeNodeAlias('index.dew.js', resolved);
else if (convertFiles[resolved])
writeDewAlias('index.dew.js', toDew(resolved));
}
}
else {
// index.js and index.json both already aliased to index.dew.js
if ('index.node' in convertFiles && !('index.js' in convertFiles) && !('index.json' in convertFiles)) {
writeNodeAlias('index.dew.js', 'index.node');
}
}
/*
* Config resolution
* As well as setting up aliases, we must also now update the config main and map to reference exact files
* This is because "module" is designed to skip automatic extension adding and directory indices
* In addition, a ".json" main needs a special wrapper
*/
let changed = false;
if (pcfg.main) {
// TODO add support for maps
// issue is that folder and file map cases need to be separated, but completely doable by just outputting two maps per original map
if (!(pcfg.map && pcfg.map[pcfg.main])) {
let resolved = resolveFile(pcfg.main, convertFiles) || resolveDir(pcfg.main, convertFiles, folderMains);
// JSON mains
if (resolved) {
if (resolved.endsWith('.json'))
resolved += '.js';
if (resolved !== pcfg.main) {
pcfg.main = resolved;
changed = true;
}
}
}
}
if (changed) {
let { json: pjson, style } = await readJSONStyled(path.resolve(dir, 'package.json'));
if (!pjson)
pjson = {};
await writeJSONStyled(path.resolve(dir, 'package.json'), Object.assign(pjson, serializePackageConfig(pcfg, defaultRegistry)), style || defaultStyle);
}
// update the package to be "type": "module" now that it is converted
pcfg.type = 'module';
log.debug(`Completed dew conversion, writing dew aliases for ${pkgName}...`);
await Promise.all(aliasPromises);
}
export function listAllFiles (dir: string): Promise<string[]> {
dir = path.resolve(dir);
const files = [];
return new Promise((resolve, reject) => {
let cnt = 0;
visitFileOrDir(dir);
function visitFileOrDir (fileOrDir) {
cnt++;
fileOrDir = path.resolve(fileOrDir);
fs.lstat(fileOrDir, (err, stats) => {
if (err) return reject(err);
if (stats.isSymbolicLink()) {
if (--cnt === 0)
resolve(files);
}
else if (!stats.isDirectory()) {
files.push(path.relative(dir, fileOrDir).replace(/\\/g, '/'));
if (--cnt === 0)
resolve(files);
}
else {
fs.readdir(fileOrDir, (err, paths) => {
if (err) return reject(err);
cnt--;
if (paths.length === 0 && cnt === 0)
resolve(files);
paths.forEach(fileOrDirPath => visitFileOrDir(path.resolve(fileOrDir, fileOrDirPath)));
});
}
});
}
});
}
function getLocalMaps (pcfg: ProcessedPackageConfig) {
const localMaps: Record<string, boolean> = Object.create(null);
if (pcfg.map) {
for (const target of Object.keys(pcfg.map)) {
if (target.startsWith('./'))
localMaps[target.substr(2)] = true;
}
}
return localMaps;
} | the_stack |
import { PlatformAccessory, Service } from 'homebridge';
import { Zigbee2mqttPlatform } from './platform';
import { ExtendedTimer } from './timer';
import { hap } from './hap';
import { BasicServiceCreatorManager, ServiceCreatorManager } from './converters/creators';
import { BasicAccessory, BasicLogger, ServiceHandler } from './converters/interfaces';
import { deviceListEntriesAreEqual, DeviceListEntry, isDeviceDefinition, isDeviceListEntry } from './z2mModels';
import { BaseDeviceConfiguration } from './configModels';
import { QoS } from 'mqtt';
export class Zigbee2mqttAccessory implements BasicAccessory {
private readonly updateTimer: ExtendedTimer;
private readonly serviceCreatorManager: ServiceCreatorManager;
private readonly serviceHandlers = new Map<string, ServiceHandler>();
private readonly serviceIds = new Set<string>();
private pendingPublishData: Record<string, unknown>;
private publishIsScheduled: boolean;
private readonly pendingGetKeys: Set<string>;
private getIsScheduled: boolean;
get log(): BasicLogger {
return this.platform.log;
}
get displayName(): string {
return this.accessory.context.device.friendly_name;
}
constructor(
private readonly platform: Zigbee2mqttPlatform,
public readonly accessory: PlatformAccessory,
private readonly additionalConfig: BaseDeviceConfiguration,
serviceCreatorManager?: ServiceCreatorManager,
) {
// Store ServiceCreatorManager
if (serviceCreatorManager === undefined) {
this.serviceCreatorManager = BasicServiceCreatorManager.getInstance();
} else {
this.serviceCreatorManager = serviceCreatorManager;
}
// Setup delayed publishing
this.pendingPublishData = {};
this.publishIsScheduled = false;
// Setup delayed get
this.pendingGetKeys = new Set<string>();
this.getIsScheduled = false;
// Log additional config
this.platform.log.debug(`Config for accessory ${this.displayName} : ${JSON.stringify(this.additionalConfig)}`);
this.updateDeviceInformation(accessory.context.device, true);
// Ask Zigbee2MQTT for a status update at least once every 4 hours.
this.updateTimer = new ExtendedTimer(() => {
this.queueAllKeysForGet();
}, (4 * 60 * 60 * 1000));
// Immediately request an update to start off.
this.queueAllKeysForGet();
}
registerServiceHandler(handler: ServiceHandler): void {
const key = handler.identifier;
if (this.serviceHandlers.has(key)) {
this.log.error(`DUPLICATE SERVICE HANDLER with identifier ${key} for accessory ${this.displayName}. New one will not stored.`);
} else {
this.serviceHandlers.set(key, handler);
}
}
isServiceHandlerIdKnown(identifier: string): boolean {
return this.serviceHandlers.has(identifier);
}
isPropertyExcluded(property: string | undefined): boolean {
if (property === undefined) {
// Property is undefined, so it can't be excluded.
// This is accepted so all exposes models can easily be checked.
return false;
}
return this.additionalConfig.excluded_keys?.includes(property) ?? false;
}
isValueAllowedForProperty(property: string, value: string): boolean {
const config = this.additionalConfig.values?.find(c => c.property === property);
if (config) {
if (config.include && config.include.length > 0) {
if (config.include.findIndex(p => this.doesValueMatchPattern(value, p)) < 0) {
// Value doesn't match any of the include patterns
return false;
}
}
if (config.exclude && config.exclude.length > 0) {
if (config.exclude.findIndex(p => this.doesValueMatchPattern(value, p)) >= 0) {
// Value matches one of the exclude patterns
return false;
}
}
}
return true;
}
private doesValueMatchPattern(value: string, pattern: string) {
if (pattern.length === 0) {
return false;
}
if (pattern.length >= 2) {
// Need at least 2 characters for the wildcard to work
if (pattern.startsWith('*')) {
return value.endsWith(pattern.substr(1));
}
if (pattern.endsWith('*')) {
return value.startsWith(pattern.substr(0, pattern.length - 1));
}
}
return value === pattern;
}
private queueAllKeysForGet(): void {
const keys = [...this.serviceHandlers.values()].map(h => h.getableKeys).reduce((a, b) => {
return a.concat(b);
}, []);
if (keys.length > 0) {
this.queueKeyForGetAction(keys);
}
}
private publishPendingGetKeys(): void {
const keys = [...this.pendingGetKeys];
this.pendingGetKeys.clear();
this.getIsScheduled = false;
if (keys.length > 0) {
const data = {};
for (const k of keys) {
data[k] = 0;
}
// Publish using ieeeAddr, as that will never change and the friendly_name might.
this.platform.publishMessage(`${this.accessory.context.device.ieee_address}/get`,
JSON.stringify(data), { qos: this.getMqttQosLevel(1) });
}
}
queueKeyForGetAction(key: string | string[]): void {
if (Array.isArray(key)) {
for (const k of key) {
this.pendingGetKeys.add(k);
}
} else {
this.pendingGetKeys.add(key);
}
this.log.debug(`Pending get: ${[...this.pendingGetKeys].join(', ')}`);
if (!this.getIsScheduled) {
this.getIsScheduled = true;
process.nextTick(() => {
this.publishPendingGetKeys();
});
}
}
static getUniqueIdForService(service: Service): string {
if (service.subtype === undefined) {
return service.UUID;
}
return `${service.UUID}_${service.subtype}`;
}
getOrAddService(service: Service): Service {
this.serviceIds.add(Zigbee2mqttAccessory.getUniqueIdForService(service));
const existingService = this.accessory.services.find(e =>
e.UUID === service.UUID && e.subtype === service.subtype,
);
if (existingService !== undefined) {
return existingService;
}
return this.accessory.addService(service);
}
queueDataForSetAction(data: Record<string, unknown>): void {
this.pendingPublishData = { ...this.pendingPublishData, ...data };
this.log.debug(`Pending data: ${JSON.stringify(this.pendingPublishData)}`);
if (!this.publishIsScheduled) {
this.publishIsScheduled = true;
process.nextTick(() => {
this.publishPendingSetData();
});
}
}
private publishPendingSetData() {
this.platform.publishMessage(`${this.accessory.context.device.ieee_address}/set`, JSON.stringify(this.pendingPublishData),
{ qos: this.getMqttQosLevel(2) });
this.publishIsScheduled = false;
this.pendingPublishData = {};
}
get UUID(): string {
return this.accessory.UUID;
}
get ieeeAddress(): string {
return this.accessory.context.device.ieee_address;
}
matchesIdentifier(id: string): boolean {
return (id === this.ieeeAddress || this.accessory.context.device.friendly_name === id);
}
updateDeviceInformation(info: DeviceListEntry | undefined, force_update = false) {
// Only update the device if a valid device list entry is passed.
// This is done so that old, pre-v1.0.0 accessories will only get updated when new device information is received.
if (isDeviceListEntry(info)
&& (force_update || !deviceListEntriesAreEqual(this.accessory.context.device, info))) {
const oldFriendlyName = this.accessory.context.device.friendly_name;
const friendlyNameChanged = (force_update || info.friendly_name.localeCompare(this.accessory.context.device.friendly_name) !== 0);
// Device info has changed
this.accessory.context.device = info;
if (!isDeviceDefinition(info.definition)) {
this.log.error(`No device definition for device ${info.friendly_name} (${this.ieeeAddress}).`);
} else {
// Update accessory info
// Note: getOrAddService is used so that the service is known in this.serviceIds and will not get filtered out.
this.getOrAddService(new hap.Service.AccessoryInformation())
.updateCharacteristic(hap.Characteristic.Name, info.friendly_name)
.updateCharacteristic(hap.Characteristic.Manufacturer, info.definition.vendor ?? 'Zigbee2MQTT')
.updateCharacteristic(hap.Characteristic.Model, info.definition.model ?? 'unknown')
.updateCharacteristic(hap.Characteristic.SerialNumber, info.ieee_address)
.updateCharacteristic(hap.Characteristic.HardwareRevision, info.date_code ?? '?')
.updateCharacteristic(hap.Characteristic.FirmwareRevision, info.software_build_id ?? '?');
// Create (new) services
this.serviceCreatorManager.createHomeKitEntitiesFromExposes(this, info.definition.exposes);
}
this.cleanStaleServices();
if (friendlyNameChanged) {
this.platform.log.debug(`Updating service names for ${info.friendly_name} (from ${oldFriendlyName})`);
this.updateServiceNames();
}
}
this.platform.api.updatePlatformAccessories([this.accessory]);
}
private cleanStaleServices(): void {
// Remove all services of which identifier is not known
const staleServices = this.accessory.services.filter(s => !this.serviceIds.has(Zigbee2mqttAccessory.getUniqueIdForService(s)));
staleServices.forEach((s) => {
this.log.debug(`Clean up stale service ${s.displayName} (${s.UUID}) for accessory ${this.displayName} (${this.ieeeAddress}).`);
this.accessory.removeService(s);
});
}
private updateServiceNames(): void {
// Update the name of all services
for (const service of this.accessory.services) {
if (service.UUID === hap.Service.AccessoryInformation.UUID) {
continue;
}
const nameCharacteristic = service.getCharacteristic(hap.Characteristic.Name);
if (nameCharacteristic !== undefined) {
const displayName = this.getDefaultServiceDisplayName(service.subtype);
nameCharacteristic.updateValue(displayName);
}
}
}
private getMqttQosLevel(defaultQoS: QoS): QoS {
if (this.platform.config?.mqtt.disable_qos) {
return 0;
}
return defaultQoS;
}
updateStates(state: Record<string, unknown>) {
// Restart timer
this.updateTimer.restart();
// Filter out all properties that have a null/undefined value
for (const key in state) {
if (state[key] === null || state[key] === undefined) {
delete state[key];
}
}
// Call updates
for (const handler of this.serviceHandlers.values()) {
handler.updateState(state);
}
}
getDefaultServiceDisplayName(subType: string | undefined): string {
let name = this.displayName;
if (subType !== undefined) {
name += ` ${subType}`;
}
return name;
}
} | the_stack |
import * as d3 from 'd3-selection';
import 'd3-transition';
import getNamespace from './getNamespace';
type ElementDatum = {
append: string;
children?: ElementDatum[];
duration?: number | Function | TransitionObject;
delay?: number | Function | TransitionObject;
ease?: Function | TransitionObject;
style?: ElementStyles;
call?: Function;
[key: string]: ElementValue;
};
type ElementValue = number | string | Function | object;
type ElementStyles = {
[key: string]: number | string | Function | object;
};
type TransitionState = 'start' | 'enter' | 'update' | 'exit';
// TODO: Causes type errors on style and children
type TransitionObject = {
start?: number | string | Function;
update?: number | string | Function;
enter: number | string | Function;
exit?: number | string | Function;
};
// type Selector = string | Node;
// TODO: Consider incorporating element types from:
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts
/**
* Using D3, this function renders elements based on declarative `data`, effectively replacing `select`, `append`, `data`, `join`, `enter`, `exit`, `transition` and more.
* @param selector
* @param data
*/
export default function render(selector, data: ElementDatum[]) {
// Crude way to check if `selector` is a D3 selection
if (typeof selector === 'object' && selector._groups && selector._parents) {
return renderSelection(selector, data);
}
const selection = d3.select(selector);
return renderSelection(selection, data);
}
/**
* Recursively renders elements based on `data`, which can be deeply nested with the `children` key.
*/
export function renderSelection(selection, data: ElementDatum[], level = 0) {
if (!Boolean(data)) {
return selection;
}
return (
selection
// Cool way to select immediate children. (Totally didn't know you could do this)
.selectAll((_, i, nodes) => {
return nodes[i].children;
})
.data(
// Ensure all data elements are okay
data.filter(d => Boolean(d)),
(d, i) => d?.key || i
)
.join(
enter => {
return enter
.append(d => {
// Yes you saw that right. Append element based on 'append' key in data.
// Makes this whole function incredibly flexible
const namespace = getNamespace(d.append);
if (namespace === 'html') {
return document.createElement(d.append);
}
// https://stackoverflow.com/questions/51857699/append-shapes-dynamically-in-d3
return document.createElementNS(
// @ts-ignore
d3.namespace(namespace).space,
d.append
);
})
.each(function(d) {
const element = d3.select(this);
// Hook into things like selection.call(xAxis)
if (typeof d.call === 'function') {
d.call(element);
}
// Add initial attributes. For now, initial and exit values are the same
element.call(selection => addAttributes(selection, d, 'start'));
// Add HTML
if (d.html) {
element.html(d.html);
}
// Add events to element eg. onClick
element.call(selection => addEvents(selection, d));
// Add enter transitions
element.call(selection => addTransition(selection, d, 'enter'));
// element.call(selection =>
// addEvents(selection, d, 'onTransition')
// );
// Recursively run again, passing in each child in selection
renderSelection(element, d.children, level + 1);
});
},
update => {
return update.each(function(d) {
const element = d3.select(this);
element.call(selection => addTransition(selection, d, 'update'));
renderSelection(element, d.children, level + 1);
});
},
exit => {
// Important magic sauce to exit all descendent children
exit.selectAll('*').each(exitTransition);
// NOTE: This doesn't seem to work, but '*' above will do for now
// exit.each(function(d) {
// renderSelection(d3.select(this), d, level + 1);
// });
return exit.each(exitTransition);
}
)
);
}
/**
* Add attributes to element node
* @param selection
* @param datum
* @param state
*/
function addAttributes(
selection,
datum: ElementDatum,
state: TransitionState
// node = null
) {
// Assume anything other than key, text etc are attributes
const {
append,
call,
key,
text,
html,
style,
children,
duration,
delay,
ease,
...attributes
} = datum;
// Rather than hand coding every attribute, we loop over the attributes object
for (const key in attributes) {
const attributeValue = attributes[key];
const value = getValue(attributeValue, state);
const isEvent = key.indexOf('on') === 0;
// Skip any on* events, we'll handle them in addEvents
if (!isEvent) {
selection.attr(keyToAttribute(key), value);
}
}
if (datum.text) {
selection.text(datum.text);
}
if (datum.style) {
selection = addStyles(selection, datum.style, state);
}
return selection;
}
/**
* Add event to selection element
* @param selection
* @param datum
*/
function addEvents(selection, datum, onPrefix = 'on') {
// Loop throught all keys in datum
for (const key in datum) {
const isEvent = key.indexOf(onPrefix) === 0;
// Only allow keys with on*
if (isEvent) {
const callback = datum[key];
// Check that the value is a callback function
if (typeof callback === 'function') {
const eventName = key.replace(onPrefix, '').toLowerCase();
selection.on(eventName, function(e, d) {
return callback(e, d);
});
}
}
}
return selection;
}
/**
* Adds inline styles to the element
* @param selection
* @param styles
* @param state
*/
function addStyles(selection, styles: ElementStyles, state: TransitionState) {
for (const key in styles) {
const styleValue = styles[key];
const value = getValue(styleValue, state);
selection.style(camelToKebab(key), value);
}
return selection;
}
/**
* Add transition to element, animating to a particular `state` by updating
* selection with `addAttributes`
* @param selection
* @param datum
* @param state
*/
function addTransition(
selection,
datum: ElementDatum,
state: TransitionState = 'enter'
) {
const duration = getValue(datum.duration, state);
if (!Boolean(datum)) {
return selection;
}
const delay = getValue(datum.delay, state) || 0;
const ease = getValue(datum.ease, state);
let transition = selection
.transition()
.delay(delay)
.duration(duration);
if (typeof ease === 'function') {
transition = transition.ease(t => ease(t));
}
if (state === 'exit') {
transition = transition.remove();
}
return selection
.transition(transition)
.call(selection => addAttributes(selection, datum, state));
}
function exitTransition(d) {
d3.select(this).call(selection => addTransition(selection, d, 'exit'));
}
/**
* Get value from ElementDatum key, process and pass to selection.attr(),
* selection.transition() or selection.style()
* Every value can have an optional exit/enter value
* We just check if value is an object eg. { exit: 0, enter: 100 }
* @param value
* @param state
*/
function getValue(value, state: TransitionState): number | string | Function {
if (typeof value === 'object') {
const newValue = value[state];
// Default to `exit` if `start` value not available
// Assume that element will start the same way it exits
if (state === 'start' && isEmpty(newValue)) {
return value['exit'];
}
// Default to `enter` if `update` value not available
if (state === 'update' && isEmpty(newValue)) {
return value['enter'];
}
return newValue;
}
return value;
}
/**
* Convert camelCase to kebab-case for JavaScript to HTML/CSS interop
* @param string
*/
function camelToKebab(string: string): string {
return string.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();
}
/**
* Convert key to HTML attribute. Most keys will change from camel to kebab
* case, except for certain SVG attributes.
* @param string
*/
function keyToAttribute(key: string): string {
if (
[
'allowReorder',
'attributeName',
'attributeType',
'autoReverse',
'baseFrequency',
'baseProfile',
'calcMode',
'clipPathUnits',
'contentScriptType',
'contentStyleType',
'diffuseConstant',
'edgeMode',
'externalResourceRequired',
'filterRes',
'filterUnits',
'glyphRef',
'gradientTransform',
'gradientUnits',
'kernelMatrix',
'kernelUnitLength',
'keyPoints',
'keySplines',
'keyTimes',
'lengthAdjust',
'limitingConeAngle',
'markerHeight',
'markerUnits',
'markerWidth',
'maskContentUnits',
'maskUnits',
'numOctaves',
'pathLength',
'patternContentUnits',
'patternTransform',
'patternUnits',
'pointsAtX',
'pointsAtY',
'pointsAtZ',
'preserveAlpha',
'preserveAspectRatio',
'primitiveUnits',
'referrerPolicy',
'refX',
'refY',
'repeatCount',
'repeatDur',
'requiredExtensions',
'requiredFeatures',
'specularConstant',
'specularExponent',
'spreadMethod',
'startOffset',
'stdDeviation',
'stitchTiles',
'surfaceScale',
'systemLanguage',
'tableValues',
'targetX',
'targetY',
'textLength',
'viewBox',
'xChannelSelector',
'yChannelSelector',
'zoomAndPan',
].includes(key)
) {
return key;
}
return camelToKebab(key);
}
function isEmpty(value) {
return value == null;
} | the_stack |
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Draggable from 'react-draggable';
import { FixedSizeList } from 'react-window';
import * as ql from './wasm-ql';
require('./style.css');
function prettyPrint(x: any) {
return JSON.stringify(x, (k, v) => {
if (k === 'abi' || k === 'account_abi') {
if (v.length <= 66)
return v;
else
return v.substr(0, 64) + '... (' + (v.length / 2) + ' bytes)';
} else
return v;
}, 4);
}
class AppState {
public alive = true;
public clientRoot: ClientRoot;
public result = [];
public chainWasm = new ql.ClientWasm('./chain-client.wasm');
public tokenWasm = new ql.ClientWasm('./token-client.wasm');
public request = 0;
public more = null;
public queryInspector = false;
public lastQuery = [];
public replyInspector = false;
public lastReply = {} as any;
private run(wasm, query, args, firstKeyName, handle) {
this.result = [];
const thisRequest = ++this.request;
let first_key = args[firstKeyName];
let running = false;
this.more = async () => {
if (running)
return;
running = true;
this.lastQuery = [
query,
{ ...args, snapshot_block: ['absolute', args.snapshot_block], [firstKeyName]: first_key },
];
const reply = await wasm.round_trip(this.lastQuery);
if (thisRequest !== this.request)
return;
running = false;
this.lastReply = reply[1];
handle(reply[1]);
first_key = reply[1].more;
if (!first_key)
this.more = null;
this.clientRoot.forceUpdate();
};
this.clientRoot.forceUpdate();
}
public runSelected() {
this.selection.run();
}
public accountsArgs = {
snapshot_block: 100000000,
first: '',
last: '',
include_abi: true,
max_results: 10,
};
public run_accounts() {
this.run(this.chainWasm, 'account', { ...this.accountsArgs, last: this.accountsArgs.last || 'zzzzzzzzzzzzj' }, 'first', reply => {
for (let acc of reply.accounts) {
acc = (({ name, privileged, account_creation_date, code, last_code_update, account_abi }) =>
({ name, privileged, account_creation_date, code, last_code_update, abi: account_abi }))(acc);
this.result.push(...prettyPrint(acc).split('\n'));
}
});
}
public accounts = { run: this.run_accounts.bind(this), form: AccountsForm };
public multTokensArgs = {
snapshot_block: 100000000,
account: 'b1',
first_key: { sym: '', code: '' },
last_key: { sym: '', code: '' },
max_results: 100,
};
public run_mult_tokens() {
this.run(this.tokenWasm, 'bal.mult.tok', {
...this.multTokensArgs,
last_key: { sym: this.multTokensArgs.last_key.sym || 'ZZZZZZZ', code: this.multTokensArgs.last_key.code || 'zzzzzzzzzzzzj' }
}, 'first_key', reply => {
for (const balance of reply.balances)
this.result.push(balance.account.padEnd(13, ' ') + ql.format_extended_asset(balance.amount));
});
}
public multipleTokens = { run: this.run_mult_tokens.bind(this), form: MultipleTokensForm };
public tokensMultAccArgs = {
snapshot_block: 100000000,
code: 'eosio.token',
sym: 'EOS',
first_account: '',
last_account: '',
max_results: 10,
};
public run_tok_mul_acc() {
this.run(this.tokenWasm, 'bal.mult.acc', { ...this.tokensMultAccArgs, last_account: this.tokensMultAccArgs.last_account || 'zzzzzzzzzzzzj' }, 'first_account', reply => {
for (const balance of reply.balances)
this.result.push(balance.account.padEnd(13, ' ') + ql.format_extended_asset(balance.amount));
});
}
public tokensMultAcc = { run: this.run_tok_mul_acc.bind(this), form: TokensForMultipleAccountsForm };
public transfersArgs = {
snapshot_block: 100000000,
first_key: {
receiver: '',
account: '',
block: ['absolute', 0],
transaction_id: '0000000000000000000000000000000000000000000000000000000000000000',
action_ordinal: 0,
},
last_key: {
receiver: '',
account: 'zzzzzzzzzzzzj',
block: ['absolute', 999999999],
transaction_id: 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
action_ordinal: 0xffffffff,
},
include_notify_incoming: true,
include_notify_outgoing: true,
max_results: 10,
};
public run_transfers() {
this.run(this.tokenWasm, 'transfer', {
...this.transfersArgs,
last_key: { ...this.transfersArgs.last_key, receiver: this.transfersArgs.last_key.receiver || 'zzzzzzzzzzzzj' }
}, 'first_key', reply => {
for (const transfer of reply.transfers)
this.result.push(
transfer.from.padEnd(13, ' ') + ' -> ' + transfer.to.padEnd(13, ' ') +
ql.format_extended_asset(transfer.quantity).padEnd(40, ' ') +
(transfer.key.block[1] + '').padEnd(11, ' ') + transfer.key.transaction_id +
' ' + transfer.memo);
});
}
public transfers = { run: this.run_transfers.bind(this), form: TransfersForm };
public selection = this.accounts;
public restore(prev: AppState) {
prev.request = -1;
this.result = prev.result;
this.accountsArgs = prev.accountsArgs;
this.multTokensArgs = prev.multTokensArgs;
this.tokensMultAccArgs = prev.tokensMultAccArgs;
this.transfersArgs = prev.transfersArgs;
}
}
async function delay(ms: number): Promise<void> {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms);
});
}
function Results({ appState }: { appState: AppState }) {
const FSL = FixedSizeList as any;
return (
<div className='result'>
<FSL
itemCount={appState.result.length + (appState.more ? 10 : 0)}
itemSize={16}
height={800}
>
{({ index, style }) => {
let content = '';
if (index < appState.result.length)
content = appState.result[index];
else
if (appState.more) appState.more();
return <pre style={style}>{content}</pre>;
}}
</FSL>
{appState.queryInspector &&
<div className='query-inspect-container'>
<Draggable
axis='both'
handle='.handle'
defaultPosition={{ x: 10, y: 10 }}
position={null}
scale={1}
>
<div className='inspect'>
<div className='handle'>Query Inspector</div>
<pre className='inspect-content'>{prettyPrint(appState.lastQuery)}</pre>
</div>
</Draggable>
</div>
}
{appState.replyInspector &&
<div className='reply-inspect-container'>
<Draggable
axis='both'
handle='.handle'
defaultPosition={{ x: 10, y: 10 }}
position={null}
scale={1}
>
<div className='inspect'>
<div className='handle'>Reply Inspector</div>
{console.log(appState.lastReply)}
<pre className='inspect-content'>{prettyPrint({ more: appState.lastReply.more, ...appState.lastReply })}</pre>
</div>
</Draggable>
</div>
}
</div>
);
}
function AccountsForm({ appState }: { appState: AppState }) {
return (
<div className='balance'>
<table>
<tbody>
{/* <tr>
<td>snapshot_block </td>
<td></td>
<td><input type="text" value={appState.accountsArgs.snapshot_block } onChange={e => { appState.accountsArgs.snapshot_block = +e.target.value; appState.runSelected(); }} /></td>
</tr> */}
<tr>
<td>min account</td>
<td></td>
<td><input type="text" value={appState.accountsArgs.first} onChange={e => { appState.accountsArgs.first = e.target.value; appState.runSelected(); }} /></td>
</tr>
<tr>
<td>max account</td>
<td></td>
<td><input type="text" value={appState.accountsArgs.last} onChange={e => { appState.accountsArgs.last = e.target.value; appState.runSelected(); }} /></td>
</tr>
</tbody>
</table>
</div>
);
}
function MultipleTokensForm({ appState }: { appState: AppState }) {
return (
<div className='balance'>
<table>
<tbody>
{/* <tr>
<td>snapshot_block </td>
<td></td>
<td><input type="text" value={appState.multTokensArgs.snapshot_block } onChange={e => { appState.multTokensArgs.snapshot_block = +e.target.value; appState.runSelected(); }} /></td>
</tr> */}
<tr>
<td>account</td>
<td></td>
<td><input type="text" value={appState.multTokensArgs.account} onChange={e => { appState.multTokensArgs.account = e.target.value; appState.runSelected(); }} /></td>
</tr>
{/* <tr>
<td>first_key</td>
<td>sym</td>
<td><input type="text" value={appState.multTokensArgs.first_key.sym} onChange={e => { appState.multTokensArgs.first_key.sym = e.target.value; appState.runSelected(); }} /></td>
</tr>
<tr>
<td></td>
<td>code</td>
<td><input type="text" value={appState.multTokensArgs.first_key.code} onChange={e => { appState.multTokensArgs.first_key.code = e.target.value; appState.runSelected(); }} /></td>
</tr>
<tr>
<td>last_key</td>
<td>sym</td>
<td><input type="text" value={appState.multTokensArgs.last_key.sym} onChange={e => { appState.multTokensArgs.last_key.sym = e.target.value; appState.runSelected(); }} /></td>
</tr>
<tr>
<td></td>
<td>code</td>
<td><input type="text" value={appState.multTokensArgs.last_key.code} onChange={e => { appState.multTokensArgs.last_key.code = e.target.value; appState.runSelected(); }} /></td>
</tr> */}
</tbody>
</table>
</div>
);
}
function TokensForMultipleAccountsForm({ appState }: { appState: AppState }) {
return (
<div className='balance'>
<table>
<tbody>
{/* <tr>
<td>snapshot_block </td>
<td></td>
<td><input type="text" value={appState.tokensMultAccArgs.snapshot_block } onChange={e => { appState.tokensMultAccArgs.snapshot_block = +e.target.value; appState.runSelected(); }} /></td>
</tr> */}
<tr>
<td>code</td>
<td></td>
<td><input type="text" value={appState.tokensMultAccArgs.code} onChange={e => { appState.tokensMultAccArgs.code = e.target.value; appState.runSelected(); }} /></td>
</tr>
<tr>
<td>sym</td>
<td></td>
<td><input type="text" value={appState.tokensMultAccArgs.sym} onChange={e => { appState.tokensMultAccArgs.sym = e.target.value; appState.runSelected(); }} /></td>
</tr>
<tr>
<td>min account</td>
<td></td>
<td><input type="text" value={appState.tokensMultAccArgs.first_account} onChange={e => { appState.tokensMultAccArgs.first_account = e.target.value; appState.runSelected(); }} /></td>
</tr>
<tr>
<td>max account</td>
<td></td>
<td><input type="text" value={appState.tokensMultAccArgs.last_account} onChange={e => { appState.tokensMultAccArgs.last_account = e.target.value; appState.runSelected(); }} /></td>
</tr>
</tbody>
</table>
</div>
);
}
function TransfersForm({ appState }: { appState: AppState }) {
return (
<div className='balance'>
<table>
<tbody>
{/* <tr>
<td>snapshot_block </td>
<td></td>
<td><input type="text" value={appState.transfersArgs.snapshot_block } onChange={e => { appState.transfersArgs.snapshot_block = +e.target.value; appState.runSelected(); }} /></td>
</tr> */}
<tr>
<td>min receiver</td>
<td></td>
<td><input type="text" value={appState.transfersArgs.first_key.receiver} onChange={e => { appState.transfersArgs.first_key.receiver = e.target.value; appState.runSelected(); }} /></td>
</tr>
<tr>
<td>max receiver</td>
<td></td>
<td><input type="text" value={appState.transfersArgs.last_key.receiver} onChange={e => { appState.transfersArgs.last_key.receiver = e.target.value; appState.runSelected(); }} /></td>
</tr>
<tr>
<td>incoming</td>
<td></td>
<td><input type="checkbox" checked={appState.transfersArgs.include_notify_incoming} onChange={e => { appState.transfersArgs.include_notify_incoming = e.target.checked; appState.runSelected(); }} /></td>
</tr>
<tr>
<td>outgoing</td>
<td></td>
<td><input type="checkbox" checked={appState.transfersArgs.include_notify_outgoing} onChange={e => { appState.transfersArgs.include_notify_outgoing = e.target.checked; appState.runSelected(); }} /></td>
</tr>
</tbody>
</table>
</div>
);
}
function Controls({ appState }: { appState: AppState }) {
return (
<div className='control'>
<label>
<input
type="radio"
checked={appState.selection === appState.accounts}
onChange={e => { appState.selection = appState.accounts; appState.runSelected(); }}>
</input>
Accounts
</label>
<label>
<input
type="radio"
checked={appState.selection === appState.multipleTokens}
onChange={e => { appState.selection = appState.multipleTokens; appState.runSelected(); }}>
</input>
Multiple Tokens
</label>
<label>
<input
type="radio"
checked={appState.selection === appState.tokensMultAcc}
onChange={e => { appState.selection = appState.tokensMultAcc; appState.runSelected(); }}>
</input>
Tokens For Mult Acc
</label>
<label>
<input
type="radio"
checked={appState.selection === appState.transfers}
onChange={e => { appState.selection = appState.transfers; appState.runSelected(); }}>
</input>
Transfers
</label>
<br />
<label>
<input
type='checkbox'
checked={appState.queryInspector}
onChange={e => { appState.queryInspector = e.target.checked; appState.clientRoot.forceUpdate(); }}>
</input>
Query Inspector
</label>
<label>
<input
type='checkbox'
checked={appState.replyInspector}
onChange={e => { appState.replyInspector = e.target.checked; appState.clientRoot.forceUpdate(); }}>
</input>
Reply Inspector
</label>
</div>
);
}
class ClientRoot extends React.Component<{ appState: AppState }> {
public render() {
const { appState } = this.props;
appState.clientRoot = this;
return (
<div className='client-root'>
<div className='banner'>
Example application demonstrating wasm-ql
</div>
<Controls appState={appState} />
{appState.selection.form({ appState })}
<Results appState={appState} />
<div className='disclaimer'>
<a href="https://github.com/EOSIO/history-tools">GitHub Repo...</a>
<br /><br />
Disclaimer: All repositories and other materials are provided subject to this
<a href="https://block.one/important-notice/">IMPORTANT</a>
notice and you must familiarize yourself with its terms. The notice contains
important information, limitations and restrictions relating to our software,
publications, trademarks, third-party resources, and forward-looking statements.
By accessing any of our repositories and other materials, you accept and agree
to the terms of the notice.
</div>
</div>
);
}
}
export default function init(prev: AppState) {
let appState = new AppState();
if (prev) {
appState.restore(prev);
prev.alive = false;
}
ReactDOM.render(<ClientRoot {...{ appState }} />, document.getElementById('main'));
appState.runSelected();
return appState;
} | the_stack |
import {
IAuthentication,
IConnectionFactory,
OutputFormatPropertyName,
RecognitionMode,
RecognizerConfig,
ServiceRecognizerBase,
SpeechConnectionFactory,
SpeechServiceConfig,
SpeechServiceRecognizer,
} from "../common.speech/Exports";
import { marshalPromiseToCallbacks } from "../common/Exports";
import { AudioConfigImpl } from "./Audio/AudioConfig";
import { Contracts } from "./Contracts";
import {
AudioConfig,
AutoDetectSourceLanguageConfig,
KeywordRecognitionModel,
OutputFormat,
PropertyCollection,
PropertyId,
Recognizer,
SpeechRecognitionCanceledEventArgs,
SpeechRecognitionEventArgs,
SpeechRecognitionResult,
} from "./Exports";
import { SpeechConfig, SpeechConfigImpl } from "./SpeechConfig";
/**
* Performs speech recognition from microphone, file, or other audio input streams, and gets transcribed text as result.
* @class SpeechRecognizer
*/
export class SpeechRecognizer extends Recognizer {
private privDisposedRecognizer: boolean;
/**
* SpeechRecognizer constructor.
* @constructor
* @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer
* @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer
*/
public constructor(speechConfig: SpeechConfig, audioConfig?: AudioConfig) {
const speechConfigImpl: SpeechConfigImpl = speechConfig as SpeechConfigImpl;
Contracts.throwIfNull(speechConfigImpl, "speechConfig");
Contracts.throwIfNullOrWhitespace(
speechConfigImpl.properties.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage),
PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage]);
super(audioConfig, speechConfigImpl.properties, new SpeechConnectionFactory());
this.privDisposedRecognizer = false;
}
/**
* SpeechRecognizer constructor.
* @constructor
* @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer
* @param {AutoDetectSourceLanguageConfig} autoDetectSourceLanguageConfig - An source language detection configuration associated with the recognizer
* @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer
*/
public static FromConfig(speechConfig: SpeechConfig, autoDetectSourceLanguageConfig: AutoDetectSourceLanguageConfig, audioConfig?: AudioConfig): SpeechRecognizer {
const speechConfigImpl: SpeechConfigImpl = speechConfig as SpeechConfigImpl;
autoDetectSourceLanguageConfig.properties.mergeTo(speechConfigImpl.properties);
const recognizer = new SpeechRecognizer(speechConfig, audioConfig);
return recognizer;
}
/**
* The event recognizing signals that an intermediate recognition result is received.
* @member SpeechRecognizer.prototype.recognizing
* @function
* @public
*/
public recognizing: (sender: Recognizer, event: SpeechRecognitionEventArgs) => void;
/**
* The event recognized signals that a final recognition result is received.
* @member SpeechRecognizer.prototype.recognized
* @function
* @public
*/
public recognized: (sender: Recognizer, event: SpeechRecognitionEventArgs) => void;
/**
* The event canceled signals that an error occurred during recognition.
* @member SpeechRecognizer.prototype.canceled
* @function
* @public
*/
public canceled: (sender: Recognizer, event: SpeechRecognitionCanceledEventArgs) => void;
/**
* Gets the endpoint id of a customized speech model that is used for speech recognition.
* @member SpeechRecognizer.prototype.endpointId
* @function
* @public
* @returns {string} the endpoint id of a customized speech model that is used for speech recognition.
*/
public get endpointId(): string {
Contracts.throwIfDisposed(this.privDisposedRecognizer);
return this.properties.getProperty(PropertyId.SpeechServiceConnection_EndpointId, "00000000-0000-0000-0000-000000000000");
}
/**
* Gets the authorization token used to communicate with the service.
* @member SpeechRecognizer.prototype.authorizationToken
* @function
* @public
* @returns {string} Authorization token.
*/
public get authorizationToken(): string {
return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);
}
/**
* Gets/Sets the authorization token used to communicate with the service.
* @member SpeechRecognizer.prototype.authorizationToken
* @function
* @public
* @param {string} token - Authorization token.
*/
public set authorizationToken(token: string) {
Contracts.throwIfNullOrWhitespace(token, "token");
this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, token);
}
/**
* Gets the spoken language of recognition.
* @member SpeechRecognizer.prototype.speechRecognitionLanguage
* @function
* @public
* @returns {string} The spoken language of recognition.
*/
public get speechRecognitionLanguage(): string {
Contracts.throwIfDisposed(this.privDisposedRecognizer);
return this.properties.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage);
}
/**
* Gets the output format of recognition.
* @member SpeechRecognizer.prototype.outputFormat
* @function
* @public
* @returns {OutputFormat} The output format of recognition.
*/
public get outputFormat(): OutputFormat {
Contracts.throwIfDisposed(this.privDisposedRecognizer);
if (this.properties.getProperty(OutputFormatPropertyName, OutputFormat[OutputFormat.Simple]) === OutputFormat[OutputFormat.Simple]) {
return OutputFormat.Simple;
} else {
return OutputFormat.Detailed;
}
}
/**
* The collection of properties and their values defined for this SpeechRecognizer.
* @member SpeechRecognizer.prototype.properties
* @function
* @public
* @returns {PropertyCollection} The collection of properties and their values defined for this SpeechRecognizer.
*/
public get properties(): PropertyCollection {
return this.privProperties;
}
/**
* Starts speech recognition, and stops after the first utterance is recognized.
* The task returns the recognition text as result.
* Note: RecognizeOnceAsync() returns when the first utterance has been recognized,
* so it is suitable only for single shot recognition
* like command or query. For long-running recognition, use StartContinuousRecognitionAsync() instead.
* @member SpeechRecognizer.prototype.recognizeOnceAsync
* @function
* @public
* @param cb - Callback that received the SpeechRecognitionResult.
* @param err - Callback invoked in case of an error.
*/
public recognizeOnceAsync(cb?: (e: SpeechRecognitionResult) => void, err?: (e: string) => void): void {
marshalPromiseToCallbacks(this.recognizeOnceAsyncImpl(RecognitionMode.Interactive), cb, err);
}
/**
* Starts speech recognition, until stopContinuousRecognitionAsync() is called.
* User must subscribe to events to receive recognition results.
* @member SpeechRecognizer.prototype.startContinuousRecognitionAsync
* @function
* @public
* @param cb - Callback invoked once the recognition has started.
* @param err - Callback invoked in case of an error.
*/
public startContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {
marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(RecognitionMode.Conversation), cb, err);
}
/**
* Stops continuous speech recognition.
* @member SpeechRecognizer.prototype.stopContinuousRecognitionAsync
* @function
* @public
* @param cb - Callback invoked once the recognition has stopped.
* @param err - Callback invoked in case of an error.
*/
public stopContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {
marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err);
}
/**
* Starts speech recognition with keyword spotting, until
* stopKeywordRecognitionAsync() is called.
* User must subscribe to events to receive recognition results.
* Note: Key word spotting functionality is only available on the
* Speech Devices SDK. This functionality is currently not included in the SDK itself.
* @member SpeechRecognizer.prototype.startKeywordRecognitionAsync
* @function
* @public
* @param {KeywordRecognitionModel} model The keyword recognition model that
* specifies the keyword to be recognized.
* @param cb - Callback invoked once the recognition has started.
* @param err - Callback invoked in case of an error.
*/
public startKeywordRecognitionAsync(model: KeywordRecognitionModel, cb?: () => void, err?: (e: string) => void): void {
Contracts.throwIfNull(model, "model");
if (!!err) {
err("Not yet implemented.");
}
}
/**
* Stops continuous speech recognition.
* Note: Key word spotting functionality is only available on the
* Speech Devices SDK. This functionality is currently not included in the SDK itself.
* @member SpeechRecognizer.prototype.stopKeywordRecognitionAsync
* @function
* @public
* @param cb - Callback invoked once the recognition has stopped.
* @param err - Callback invoked in case of an error.
*/
public stopKeywordRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {
if (!!cb) {
cb();
}
}
/**
* closes all external resources held by an instance of this class.
* @member SpeechRecognizer.prototype.close
* @function
* @public
*/
public close(cb?: () => void, errorCb?: (error: string) => void): void {
Contracts.throwIfDisposed(this.privDisposedRecognizer);
marshalPromiseToCallbacks(this.dispose(true), cb, errorCb);
}
/**
* Disposes any resources held by the object.
* @member SpeechRecognizer.prototype.dispose
* @function
* @public
* @param {boolean} disposing - true if disposing the object.
*/
protected async dispose(disposing: boolean): Promise<void> {
if (this.privDisposedRecognizer) {
return;
}
if (disposing) {
this.privDisposedRecognizer = true;
await this.implRecognizerStop();
}
await super.dispose(disposing);
}
protected createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig {
return new RecognizerConfig(
speechConfig,
this.properties);
}
protected createServiceRecognizer(
authentication: IAuthentication,
connectionFactory: IConnectionFactory,
audioConfig: AudioConfig,
recognizerConfig: RecognizerConfig): ServiceRecognizerBase {
const configImpl: AudioConfigImpl = audioConfig as AudioConfigImpl;
return new SpeechServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);
}
} | the_stack |
import * as Common from '../../core/common/common.js';
import * as SDK from '../../core/sdk/sdk.js';
export function frameworkEventListeners(object: SDK.RemoteObject.RemoteObject): Promise<FrameworkEventListenersObject> {
const domDebuggerModel = object.runtimeModel().target().model(SDK.DOMDebuggerModel.DOMDebuggerModel);
if (!domDebuggerModel) {
return Promise.resolve({eventListeners: [], internalHandlers: null} as FrameworkEventListenersObject);
}
const listenersResult = {internalHandlers: null, eventListeners: []} as FrameworkEventListenersObject;
return object.callFunction(frameworkEventListenersImpl, undefined)
.then(assertCallFunctionResult)
.then(getOwnProperties)
.then(createEventListeners)
.then(returnResult)
.catch(error => {
console.error(error);
return listenersResult;
});
function getOwnProperties(object: SDK.RemoteObject.RemoteObject): Promise<SDK.RemoteObject.GetPropertiesResult> {
return object.getOwnProperties(false /* generatePreview */);
}
async function createEventListeners(result: SDK.RemoteObject.GetPropertiesResult): Promise<void> {
if (!result.properties) {
throw new Error('Object properties is empty');
}
const promises = [];
for (const property of result.properties) {
if (property.name === 'eventListeners' && property.value) {
promises.push(convertToEventListeners(property.value).then(storeEventListeners));
}
if (property.name === 'internalHandlers' && property.value) {
promises.push(convertToInternalHandlers(property.value).then(storeInternalHandlers));
}
if (property.name === 'errorString' && property.value) {
printErrorString(property.value);
}
}
await Promise.all(promises);
}
function convertToEventListeners(pageEventListenersObject: SDK.RemoteObject.RemoteObject):
Promise<SDK.DOMDebuggerModel.EventListener[]> {
return SDK.RemoteObject.RemoteArray.objectAsArray(pageEventListenersObject)
.map(toEventListener)
.then(filterOutEmptyObjects);
function toEventListener(listenerObject: SDK.RemoteObject.RemoteObject):
Promise<SDK.DOMDebuggerModel.EventListener|null> {
let type: string;
let useCapture: boolean;
let passive: boolean;
let once: boolean;
let handler: SDK.RemoteObject.RemoteObject|null = null;
let originalHandler: SDK.RemoteObject.RemoteObject|null = null;
let location: (SDK.DebuggerModel.Location|null)|null = null;
let removeFunctionObject: SDK.RemoteObject.RemoteObject|null = null;
const promises = [];
promises.push(
listenerObject
.callFunctionJSON(
truncatePageEventListener as (this: Object) => TruncatedEventListenerObjectInInspectedPage, undefined)
.then(storeTruncatedListener));
function truncatePageEventListener(this: EventListenerObjectInInspectedPage):
TruncatedEventListenerObjectInInspectedPage {
return {type: this.type, useCapture: this.useCapture, passive: this.passive, once: this.once};
}
function storeTruncatedListener(truncatedListener: TruncatedEventListenerObjectInInspectedPage): void {
if (truncatedListener.type !== undefined) {
type = truncatedListener.type;
}
if (truncatedListener.useCapture !== undefined) {
useCapture = truncatedListener.useCapture;
}
if (truncatedListener.passive !== undefined) {
passive = truncatedListener.passive;
}
if (truncatedListener.once !== undefined) {
once = truncatedListener.once;
}
}
promises.push(
listenerObject.callFunction(handlerFunction as (this: Object) => SDK.RemoteObject.RemoteObject | null)
.then(assertCallFunctionResult)
.then(storeOriginalHandler)
.then(toTargetFunction)
.then(storeFunctionWithDetails));
function handlerFunction(this: EventListenerObjectInInspectedPage): SDK.RemoteObject.RemoteObject|null {
return this.handler || null;
}
function storeOriginalHandler(functionObject: SDK.RemoteObject.RemoteObject): SDK.RemoteObject.RemoteObject {
originalHandler = functionObject;
return originalHandler;
}
function storeFunctionWithDetails(functionObject: SDK.RemoteObject.RemoteObject): Promise<void> {
handler = functionObject;
return functionObject.debuggerModel().functionDetailsPromise(functionObject).then(storeFunctionDetails);
}
function storeFunctionDetails(functionDetails: SDK.DebuggerModel.FunctionDetails|null): void {
location = functionDetails ? functionDetails.location : null;
}
promises.push(
listenerObject.callFunction(getRemoveFunction as (this: Object) => SDK.RemoteObject.RemoteObject | null)
.then(assertCallFunctionResult)
.then(storeRemoveFunction));
function getRemoveFunction(this: EventListenerObjectInInspectedPage): SDK.RemoteObject.RemoteObject|null {
return this.remove || null;
}
function storeRemoveFunction(functionObject: SDK.RemoteObject.RemoteObject): void {
if (functionObject.type !== 'function') {
return;
}
removeFunctionObject = functionObject;
}
return Promise.all(promises).then(createEventListener).catch(error => {
console.error(error);
return null;
});
function createEventListener(): SDK.DOMDebuggerModel.EventListener {
if (!location) {
throw new Error('Empty event listener\'s location');
}
return new SDK.DOMDebuggerModel.EventListener(
domDebuggerModel as SDK.DOMDebuggerModel.DOMDebuggerModel, object, type, useCapture, passive, once, handler,
originalHandler, location, removeFunctionObject, SDK.DOMDebuggerModel.EventListener.Origin.FrameworkUser);
}
}
}
function convertToInternalHandlers(pageInternalHandlersObject: SDK.RemoteObject.RemoteObject):
Promise<SDK.RemoteObject.RemoteArray> {
return SDK.RemoteObject.RemoteArray.objectAsArray(pageInternalHandlersObject)
.map(toTargetFunction)
.then(SDK.RemoteObject.RemoteArray.createFromRemoteObjects.bind(null));
}
function toTargetFunction(functionObject: SDK.RemoteObject.RemoteObject): Promise<SDK.RemoteObject.RemoteObject> {
return SDK.RemoteObject.RemoteFunction.objectAsFunction(functionObject).targetFunction();
}
function storeEventListeners(eventListeners: SDK.DOMDebuggerModel.EventListener[]): void {
listenersResult.eventListeners = eventListeners;
}
function storeInternalHandlers(internalHandlers: SDK.RemoteObject.RemoteArray): void {
listenersResult.internalHandlers = internalHandlers;
}
function printErrorString(errorString: SDK.RemoteObject.RemoteObject): void {
Common.Console.Console.instance().error(String(errorString.value));
}
function returnResult(): FrameworkEventListenersObject {
return listenersResult;
}
function assertCallFunctionResult(result: SDK.RemoteObject.CallFunctionResult): SDK.RemoteObject.RemoteObject {
if (result.wasThrown || !result.object) {
throw new Error('Exception in callFunction or empty result');
}
return result.object;
}
function filterOutEmptyObjects<T>(objects: (T|null)[]): T[] {
return objects.filter(filterOutEmpty) as T[];
function filterOutEmpty(object: T|null): boolean {
return Boolean(object);
}
}
/*
frameworkEventListeners fetcher functions should produce following output:
{
// framework event listeners
"eventListeners": [
{
"handler": function(),
"useCapture": true,
"passive": false,
"once": false,
"type": "change",
"remove": function(type, handler, useCapture, passive)
},
...
],
// internal framework event handlers
"internalHandlers": [
function(),
function(),
...
]
}
*/
function frameworkEventListenersImpl(this: Object): {eventListeners: Array<EventListenerObjectInInspectedPage>} {
const errorLines = [];
let eventListeners: EventListenerObjectInInspectedPage[] = [];
let internalHandlers: (() => void)[] = [];
let fetchers = [jQueryFetcher];
try {
// @ts-ignore Here because of layout tests.
if (self.devtoolsFrameworkEventListeners && isArrayLike(self.devtoolsFrameworkEventListeners)) {
// @ts-ignore Here because of layout tests.
fetchers = fetchers.concat(self.devtoolsFrameworkEventListeners);
}
} catch (e) {
errorLines.push('devtoolsFrameworkEventListeners call produced error: ' + toString(e));
}
for (let i = 0; i < fetchers.length; ++i) {
try {
const fetcherResult = fetchers[i](this);
if (fetcherResult.eventListeners && isArrayLike(fetcherResult.eventListeners)) {
const fetcherResultEventListeners = fetcherResult.eventListeners;
const nonEmptyEventListeners = fetcherResultEventListeners
.map(eventListener => {
return checkEventListener(eventListener);
})
.filter(nonEmptyObject);
eventListeners = eventListeners.concat(nonEmptyEventListeners as EventListenerObjectInInspectedPage[]);
}
if (fetcherResult.internalHandlers && isArrayLike(fetcherResult.internalHandlers)) {
const fetcherResultInternalHandlers = fetcherResult.internalHandlers as (() => void)[];
const nonEmptyInternalHandlers = fetcherResultInternalHandlers
.map(handler => {
return checkInternalHandler(handler);
})
.filter(nonEmptyObject);
internalHandlers = internalHandlers.concat(nonEmptyInternalHandlers as (() => void)[]);
}
} catch (e) {
errorLines.push('fetcher call produced error: ' + toString(e));
}
}
const result: {
eventListeners: EventListenerObjectInInspectedPage[],
internalHandlers?: (() => void)[],
errorString?: string,
} = {
eventListeners: eventListeners,
internalHandlers: internalHandlers.length ? internalHandlers : undefined,
errorString: undefined,
};
// The logic further up seems to expect that if the internalHandlers is set,
// that it should have a non-empty Array, but TS / Closure also expect the
// property to exist, so we always add it above, but then remove it again
// here if there's no value set.
if (!result.internalHandlers) {
delete result.internalHandlers;
}
if (errorLines.length) {
let errorString: string = 'Framework Event Listeners API Errors:\n\t' + errorLines.join('\n\t');
errorString = errorString.substr(0, errorString.length - 1);
result.errorString = errorString;
}
// Remove the errorString if it's not set.
if (result.errorString === '' || result.errorString === undefined) {
delete result.errorString;
}
return result;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isArrayLike(obj: any): boolean {
if (!obj || typeof obj !== 'object') {
return false;
}
try {
if (typeof obj.splice === 'function') {
const len = obj.length;
return typeof len === 'number' && (len >>> 0 === len && (len > 0 || 1 / len > 0));
}
} catch (e) {
}
return false;
}
function checkEventListener(eventListener: PossibleEventListenerObjectInInspectedPage|
null): EventListenerObjectInInspectedPage|null {
try {
let errorString = '';
if (!eventListener) {
errorString += 'empty event listener, ';
} else {
const type = eventListener.type;
if (!type || (typeof type !== 'string')) {
errorString += 'event listener\'s type isn\'t string or empty, ';
}
const useCapture = eventListener.useCapture;
if (typeof useCapture !== 'boolean') {
errorString += 'event listener\'s useCapture isn\'t boolean or undefined, ';
}
const passive = eventListener.passive;
if (typeof passive !== 'boolean') {
errorString += 'event listener\'s passive isn\'t boolean or undefined, ';
}
const once = eventListener.once;
if (typeof once !== 'boolean') {
errorString += 'event listener\'s once isn\'t boolean or undefined, ';
}
const handler = eventListener.handler;
if (!handler || (typeof handler !== 'function')) {
errorString += 'event listener\'s handler isn\'t a function or empty, ';
}
const remove = eventListener.remove;
if (remove && (typeof remove !== 'function')) {
errorString += 'event listener\'s remove isn\'t a function, ';
}
if (!errorString) {
return {
type: type,
useCapture: useCapture,
passive: passive,
once: once,
handler: handler,
remove: remove,
} as EventListenerObjectInInspectedPage;
}
}
errorLines.push(errorString.substr(0, errorString.length - 2));
return null;
} catch (error) {
errorLines.push(toString(error));
return null;
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function checkInternalHandler(handler: any): (() => any)|null {
if (handler && (typeof handler === 'function')) {
return handler;
}
errorLines.push('internal handler isn\'t a function or empty');
return null;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function toString(obj: any): string {
try {
return String(obj);
} catch (e) {
return '<error>';
}
}
function nonEmptyObject<T>(obj: T|null): boolean {
return Boolean(obj);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function jQueryFetcher(node: any): {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
eventListeners: {handler: any, useCapture: boolean, passive: boolean, once: boolean, type: string}[],
internalHandlers?: (() => void)[],
} {
if (!node || !(node instanceof Node)) {
return {eventListeners: []};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const jQuery = (window as any)['jQuery'];
if (!jQuery || !jQuery.fn) {
return {eventListeners: []};
}
const jQueryFunction = jQuery;
const data = jQuery._data || jQuery.data;
const eventListeners = [];
const internalHandlers = [];
if (typeof data === 'function') {
const events = data(node, 'events');
for (const type in events) {
for (const key in events[type]) {
const frameworkListener = events[type][key];
if (typeof frameworkListener === 'object' || typeof frameworkListener === 'function') {
const listener = {
handler: frameworkListener.handler || frameworkListener,
useCapture: true,
passive: false,
once: false,
type: type,
remove: jQueryRemove.bind(node, frameworkListener.selector),
};
eventListeners.push(listener);
}
}
}
const nodeData = data(node);
if (nodeData && typeof nodeData.handle === 'function') {
internalHandlers.push(nodeData.handle);
}
}
const entry = jQueryFunction(node)[0];
if (entry) {
const entryEvents = entry['$events'];
for (const type in entryEvents) {
const events = entryEvents[type];
for (const key in events) {
if (typeof events[key] === 'function') {
const listener = {handler: events[key], useCapture: true, passive: false, once: false, type: type};
// We don't support removing for old version < 1.4 of jQuery because it doesn't provide API for getting "selector".
eventListeners.push(listener);
}
}
}
if (entry && entry['$handle']) {
internalHandlers.push(entry['$handle']);
}
}
return {eventListeners: eventListeners, internalHandlers: internalHandlers};
}
function jQueryRemove(this: Object|null, selector: string, type: string, handler: () => void): void {
if (!this || !(this instanceof Node)) {
return;
}
const node = this as Node;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const jQuery = (window as any)['jQuery'];
if (!jQuery || !jQuery.fn) {
return;
}
const jQueryFunction = jQuery as (arg0: Node) => {
off: Function,
};
jQueryFunction(node).off(type, selector, handler);
}
}
}
export interface FrameworkEventListenersObject {
eventListeners: SDK.DOMDebuggerModel.EventListener[];
internalHandlers: SDK.RemoteObject.RemoteArray|null;
}
export interface PossibleEventListenerObjectInInspectedPage {
type?: string;
useCapture?: boolean;
passive?: boolean;
once?: boolean;
handler?: SDK.RemoteObject.RemoteObject|null;
remove?: SDK.RemoteObject.RemoteObject|null;
}
export interface EventListenerObjectInInspectedPage {
type: string;
useCapture: boolean;
passive: boolean;
once: boolean;
handler: SDK.RemoteObject.RemoteObject|null;
remove: SDK.RemoteObject.RemoteObject|null;
}
export interface TruncatedEventListenerObjectInInspectedPage {
type?: string;
useCapture?: boolean;
passive?: boolean;
once?: boolean;
} | the_stack |
import { addressToScriptHash, common, ECPoint, UInt160, UInt256 } from '@neo-one/client-common';
import { AnyNameableNode, symbolKey, tsUtils } from '@neo-one/ts-utils';
import { utils } from '@neo-one/utils';
import ts from 'typescript';
import {
isOnlyArray,
isOnlyBoolean,
isOnlyBuffer,
isOnlyMap,
isOnlyNull,
isOnlyNumber,
isOnlySet,
isOnlyString,
isOnlySymbol,
isOnlyUndefined,
} from '../compile/helper/types';
import { Context } from '../Context';
import { DiagnosticCode } from '../DiagnosticCode';
import { DiagnosticMessage } from '../DiagnosticMessage';
import { createMemoized, nodeKey, typeKey } from '../utils';
export interface ErrorDiagnosticOptions {
readonly error?: boolean;
}
export interface DiagnosticOptions extends ErrorDiagnosticOptions {
readonly warning?: boolean;
}
export const DEFAULT_DIAGNOSTIC_OPTIONS = {
error: true,
warning: false,
};
export interface SignatureTypes {
readonly paramDecls: ReadonlyArray<ts.ParameterDeclaration>;
readonly paramTypes: Map<ts.ParameterDeclaration, ts.Type | undefined>;
readonly returnType: ts.Type | undefined;
}
export class AnalysisService {
private readonly memoized = createMemoized();
public constructor(private readonly context: Context) {}
public getFunctionReturnType(
node: ts.SignatureDeclaration,
options: DiagnosticOptions = DEFAULT_DIAGNOSTIC_OPTIONS,
): ts.Type | undefined {
if (ts.isAccessor(node)) {
return this.getType(node);
}
const typeNode = tsUtils.type_.getTypeNode(node) as ts.TypeNode | undefined;
if (typeNode !== undefined) {
return this.getNotAnyType(typeNode, tsUtils.type_.getTypeFromTypeNode(this.context.typeChecker, typeNode));
}
const signatureTypes = this.extractSignature(node, options);
return signatureTypes === undefined ? undefined : signatureTypes.returnType;
}
public extractAllSignatures(
node: ts.Node,
options: DiagnosticOptions = DEFAULT_DIAGNOSTIC_OPTIONS,
): ReadonlyArray<SignatureTypes> {
return this.extractAllSignaturesForType(node, this.getType(node), options);
}
public extractSignature(
node: ts.Node,
options: DiagnosticOptions = DEFAULT_DIAGNOSTIC_OPTIONS,
): SignatureTypes | undefined {
return this.extractSignatureForType(node, this.getType(node), options);
}
public getSignatures(node: ts.CallLikeExpression): ReadonlyArray<ts.Signature> | undefined {
const signature = this.context.typeChecker.getResolvedSignature(node);
if (signature !== undefined && !tsUtils.signature.isFailure(signature)) {
return [signature];
}
const expr = tsUtils.expression.getExpressionForCall(node);
const type = this.getType(expr);
if (type === undefined) {
return undefined;
}
return tsUtils.type_.getCallSignatures(type);
}
public extractAllSignaturesForType(
node: ts.Node,
type: ts.Type | undefined,
options: DiagnosticOptions = DEFAULT_DIAGNOSTIC_OPTIONS,
): ReadonlyArray<SignatureTypes> {
const signatures = type === undefined ? undefined : tsUtils.type_.getCallSignatures(type);
if (signatures === undefined) {
return [];
}
return signatures.map((signature) => this.extractSignatureTypes(node, signature, options)).filter(utils.notNull);
}
public extractSignatureForType(
node: ts.Node,
type: ts.Type | undefined,
options: DiagnosticOptions = DEFAULT_DIAGNOSTIC_OPTIONS,
): SignatureTypes | undefined {
const signatureTypes = this.extractAllSignaturesForType(node, type, options);
if (signatureTypes.length === 0) {
return undefined;
}
if (signatureTypes.length !== 1) {
this.report(options, node, DiagnosticCode.MultipleSignatures, DiagnosticMessage.MultipleSignatures);
return undefined;
}
return signatureTypes[0];
}
public extractSignaturesForCall(
node: ts.CallLikeExpression,
options: DiagnosticOptions = DEFAULT_DIAGNOSTIC_OPTIONS,
): ReadonlyArray<SignatureTypes> | undefined {
const signatures = this.getSignatures(node);
if (signatures === undefined) {
return undefined;
}
return signatures.map((signature) => this.extractSignatureTypes(node, signature, options)).filter(utils.notNull);
}
public extractSignatureTypes(
node: ts.Node,
signature: ts.Signature,
options: DiagnosticOptions = DEFAULT_DIAGNOSTIC_OPTIONS,
): SignatureTypes | undefined {
const params = tsUtils.signature.getParameters(signature);
const paramTypes = params.map((param) => this.getTypeOfSymbol(param, node));
const paramDeclsNullable = params.map((param) => tsUtils.symbol.getValueDeclaration(param));
const nullParamIndex = paramDeclsNullable.indexOf(undefined);
if (nullParamIndex !== -1) {
/* istanbul ignore next */
const nullParam = params[nullParamIndex];
/* istanbul ignore next */
this.report(
options,
node,
DiagnosticCode.Invariant,
DiagnosticMessage.MissingParameterDeclaration,
tsUtils.symbol.getName(nullParam),
);
/* istanbul ignore next */
return undefined;
}
const paramDecls = paramDeclsNullable.filter(utils.notNull).filter(ts.isParameter);
const declToType = new Map<ts.ParameterDeclaration, ts.Type | undefined>();
// tslint:disable-next-line no-loop-statement
for (const [paramDecl, paramType] of utils.zip(paramDecls, paramTypes)) {
declToType.set(paramDecl, paramType);
}
return {
paramDecls,
paramTypes: declToType,
returnType: this.getNotAnyType(node, tsUtils.signature.getReturnType(signature)),
};
}
public extractLiteralAddress(original: ts.Expression): UInt160 | undefined {
return this.memoized('extract-literal-address', nodeKey(original), () =>
this.extractLiteral(
original,
'AddressConstructor',
(value) => {
try {
return common.stringToUInt160(addressToScriptHash(value));
} catch {
return common.stringToUInt160(value);
}
},
common.bufferToUInt160,
),
);
}
public extractLiteralHash256(original: ts.Expression): UInt256 | undefined {
return this.extractLiteral(original, 'Hash256Constructor', common.stringToUInt256, common.bufferToUInt256);
}
public extractLiteralPublicKey(original: ts.Expression): ECPoint | undefined {
return this.extractLiteral(original, 'PublicKeyConstructor', common.stringToECPoint, common.bufferToECPoint);
}
public getType(node: ts.Node, options: ErrorDiagnosticOptions = {}): ts.Type | undefined {
return this.memoized('get-type', nodeKey(node), () =>
this.getNotAnyType(node, tsUtils.type_.getType(this.context.typeChecker, node), options),
);
}
public getTypeOfSymbol(symbol: ts.Symbol | undefined, node: ts.Node): ts.Type | undefined {
if (symbol === undefined) {
return undefined;
}
return this.memoized('get-type-of-symbol', `${symbolKey(symbol)}:${nodeKey(node)}`, () =>
this.getNotAnyType(node, tsUtils.type_.getTypeAtLocation(this.context.typeChecker, symbol, node)),
);
}
public getSymbol(node: ts.Node): ts.Symbol | undefined {
return this.memoized('symbol', nodeKey(node), () => {
const symbol = tsUtils.node.getSymbol(this.context.typeChecker, node);
if (symbol === undefined) {
return undefined;
}
const aliased = tsUtils.symbol.getAliasedSymbol(this.context.typeChecker, symbol);
if (aliased !== undefined) {
return aliased;
}
return symbol;
});
}
public getTypeSymbol(node: ts.Node): ts.Symbol | undefined {
return this.memoized('get-type-symbol', nodeKey(node), () => {
const type = this.getType(node);
return this.getSymbolForType(node, type);
});
}
public getSymbolForType(_node: ts.Node, type: ts.Type | undefined): ts.Symbol | undefined {
if (type === undefined) {
return undefined;
}
return this.memoized('get-symbol-for-type', typeKey(type), () => {
let symbol = tsUtils.type_.getAliasSymbol(type);
if (symbol === undefined) {
symbol = tsUtils.type_.getSymbol(type);
}
if (symbol === undefined) {
return undefined;
}
const aliased = tsUtils.symbol.getAliasedSymbol(this.context.typeChecker, symbol);
if (aliased !== undefined) {
return aliased;
}
return symbol;
});
}
public getNotAnyType(
node: ts.Node,
type: ts.Type | undefined,
{ error = true }: ErrorDiagnosticOptions = {},
): ts.Type | undefined {
if (type !== undefined && tsUtils.type_.isAny(type)) {
if (error && !tsUtils.type_.isErrorType(type)) {
this.context.reportTypeError(node);
}
return undefined;
}
if (type !== undefined) {
const constraintType = tsUtils.type_.getConstraint(type);
if (constraintType !== undefined) {
return constraintType;
}
}
return type;
}
public extractStorageKey(node: ts.Node): string | undefined {
return this.memoized('extract-storage-key', nodeKey(node), () => {
const smartContract = tsUtils.node.getFirstAncestorByTest(node, ts.isClassDeclaration);
if (smartContract === undefined || !this.isSmartContract(smartContract)) {
return undefined;
}
const decl = tsUtils.node.getFirstAncestorByTest(node, ts.isPropertyDeclaration);
if (decl === undefined) {
return undefined;
}
return tsUtils.node.getName(decl);
});
}
public isSmartContract(node: ts.ClassDeclaration): boolean {
return this.memoized('is-smart-contract', nodeKey(node), () => {
const extendsExpr = tsUtils.class_.getExtends(node);
const isSmartContract =
extendsExpr !== undefined &&
this.context.builtins.isValue(tsUtils.expression.getExpression(extendsExpr), 'SmartContract');
if (isSmartContract) {
return true;
}
const baseClasses = tsUtils.class_.getBaseClasses(this.context.typeChecker, node);
if (baseClasses.some((value) => this.context.builtins.isValue(value, 'SmartContract'))) {
return true;
}
const baseClass = tsUtils.class_.getBaseClass(this.context.typeChecker, node);
return baseClass !== undefined && this.isSmartContract(baseClass);
});
}
public isSmartContractNode(node: ts.Node): boolean {
return this.memoized('is-smart-contract-node', nodeKey(node), () => {
const symbol = this.getSymbol(node);
if (symbol === undefined) {
return false;
}
const decls = tsUtils.symbol.getDeclarations(symbol);
if (decls.length === 0) {
return false;
}
const decl = decls[0];
return ts.isClassDeclaration(decl) && this.isSmartContract(decl);
});
}
public getSymbolAndAllInheritedSymbols(node: ts.Node): ReadonlyArray<ts.Symbol> {
return this.memoized('get-symbol-and-all-inherited-symbols', nodeKey(node), () => {
const symbol = this.getSymbol(node);
const symbols = [symbol].filter(utils.notNull);
if (ts.isClassDeclaration(node) || ts.isClassExpression(node) || ts.isInterfaceDeclaration(node)) {
const baseTypes = tsUtils.class_.getBaseTypesFlattened(this.context.typeChecker, node);
return symbols.concat(baseTypes.map((baseType) => this.getSymbolForType(node, baseType)).filter(utils.notNull));
}
return symbols;
});
}
public isValidStorageType(node: ts.Node, type: ts.Type): boolean {
return !tsUtils.type_.hasType(
type,
(tpe) =>
!tsUtils.type_.isOnlyType(
tpe,
(tp) =>
isOnlyUndefined(this.context, node, tp) ||
isOnlyNull(this.context, node, tp) ||
isOnlyBoolean(this.context, node, tp) ||
isOnlyNumber(this.context, node, tp) ||
isOnlyString(this.context, node, tp) ||
isOnlySymbol(this.context, node, tp) ||
isOnlyBuffer(this.context, node, tp) ||
this.isValidStorageArray(node, tp) ||
this.isValidStorageMap(node, tp) ||
this.isValidStorageSet(node, tp),
),
);
}
public findReferencesAsNodes(node: AnyNameableNode | ts.Identifier): ReadonlyArray<ts.Node> {
return this.memoized('find-references-as-nodes', nodeKey(node), () =>
tsUtils.reference
.findReferencesAsNodes(this.context.program, this.context.languageService, node)
.filter((found) => this.context.sourceFiles.has(tsUtils.node.getSourceFile(found))),
);
}
public isSmartContractMixinFunction(node: ts.FunctionDeclaration | ts.FunctionExpression): boolean {
const parameters = tsUtils.parametered.getParameters(node);
if (parameters.length !== 1) {
return false;
}
const signatureTypess = this.extractAllSignatures(node);
if (signatureTypess.length !== 1) {
return false;
}
const signatureTypes = signatureTypess[0];
const firstParam = signatureTypes.paramDecls[0];
const firstParamType = signatureTypes.paramTypes.get(firstParam);
if (firstParamType === undefined || tsUtils.type_.getConstructSignatures(firstParamType).length !== 1) {
return false;
}
const constructSignatureTypes = this.extractSignatureTypes(
firstParam,
tsUtils.type_.getConstructSignatures(firstParamType)[0],
);
if (constructSignatureTypes === undefined) {
return false;
}
const returnTypeSymbol = this.getSymbolForType(firstParam, constructSignatureTypes.returnType);
return returnTypeSymbol !== undefined && returnTypeSymbol === this.context.builtins.getValueSymbol('SmartContract');
}
private isValidStorageArray(node: ts.Node, type: ts.Type): boolean {
if (!isOnlyArray(this.context, node, type)) {
return false;
}
const typeArguments = tsUtils.type_.getTypeArgumentsArray(type);
if (typeArguments.length !== 1) {
return true;
}
return this.isValidStorageType(node, typeArguments[0]);
}
private isValidStorageMap(node: ts.Node, type: ts.Type): boolean {
if (!isOnlyMap(this.context, node, type)) {
return false;
}
const typeArguments = tsUtils.type_.getTypeArgumentsArray(type);
if (typeArguments.length !== 2) {
return true;
}
return this.isValidStorageType(node, typeArguments[0]) && this.isValidStorageType(node, typeArguments[1]);
}
private isValidStorageSet(node: ts.Node, type: ts.Type): boolean {
if (!isOnlySet(this.context, node, type)) {
return false;
}
const typeArguments = tsUtils.type_.getTypeArgumentsArray(type);
if (typeArguments.length !== 1) {
return true;
}
return this.isValidStorageType(node, typeArguments[0]);
}
private extractLiteral<T>(
original: ts.Expression,
name: string,
processText: (value: string) => T,
processBuffer: (value: Buffer) => T,
): T | undefined {
return this.traceIdentifier(original, (node) => {
if (!ts.isCallExpression(node) && !ts.isTaggedTemplateExpression(node)) {
return undefined;
}
const expr = ts.isCallExpression(node) ? tsUtils.expression.getExpression(node) : tsUtils.template.getTag(node);
const symbol = this.getSymbol(expr);
const hash256From = this.context.builtins.getOnlyMemberSymbol(name, 'from');
const bufferFrom = this.context.builtins.getOnlyMemberSymbol('BufferConstructor', 'from');
if (symbol === hash256From) {
const arg = ts.isCallExpression(node)
? (tsUtils.argumented.getArguments(node)[0] as ts.Expression | undefined)
: tsUtils.template.getTemplate(node);
if (
ts.isTaggedTemplateExpression(node) &&
!ts.isNoSubstitutionTemplateLiteral(tsUtils.template.getTemplate(node))
) {
return undefined;
}
if (arg === undefined) {
return undefined;
}
return this.traceIdentifier(arg, (value) => {
if (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value)) {
try {
return processText(tsUtils.literal.getLiteralValue(value));
} catch {
// do nothing
}
}
return undefined;
});
}
if (symbol === bufferFrom && ts.isCallExpression(node)) {
const arg = tsUtils.argumented.getArguments(node)[0] as ts.Expression | undefined;
if (arg === undefined) {
return undefined;
}
return this.traceIdentifier(arg, (value) => {
if (!ts.isStringLiteral(value)) {
return undefined;
}
try {
return processBuffer(Buffer.from(tsUtils.literal.getLiteralValue(value), 'hex'));
} catch {
return undefined;
}
});
}
return undefined;
});
}
private traceIdentifier<T>(
nodeIn: ts.Expression,
extractValue: (value: ts.Expression) => T | undefined,
): T | undefined {
const node = this.unwrapExpression(nodeIn);
if (ts.isIdentifier(node)) {
const symbol = this.getSymbol(node);
if (symbol === undefined) {
return undefined;
}
const decl = tsUtils.symbol.getValueDeclaration(symbol);
if (decl === undefined) {
return undefined;
}
if (!ts.isVariableDeclaration(decl)) {
return undefined;
}
const parent = tsUtils.node.getParent(decl);
if (!ts.isVariableDeclarationList(parent) || !tsUtils.modifier.isConst(parent)) {
return undefined;
}
const initializer = tsUtils.initializer.getInitializer(parent);
if (initializer === undefined) {
return undefined;
}
return this.traceIdentifier(initializer, extractValue);
}
return extractValue(node);
}
private unwrapExpression(node: ts.Expression): ts.Expression {
if (ts.isParenthesizedExpression(node)) {
return tsUtils.expression.getExpression(node);
}
if (ts.isAsExpression(node)) {
return tsUtils.expression.getExpression(node);
}
return node;
}
private report(
options: DiagnosticOptions,
node: ts.Node,
code: DiagnosticCode,
message: DiagnosticMessage,
// tslint:disable-next-line no-any readonly-array
...args: any[]
): void {
if (options.error) {
this.context.reportError(node, code, message, ...args);
} else if (options.warning) {
this.context.reportWarning(node, code, message, ...args);
}
}
} | the_stack |
* @param State The first value, often a Redux root state object
* @param Result The final result returned by the selector
* @param Params All additional arguments passed into the selector
*/
export type Selector<
// The state can be anything
State = any,
// The result will be inferred
Result = unknown,
// There are either 0 params, or N params
Params extends never | readonly any[] = any[]
// If there are 0 params, type the function as just State in, Result out.
// Otherwise, type it as State + Params in, Result out.
> = [Params] extends [never]
? (state: State) => Result
: (state: State, ...params: Params) => Result
/** Selectors generated by Reselect have several additional fields attached: */
export interface OutputSelectorFields<Combiner extends UnknownFunction> {
/** The final function passed to `createSelector` */
resultFunc: Combiner
/** The same function, memoized */
memoizedResultFunc: Combiner
/** Returns the last result calculated by the selector */
lastResult: () => ReturnType<Combiner>
/** An array of the input selectors */
dependencies: SelectorArray
/** Counts the number of times the output has been recalculated */
recomputations: () => number
/** Resets the count of recomputations count to 0 */
resetRecomputations: () => number
}
/** Represents the actual selectors generated by `createSelector`.
* The selector is:
* - "a function that takes this state + params and returns a result"
* - plus the attached additional fields
*/
export type OutputSelector<
S extends SelectorArray,
Result,
Combiner extends UnknownFunction,
Params extends readonly any[] = never // MergeParameters<S>
> = Selector<GetStateFromSelectors<S>, Result, Params> &
OutputSelectorFields<Combiner>
/** A selector that is assumed to have one additional argument, such as
* the props from a React component
*/
export type ParametricSelector<State, Props, Result> = Selector<
State,
Result,
[Props, ...any]
>
/** A generated selector that is assumed to have one additional argument */
export type OutputParametricSelector<
State,
Props,
Result,
Combiner extends UnknownFunction
> = ParametricSelector<State, Props, Result> & OutputSelectorFields<Combiner>
/** An array of input selectors */
export type SelectorArray = ReadonlyArray<Selector>
/** A standard function returning true if two values are considered equal */
export type EqualityFn = (a: any, b: any) => boolean
/*
*
* Reselect Internal Types
*
*/
/** Extracts an array of all return types from all input selectors */
export type SelectorResultArray<Selectors extends SelectorArray> =
ExtractReturnType<Selectors>
/** Determines the combined single "State" type (first arg) from all input selectors */
export type GetStateFromSelectors<S extends SelectorArray> =
MergeParameters<S>[0]
/** Determines the combined "Params" type (all remaining args) from all input selectors */
export type GetParamsFromSelectors<
S extends SelectorArray,
RemainingItems extends readonly unknown[] = Tail<MergeParameters<S>>
// This seems to default to an array containing an empty object, which is
// not meaningful and causes problems with the `Selector/OutputSelector` types.
// Force it to have a meaningful value, or cancel it out.
> = RemainingItems extends [EmptyObject] ? never : RemainingItems
/** Given a set of input selectors, extracts the intersected parameters to determine
* what values can actually be passed to all of the input selectors at once
* WARNING: "you are not expected to understand this" :)
*/
export type MergeParameters<
// The actual array of input selectors
T extends readonly UnknownFunction[],
// Given those selectors, we do several transformations on the types in sequence:
// 1) Extract "the type of parameters" for each input selector, so that we now have
// a tuple of all those parameters
ParamsArrays extends readonly any[][] = ExtractParams<T>,
// 2) Transpose the parameter tuples.
// Originally, we have nested arrays with "all params from input", "from input 2", etc:
// `[ [i1a, i1b, i1c], [i2a, i2b, i2c], [i3a, i3b, i3c] ],
// In order to intersect the params at each index, we need to transpose them so that
// we have "all the first args", "all the second args", and so on:
// `[ [i1a, i2a, i3a], [i1b, i2b, i3b], [i1c, i2c, i3c] ]
// Unfortunately, this step also turns the arrays into a union, and weirder, it is
// a union of all possible combinations for all input functions, so there's duplicates.
TransposedArrays = Transpose<ParamsArrays>,
// 3) Turn the union of arrays back into a nested tuple. Order does not matter here.
TuplifiedArrays extends any[] = TuplifyUnion<TransposedArrays>,
// 4) Find the longest params array out of the ones we have.
// Note that this is actually the _nested_ data we wanted out of the transpose step,
// so it has all the right pieces we need.
LongestParamsArray extends readonly any[] = LongestArray<TuplifiedArrays>
> =
// After all that preparation work, we can actually do parameter extraction.
// These steps work somewhat inside out (jump ahead to the middle):
// 11) Finally, after all that, run a shallow expansion on the values to make the user-visible
// field details more readable when viewing the selector's type in a hover box.
ExpandItems<
// 10) Tuples can have field names attached, and it seems to work better to remove those
RemoveNames<{
// 5) We know the longest params array has N args. Loop over the indices of that array.
// 6) For each index, do a check to ensure that we're _only_ checking numeric indices,
// not any field names for array functions like `slice()`
[index in keyof LongestParamsArray]: LongestParamsArray[index] extends LongestParamsArray[number]
? // 9) Any object types that were intersected may have had
IgnoreInvalidIntersections<
// 8) Then, intersect all of the parameters for this arg together.
IntersectAll<
// 7) Since this is a _nested_ array, extract the right sub-array for this index
LongestParamsArray[index]
>
>
: never
}>
>
/*
*
* Reselect Internal Utility Types
*
*/
/** Any function with arguments */
export type UnknownFunction = (...args: any[]) => any
/** An object with no fields */
type EmptyObject = {
[K in any]: never
}
type IgnoreInvalidIntersections<T> = T extends EmptyObject ? never : T
/** Extract the parameters from all functions as a tuple */
export type ExtractParams<T extends readonly UnknownFunction[]> = {
[index in keyof T]: T[index] extends T[number] ? Parameters<T[index]> : never
}
/** Extract the return type from all functions as a tuple */
export type ExtractReturnType<T extends readonly UnknownFunction[]> = {
[index in keyof T]: T[index] extends T[number] ? ReturnType<T[index]> : never
}
/** Recursively expand all fields in an object for easier reading */
export type ExpandItems<T extends readonly unknown[]> = {
[index in keyof T]: T[index] extends T[number] ? Expand<T[index]> : never
}
/** First item in an array */
export type Head<T> = T extends [any, ...any[]] ? T[0] : never
/** All other items in an array */
export type Tail<A> = A extends [any, ...infer Rest] ? Rest : never
/** Extract only numeric keys from an array type */
export type AllArrayKeys<A extends readonly any[]> = A extends any
? {
[K in keyof A]: K
}[number]
: never
export type List<A = any> = ReadonlyArray<A>
export type Has<U, U1> = [U1] extends [U] ? 1 : 0
/** Select the longer of two arrays */
export type Longest<L extends List, L1 extends List> = L extends unknown
? L1 extends unknown
? { 0: L1; 1: L }[Has<keyof L, keyof L1>]
: never
: never
/** Recurse over a nested array to locate the longest one.
* Acts like a type-level `reduce()`
*/
export type LongestArray<S extends readonly any[][]> =
// If this isn't a tuple, all indices are the same, we can't tell a difference
IsTuple<S> extends '0'
? // so just return the type of the first item
S[0]
: // If there's two nested arrays remaining, compare them
S extends [any[], any[]]
? Longest<S[0], S[1]>
: // If there's more than two, extract their types, treat the remainder as a smaller array
S extends [any[], any[], ...infer Rest]
? // then compare those two, recurse through the smaller array, and compare vs its result
Longest<
Longest<S[0], S[1]>,
Rest extends any[][] ? LongestArray<Rest> : []
>
: // If there's one item left, return it
S extends [any[]]
? S[0]
: never
/** Recursive type for intersecting together all items in a tuple, to determine
* the final parameter type at a given argument index in the generated selector. */
export type IntersectAll<T extends any[]> = IsTuple<T> extends '0'
? T[0]
: _IntersectAll<T>
type IfJustNullish<T, True, False> = [T] extends [undefined | null]
? True
: False
/** Intersect a pair of types together, for use in parameter type calculation.
* This is made much more complex because we need to correctly handle cases
* where a function has fewer parameters and the type is `undefined`, as well as
* optional params or params that have `null` or `undefined` as part of a union.
*
* If the next type by itself is `null` or `undefined`, we exclude it and return
* the other type. Otherwise, intersect them together.
*/
type _IntersectAll<T, R = unknown> = T extends [infer First, ...infer Rest]
? _IntersectAll<Rest, IfJustNullish<First, R, R & First>>
: R
/*
*
* External/Copied Utility Types
*
*/
/** The infamous "convert a union type to an intersection type" hack
* Source: https://github.com/sindresorhus/type-fest/blob/main/source/union-to-intersection.d.ts
* Reference: https://github.com/microsoft/TypeScript/issues/29594
*/
export type UnionToIntersection<Union> = (
// `extends unknown` is always going to be the case and is used to convert the
// `Union` into a [distributive conditional
// type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
Union extends unknown
? // The union type is used as the only argument to a function since the union
// of function arguments is an intersection.
(distributedUnion: Union) => void
: // This won't happen.
never
// Infer the `Intersection` type since TypeScript represents the positional
// arguments of unions of functions as an intersection of the union.
) extends (mergedIntersection: infer Intersection) => void
? Intersection
: never
/**
* Removes field names from a tuple
* Source: https://stackoverflow.com/a/63571175/62937
*/
type RemoveNames<T extends readonly any[]> = [any, ...T] extends [
any,
...infer U
]
? U
: never
/**
* Assorted util types for type-level conditional logic
* Source: https://github.com/KiaraGrouwstra/typical
*/
export type Bool = '0' | '1'
export type Obj<T> = { [k: string]: T }
export type And<A extends Bool, B extends Bool> = ({
1: { 1: '1' } & Obj<'0'>
} & Obj<Obj<'0'>>)[A][B]
export type Matches<V, T> = V extends T ? '1' : '0'
export type IsArrayType<T> = Matches<T, any[]>
export type Not<T extends Bool> = { '1': '0'; '0': '1' }[T]
export type InstanceOf<V, T> = And<Matches<V, T>, Not<Matches<T, V>>>
export type IsTuple<T extends { length: number }> = And<
IsArrayType<T>,
InstanceOf<T['length'], number>
>
/**
* Code to convert a union of values into a tuple.
* Source: https://stackoverflow.com/a/55128956/62937
*/
type Push<T extends any[], V> = [...T, V]
type LastOf<T> = UnionToIntersection<
T extends any ? () => T : never
> extends () => infer R
? R
: never
// TS4.1+
type TuplifyUnion<
T,
L = LastOf<T>,
N = [T] extends [never] ? true : false
> = true extends N ? [] : Push<TuplifyUnion<Exclude<T, L>>, L>
/**
* Converts "the values of an object" into a tuple, like a type-level `Object.values()`
* Source: https://stackoverflow.com/a/68695508/62937
*/
export type ObjValueTuple<
T,
KS extends any[] = TuplifyUnion<keyof T>,
R extends any[] = []
> = KS extends [infer K, ...infer KT]
? ObjValueTuple<T, KT, [...R, T[K & keyof T]]>
: R
/**
* Transposes nested arrays
* Source: https://stackoverflow.com/a/66303933/62937
*/
type Transpose<T> = T[Extract<
keyof T,
T extends readonly any[] ? number : unknown
>] extends infer V
? {
[K in keyof V]: {
[L in keyof T]: K extends keyof T[L] ? T[L][K] : undefined
}
}
: never
/** Utility type to infer the type of "all params of a function except the first", so we can determine what arguments a memoize function accepts */
export type DropFirst<T extends unknown[]> = T extends [unknown, ...infer U]
? U
: never
/**
* Expand an item a single level, or recursively.
* Source: https://stackoverflow.com/a/69288824/62937
*/
export type Expand<T> = T extends (...args: infer A) => infer R
? (...args: Expand<A>) => Expand<R>
: T extends infer O
? { [K in keyof O]: O[K] }
: never
export type ExpandRecursively<T> = T extends (...args: infer A) => infer R
? (...args: ExpandRecursively<A>) => ExpandRecursively<R>
: T extends object
? T extends infer O
? { [K in keyof O]: ExpandRecursively<O[K]> }
: never
: T
type Identity<T> = T
/**
* Another form of type value expansion
* Source: https://github.com/microsoft/TypeScript/issues/35247
*/
export type Mapped<T> = Identity<{ [k in keyof T]: T[k] }>
/**
* Fully expand a type, deeply
* Source: https://github.com/millsp/ts-toolbelt (`Any.Compute`)
*/
type ComputeDeep<A, Seen = never> = A extends BuiltIn
? A
: If2<
Has<Seen, A>,
A,
A extends Array<any>
? A extends Array<Record<Key, any>>
? Array<
{
[K in keyof A[number]]: ComputeDeep<A[number][K], A | Seen>
} & unknown
>
: A
: A extends ReadonlyArray<any>
? A extends ReadonlyArray<Record<Key, any>>
? ReadonlyArray<
{
[K in keyof A[number]]: ComputeDeep<A[number][K], A | Seen>
} & unknown
>
: A
: { [K in keyof A]: ComputeDeep<A[K], A | Seen> } & unknown
>
export type If2<B extends Boolean2, Then, Else = never> = B extends 1
? Then
: Else
export type Boolean2 = 0 | 1
export type Key = string | number | symbol
export type BuiltIn =
| Function
| Error
| Date
| { readonly [Symbol.toStringTag]: string }
| RegExp
| Generator | the_stack |
█████████████████████████████████
█████████████████████████████████
████ ▄▄▄▄▄ █▀▀ ██ ██ ▄▄▄▄▄ ████
████ █ █ █▄▀██▀█ ▄█ █ █ ████
████ █▄▄▄█ █ ▄ █ ▀▄ ▄█ █▄▄▄█ ████
████▄▄▄▄▄▄▄█ █ ▀▄█ █▄█▄▄▄▄▄▄▄████
████▄▄▀▄▀█▄▄▀▀█ ██▄▄▀ ▄▄█▄▄▀████
████ █ ▄▄▄▄█▄▀▀ ▀ █ █▀ ██▄▄████
█████▀█▀ ▄▄██▄ █▀▄█▄▄ ▀█ ▀▄ ████
████▄▀█▀██▄██ █▄▄█ ▄██▀▀▄▀▄████
████▄▄▄▄▄█▄█▀ ▀█ ▀ ▄▄▄ █▀████
████ ▄▄▄▄▄ █▄▀█▄ █ ▄ █▄█ ▀▀ ▄████
████ █ █ █▀▀█▀██▀█▄▄▄ █▀█▄████
████ █▄▄▄█ █▀ ▄███▀▄▀▀▀█▄ ▄█▄████
████▄▄▄▄▄▄▄█▄███▄██▄▄▄█▄███▄▄████
█████████████████████████████████
█████████████████████████████████
*/
const THICK = 100
const gfx = cc['gfx'];
const { ccclass, property, menu, requireComponent } = cc._decorator;
@ccclass
@menu("i18n:MAIN_MENU.component.physics/Collider/PolygonEX-lamyoung.com")
@requireComponent(cc.RigidBody)
export default class PhysicsPolygonColliderEx extends cc.Component {
@property(cc.MeshRenderer)
meshRenderer: cc.MeshRenderer = null;
public get polys() {
return this._polys.map((v) => { return this._convertClipperPathToVecArray(v) });
}
private _polys: { X: number, Y: number }[][] = [];
private _physicsPolygonColliders: cc.PhysicsPolygonCollider[] = [];
init(polys: cc.Vec2[][]) {
this._polys = polys.map((v) => { return this._convertVecArrayToClipperPath(v) });
this._commands = [];
}
private _commands: { name: string, params: any[] }[] = [];
pushCommand(name: string, params: any[]) {
this._commands.push({ name, params });
}
polyDifference(poly: cc.Vec2[], ctx?: cc.Graphics) {
// if (poly.length < 3) return;
// 计算新的多边形
const cpr = new ClipperLib.Clipper(ClipperLib.Clipper.ioStrictlySimple); //ClipperLib.Clipper.ioStrictlySimple | ClipperLib.Clipper.ioPreserveCollinear
// cpr.PreserveCollinear = true;
const subj_paths = this._polys;
const clip_paths = [this._convertVecArrayToClipperPath(poly)]
cpr.AddPaths(subj_paths, ClipperLib.PolyType.ptSubject, true);
cpr.AddPaths(clip_paths, ClipperLib.PolyType.ptClip, true);
const subject_fillType = ClipperLib.PolyFillType.pftEvenOdd;
const clip_fillType = ClipperLib.PolyFillType.pftEvenOdd;
const solution_polytree = new ClipperLib.PolyTree();
cpr.Execute(ClipperLib.ClipType.ctDifference, solution_polytree, subject_fillType, clip_fillType);
const solution_expolygons = ClipperLib.JS.PolyTreeToExPolygons(solution_polytree);
this._polys = ClipperLib.Clipper.PolyTreeToPaths(solution_polytree);
// cc.log(solution_expolygons);
// 将多边形分割成三角形 并绘制出来
ctx && ctx.clear(true);
let _physicsPolygonColliders_count = 0;
for (const expolygon of solution_expolygons) {
// const outers = ClipperLib.Clipper.SimplifyPolygon(expolygon.outer,ClipperLib.PolyFillType.pftEvenOdd);
// cc.log(outer,"outer",expolygon.outer)
const countor = this._convertClipperPathToPoly2triPoint(expolygon.outer);
if (countor.length < 2) continue;
const swctx = new poly2tri.SweepContext(countor, { cloneArrays: true });
// const exclude = countor;
const holes = expolygon.holes.map(h => { return this._convertClipperPathToPoly2triPoint(h, countor) });
try {
// 防止 addhole 失败 使用try
swctx.addHoles(holes);
swctx.triangulate();
const triangles = swctx.getTriangles();
// cc.log('triangles', triangles);
for (const tri of triangles) {
// 逐一处理三角形
let c = this._physicsPolygonColliders[_physicsPolygonColliders_count];
if (!c) {
c = this.addComponent(cc.PhysicsPolygonCollider);
c.friction = 0;
c.restitution = 0;
this._physicsPolygonColliders[_physicsPolygonColliders_count] = c;
}
c.points = tri.getPoints().map((v, i) => {
if (ctx) {
if (i === 0) ctx.moveTo(v.x, v.y);
else ctx.lineTo(v.x, v.y);
}
return cc.v2(v.x, v.y)
});
c.apply();
_physicsPolygonColliders_count++;
if (ctx) {
ctx.close();
ctx.fill();
}
}
} catch (e) {
console.error('polyDifference poly2tri error', _physicsPolygonColliders_count, expolygon);
console.error(e);
continue;
}
}
this._physicsPolygonColliders.slice(_physicsPolygonColliders_count).forEach((v => {
if (v.points.length) {
v.points.length = 0;
v.apply();
}
}));
// 绘制底层 mesh
const arr2 = this._polys.map((v) => { return this._convertClipperPathToVecArray(v) });
const poly_tri_arr = [];
const c_count = arr2.length;
for (let k = 0; k < c_count; k++) {
let tmpArr = arr2[k];
let tmpArr2 = [];
for (let k2 = 0; k2 < tmpArr.length; k2++) {
let aa = tmpArr[k2];
tmpArr2.push([aa.x, aa.y]);
}
poly_tri_arr.push(tmpArr2);
}
this.addMesh(poly_tri_arr);
}
addMesh(tri) {
let allPoints = [];
let indexArr = [];
let uvIndexArr = [];
let uvType = 0;
let uvupTypeArr = [cc.v2(0, 0), cc.v2(0, 1), cc.v2(1, 0), cc.v2(1, 1)]
let uvDownTypeArr = [cc.v2(1, 1), cc.v2(0, 0), cc.v2(0, 1), cc.v2(1, 0)]
let colorIndex = [];
// console.log("****2this._regions.length:"+tri.length);
for (let i = 0; i < tri.length; i++) {
let singleParr = [].concat(tri[i]);
indexArr[i] = [];
let length = singleParr.length;
for (let j = 0; j < length; j++) {
if (singleParr[j]) {
allPoints.push(cc.v3(singleParr[j][0], singleParr[j][1], 0))
indexArr[i].push(allPoints.length - 1)
uvIndexArr.push(uvupTypeArr[uvType]);
uvType = uvType >= 3 ? 0 : uvType + 1;
colorIndex.push(cc.Color.WHITE)
}
}
}
uvType = 0;
let iLength = allPoints.length;
for (let i = 0; i < iLength; i++) {
allPoints[i + iLength] = cc.v3(allPoints[i].x, allPoints[i].y, -THICK)
uvIndexArr.push(uvDownTypeArr[uvType]);
uvType = uvType >= 3 ? 0 : uvType + 1;
colorIndex.push(cc.Color.WHITE)
}
const vfmtPosColor = new gfx.VertexFormat([
{ name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 },
{ name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 },
{ name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true },
]);
let mesh = new cc.Mesh();
mesh.init(vfmtPosColor, allPoints.length, true);
this.meshRenderer.mesh = mesh;
mesh.setVertices(gfx.ATTR_POSITION, allPoints);
mesh.setVertices(gfx.ATTR_COLOR, colorIndex);
mesh.setVertices(gfx.ATTR_UV0, uvIndexArr);
let indices = this.conmuteIndices(indexArr, iLength)
mesh.setIndices(indices);
}
conmuteIndices(indexArr, length) {
let indicesarr = [];
for (let i = 0; i < indexArr.length; i++) {
let arr = indexArr[i];
for (let j = 0; j < arr.length; j++) {
let p1, p2, p3, p4;
if (j < arr.length - 1) {
p1 = arr[j];
p2 = arr[j + 1];
p3 = arr[j] + length;
p4 = arr[j + 1] + length;
} else {
p1 = arr[j];
p2 = arr[0];
p3 = arr[j] + length;
p4 = arr[0] + length;
}
indicesarr.push(p1, p2, p4, p3, p4, p1)
}
}
return indicesarr;
}
lateUpdate(dt: number) {
if (this._commands.length) {
// 每帧执行命令队列
for (let index = 0; index < Math.ceil(this._commands.length / 2 + 0.5); index++) {
const cmd = this._commands.shift();
if (cmd)
this[cmd.name](...cmd.params);
else
break;
}
}
}
private _convertVecArrayToClipperPath(poly: cc.Vec2[]) {
return poly.map((p) => { return { X: p.x, Y: p.y } });
}
private _convertClipperPathToVecArray(poly: { X: number, Y: number }[]) {
return poly.map((p) => { return cc.v2(p.X, p.Y) });
}
private _convertClipperPathToPoly2triPoint(poly: { X: number, Y: number }[], exclude: poly2tri.Point[] = []): poly2tri.Point[] {
// return poly.map((p) => { return new poly2tri.Point(p.X, p.Y) });
const newPos: poly2tri.Point[] = [];
poly.forEach((p, i) => {
const p_now = new poly2tri.Point(p.X, p.Y)
const isIn = exclude.some((e_p) => {
if (e_p.equals(p_now)) {
return true;
}
})
if (!isIn) {
newPos.push(p_now);
exclude.push(p_now);
}
})
if (newPos.length > 2)
return newPos;
else
return [];
}
}
// 欢迎关注微信公众号[白玉无冰]
// qq 交流群 859642112
/**
█████████████████████████████████████
█████████████████████████████████████
████ ▄▄▄▄▄ █▀█ █▄██▀▄ ▄▄██ ▄▄▄▄▄ ████
████ █ █ █▀▀▀█ ▀▄▀▀▀█▄▀█ █ █ ████
████ █▄▄▄█ █▀ █▀▀▀ ▀▄▄ ▄ █ █▄▄▄█ ████
████▄▄▄▄▄▄▄█▄▀ ▀▄█ ▀▄█▄▀ █▄▄▄▄▄▄▄████
████▄▄ ▄▀▄▄ ▄▀▄▀▀▄▄▄ █ █ ▀ ▀▄█▄▀████
████▀ ▄ █▄█▀█▄█▀█ ▀▄ █ ▀ ▄▄██▀█████
████ ▄▀▄▄▀▄ █▄▄█▄ ▀▄▀ ▀ ▀ ▀▀▀▄ █▀████
████▀ ██ ▀▄ ▄██ ▄█▀▄ ██▀ ▀ █▄█▄▀█████
████ ▄██▄▀ █▀▄▀▄▀▄▄▄▄ ▀█▀ ▀▀ █▀████
████ █▄ █ ▄ █▀ █▀▄█▄▄▄▄▀▄▄█▄▄▄▄▀█████
████▄█▄█▄█▄█▀ ▄█▄ ▀▄██ ▄▄▄ ▀ ████
████ ▄▄▄▄▄ █▄██ ▄█▀ ▄ █▄█ ▄▀█████
████ █ █ █ ▄█▄ ▀ ▀▀██ ▄▄▄▄ ▄▀ ████
████ █▄▄▄█ █ ▄▄▀ ▄█▄█▄█▄ ▀▄ ▄ █████
████▄▄▄▄▄▄▄█▄██▄▄██▄▄▄█████▄▄█▄██████
█████████████████████████████████████
█████████████████████████████████████
*/ | the_stack |
import { PerspectiveCamera, Vector4, MathUtils } from 'three';
import { Tween, Easing } from '@tweenjs/tween.js';
import { getMaxFullScreenDepthForPlane, toAbsolutePosition } from './background-camera-utils';
import { PlaneMesh } from './background';
import { TransitionConfig, LoopableTransitionConfig } from './transition';
import { clamp } from './utils';
interface CameraPosition {
// the x postion of the camera from 0 to 1, or the left to right-most position respectively.
x?: number;
// the y position of the camera from 0 to 1, or the top to bottom-most position respectively.
y?: number;
// the z position of the camera from 0 to 1, or the closest to farther position respectively.
z?: number;
}
interface CameraPositionWithRotation extends CameraPosition {
// the z-axis rotation of the camera in degrees.
zr?: number;
}
type CameraOffset = CameraPositionWithRotation;
interface CameraPositionTween {
x: number,
y: number,
z: number
}
interface CameraRotationTween {
zr: number;
}
interface CameraSwayTween {
offsetX: number;
offsetY: number;
offsetZ: number;
offsetZR: number;
}
// Max camera zoom range - this ensures the camera doesn't exceed the near plane of its frustum.
const CameraZoomRange = 0.9;
class BackgroundCamera {
private _plane: PlaneMesh;
public readonly camera: PerspectiveCamera;
// the relative position of the camera
// NOTE: the w component is used as the z-axis rotation component of the vector (also aliased as zr)
private readonly _position: Vector4 = new Vector4(0, 0, 1, 0);
private readonly _positionOffset: Vector4 = new Vector4(0, 0, 0, 0);
private readonly _positionWithOffset: Vector4 = this._position.clone(); // cached for re-use per render frame
private _positionTransition: Tween<CameraPositionTween> = new Tween({ x: 0, y: 0, z: 0 });
private _rotationTransition: Tween<CameraRotationTween> = new Tween({ zr: 0 });
private readonly _swayOffset = new Vector4(0, 0, 0, 0);
private _swayTransition: Tween<CameraSwayTween> = new Tween({ offsetX: 0, offsetY: 0, offsetZ: 0, offsetZR: 0 });
/**
* Constructs a BackgroundCamera using a Background's plane.
* @param {PlaneMesh} plane - a three.js plane mesh representing the background.
* @param {Number} width - the width of the camera.
* @param {Number} height - the height of the camera.
*/
constructor(plane: PlaneMesh, width: number, height: number) {
this._plane = plane;
this.camera = new PerspectiveCamera(35, width / height, 0.001);
}
/**
* Returns the current position of the camera.
* @returns CameraPositionWithRotation
*/
get position(): CameraPositionWithRotation {
// NOTE: the relative camera position is the base position and does NOT include offsets (e.g sway or offset).
const { x, y, z, w: zr } = this._position;
return { x, y, z, zr };
}
/**
* Returns the current position offset of the camera.
* @returns CameraPositionWithRotation
*/
get positionOffset(): CameraPositionWithRotation {
const { x, y, z, w: zr } = this._positionOffset;
return { x, y, z, zr };
}
/**
* Returns whether the camera is currently moving.
* @returns boolean
*/
isMoving(): boolean {
return this._positionTransition.isPlaying();
}
/**
* Returns whether the camera is currently rotating.
* @returns boolean
*/
isRotating(): boolean {
return this._rotationTransition.isPlaying();
}
/**
* Returns whether the camera is currently swaying.
* @returns boolean
*/
isSwaying(): boolean {
return this._swayTransition.isPlaying();
}
/**
* Sets the size of the camera.
* @param {number} width
* @param {number} height
*/
setSize(width: number, height: number): void {
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
}
/**
* Offsets the camera position.
* @param {CameraPositionWithRotation} offset - the offset to apply.
*/
offset(offset: CameraPositionWithRotation): void {
const { x = 0, y = 0, z = 0, zr = 0 } = offset;
this._positionOffset.set(x, y, z, zr);
}
/**
* Sways the camera around its position. Cancels any in-progress sways.
* @param {CameraOffset | boolean} offset - the offset to sway on each axis in relative units from 0 to 1.
* The rotation offset (zr) must be specified in units of degrees.
* The x/y offsets should be set based off a z of 1 and will be scaled down appropriately based on the camera's current z position.
* If a boolean is passed in instead then the sway will either continue or stop based on the value.
* @param {LoopableTransitionConfig} transition - optional configuration for a transition.
*/
sway(offset: CameraOffset | boolean, transition: LoopableTransitionConfig = {}): void {
if (typeof offset === 'boolean') {
if (!offset) {
this._swayTransition.stop();
}
return;
}
this._swayTransition.stop();
const {
loop = false,
duration = 0,
delay = 0,
easing = Easing.Linear.None,
onInit = () => ({}),
onStart = () => ({}),
onUpdate = () => ({}),
onComplete = () => ({}),
onStop = () => ({}),
} = transition;
const { x = 0, y = 0, z = 0, zr = 0 } = offset;
const zrInRadians = MathUtils.degToRad(zr);
// calculate offsets within range of available positions
// NOTE: this doesn't guarantee that sway values won't be clamped since position and offsets can change over time
// this is still useful enough however to ensure that we won't use sway values that will obviously get clamped
const xPosition = clamp(this._position.x + this._positionOffset.x, 0, 1);
const xMin = Math.max(0, xPosition - x);
const xMax = Math.min(1, xPosition + x);
const xRange = xMax - xMin;
const xOffset = (xMin + xRange * Math.random()) - xPosition;
const yPosition = clamp(this._position.y + this._positionOffset.y, 0, 1);
const yMin = Math.max(0, yPosition - y);
const yMax = Math.min(1, yPosition + y);
const yRange = yMax - yMin;
const yOffset = (yMin + yRange * Math.random()) - yPosition;
const zPosition = clamp(this._position.z + this._positionOffset.z, 0, 1);
const zMin = Math.max(0, zPosition - z);
const zMax = Math.min(1, zPosition + z);
const zRange = zMax - zMin;
const zOffset = (zMin + zRange * Math.random()) - zPosition;
onInit();
this._swayTransition = new Tween({
offsetX: this._swayOffset.x,
offsetY: this._swayOffset.y,
offsetZ: this._swayOffset.z,
offsetZR: this._swayOffset.w,
})
.to({
offsetX: xOffset,
offsetY: yOffset,
offsetZ: zOffset,
offsetZR: -zrInRadians + Math.random() * zrInRadians * 2,
}, duration * 1000)
.easing(easing)
.onStart(onStart)
.onUpdate(({ offsetX, offsetY, offsetZ, offsetZR }) => {
this._swayOffset.set(offsetX, offsetY, offsetZ, offsetZR);
onUpdate();
})
.onComplete(() => {
if (loop) {
this.sway(offset, transition);
}
onComplete();
})
.onStop(onStop)
.delay(delay * 1000)
.start();
}
/**
* Rotates the camera on its z-axis. Cancels any in-progress rotations.
* @param {number | boolean} angle - the angle to rotate in degrees.
* If a boolean is passed in instead then the rotation will either continue or stop based on the value.
* @param {TransitionConfig} transition - optional configuration for a transition.
*/
rotate(angle: number | boolean, transition: TransitionConfig = {}): void {
if (typeof angle === 'boolean') {
if (!angle) {
this._rotationTransition.stop();
}
return;
}
this._rotationTransition.stop();
const {
duration = 0,
delay = 0,
easing = Easing.Linear.None,
onInit = () => ({}),
onStart = () => ({}),
onUpdate = () => ({}),
onComplete = () => ({}),
onStop = () => ({}),
} = transition;
const angleInRadians = MathUtils.degToRad(angle);
onInit();
if (duration > 0 || delay > 0) {
this._rotationTransition = new Tween({ zr: this._position.w })
.to({ zr: angleInRadians }, duration * 1000)
.easing(easing)
.onStart(onStart)
.onUpdate(({ zr }) => {
this._position.set(this._position.x, this._position.y, this._position.z, zr);
onUpdate();
})
.onComplete(onComplete)
.onStop(onStop)
.delay(delay * 1000)
.start();
} else {
this._position.set(this._position.x, this._position.y, this._position.z, angleInRadians);
}
}
/**
* Moves the camera to a relative position on the background. Cancels any in-progress moves.
* @param {CameraPosition | boolean} position - the position to move towards on each axis in relative units from 0 to 1.
* If a boolean is passed in instead then the move will either continue or stop based on the value.
* @param {TransitionConfig} transition - optional configuration for a transition.
*/
move(position: CameraPosition | boolean, transition: TransitionConfig = {}): void {
if (typeof position === 'boolean') {
if (!position) {
this._positionTransition.stop();
}
return;
}
this._positionTransition.stop();
const { x: currentX, y: currentY, z: currentZ } = this._position;
const { x = currentX, y = currentY, z = currentZ } = position;
const {
duration = 0,
delay = 0,
easing = Easing.Linear.None,
onInit = () => ({}),
onStart = () => ({}),
onUpdate = () => ({}),
onComplete = () => ({}),
onStop = () => ({}),
} = transition;
onInit();
if (duration > 0 || delay > 0) {
this._positionTransition = new Tween({ x: currentX, y: currentY, z: currentZ })
.to({ x, y, z }, duration * 1000)
.easing(easing)
.onStart(onStart)
.onUpdate(({ x, y, z }) => {
this._position.set(x, y, z, this._position.w);
onUpdate();
})
.onComplete(onComplete)
.onStop(onStop)
.delay(delay * 1000)
.start();
} else {
this._position.set(x, y, z, this._position.w);
}
}
/**
* Updates the camera position. Should be called on every render frame.
*/
update(): void {
// scale sway based on the current depth to provide a consistent distance regardless of depth
const swayScale = this._positionWithOffset.z / getMaxFullScreenDepthForPlane(this._plane, this.camera, this.camera.rotation.z);
this._positionWithOffset.set(
clamp(this._position.x + this._positionOffset.x + this._swayOffset.x * swayScale, 0, 1),
clamp(this._position.y + this._positionOffset.y + this._swayOffset.y * swayScale, 0, 1),
clamp((this._position.z + this._positionOffset.z + this._swayOffset.z) * CameraZoomRange + (1.0 - CameraZoomRange), 0, 1),
this._position.w + MathUtils.degToRad(this._positionOffset.w) + this._swayOffset.w,
);
const { x: absoluteX, y: absoluteY, z: absoluteDepth } = toAbsolutePosition(
this._plane,
this.camera,
this._positionWithOffset,
);
this.camera.position.set(absoluteX, absoluteY, absoluteDepth);
this.camera.rotation.z = this._position.w + MathUtils.degToRad(this._positionOffset.w) + this._swayOffset.w;
}
/**
* Disposes this object. Call when this object is no longer needed, otherwise leaks may occur.
*/
dispose(): void {
this.sway(false);
this.move(false);
this.rotate(false);
}
}
export {
CameraPosition,
CameraPositionWithRotation,
CameraOffset,
BackgroundCamera,
};
export default BackgroundCamera; | the_stack |
import * as d3 from 'd3';
import { Query } from '../query';
export interface Link {
/**
* Get the text representation of a link.
*
* @param link the link to get the text representation.
* @returns the text representation of the link.
*/
getTextValue: (link: any) => string;
/**
* Return the color to use on links and relation donut segments.
*
*
* Return null or undefined
* @param link
* @param element
* @param attribute
* @return color
*/
getColor: (link: any, element: SVGGElement, attribute: string) => string;
/**
*
* @param link
* @param element
* @return css class
*/
getCSSClass: (link: any, element: SVGGElement) => string;
/**
*
* @param link
*/
getDistance: (link: any) => number;
/**
* Get the semantic text representation of a link.
*
* @param link the link to get the semantic text representation.
* @returns the semantic text representation of the link.
*/
getSemanticValue: (link: any) => string;
}
export interface Taxonomy {
/**
* Get the text representation of a taxonomy.
*
* @param label the label used for the taxonomy.
* @returns the text representation of the taxonomy.
*/
getTextValue: (label: string) => string;
/**
*
* @param label
* @param element
* @return css class
*/
getCSSClass: (label: string, element: SVGGElement) => string;
}
export interface Node {
/**
* Defines whether this label can be used as root element of the graph
* query builder.
* This property is also used to determine whether the label can be
* displayed in the taxonomy filter.
*
* The default value is true.
*/
isSearchable: boolean;
/**
* Defines whether this label will automatically expend its relations
* when displayed on graph.
* If set to true, once displayed additional request will be sent on
* the database to retrieve its relations.
*
* The default value is false.
*/
autoExpandRelations: boolean;
/**
* Defines whether this label will automatically load its available
* data displayed on graph.
* If set to true, once displayed additional request will be sent on
* the database to retrieve its possible values.
*
* The default value is false.
*/
isAutoLoadValue: boolean;
/**
* Defines the list of attribute to return for node of this label.
* All the attributes listed here will be added in generated cypher
* queries and available in result list and in node provider's
* functions.
*
* The default value contains only the Neo4j internal id.
* This id is used by default because it is a convenient way to identify
* a node when nothing is known about its attributes.
* But you should really consider using your application attributes
* instead, it is a bad practice to rely on this attribute.
*/
returnAttributes: any[];
/**
* Defines the attribute used to order the value displayed on node.
*
* Default value is "count" attribute.
*/
valueOrderByAttribute: string;
/**
* Defines whether the value query order by is ascending, if false order
* by will be descending.
*
* Default value is false (descending)
*/
isValueOrderAscending: boolean;
/**
* Defines the attributes used to order the results.
* It can be an attribute name or a list of attribute names.
*
* Default value is "null" to disable order by.
*/
resultOrderByAttribute: null | string;
/**
* Defines whether the result query order by is ascending, if false
* order by will be descending.
* It can be a boolean value or a list of boolean to match the resultOrderByAttribute.
* If size of isResultOrderAscending < size of resultOrderByAttribute last value is used.
*
* Default value is true (ascending)
*/
isResultOrderAscending: boolean;
/**
* Defines the attribute of the node to use in query constraint for
* nodes of this label.
* This attribute is used in the generated cypher query to build the
* constraints with selected values.
*
* The default value is the Neo4j internal id.
* This id is used by default because it is a convenient way to
* identify a node when nothing is known about its attributes.
* But you should really consider using your application attributes
* instead, it is a bad practice to rely on this attribute.
*/
constraintAttribute: Query.NEO4J_INTERNAL_ID;
/**
* Defines the attribute of the node to use by default to display the node.
* This attribute must be present in returnAttributes list.
*
* The default value is undefined.
* If undefined the first attribute of the returnAttributes will be used or
* constraintAttribute if the list is empty.
*/
displayAttribute: undefined | any[];
/**
* Return the list of predefined constraints to add for the given label.
* These constraints will be added in every generated Cypher query.
*
* For example if the returned list contain ["$identifier.born > 1976"]
* for "Person" nodes everywhere in popoto.js the generated Cypher
* query will add the constraint "WHERE person.born > 1976"
*
* @returns
*/
getPredefinedConstraints: any[];
/**
* Filters the query generated to retrieve the queries.
*
* @param initialQuery contains the query as an object structure.
* @returns filtered result query
*/
filterResultQuery: (initialQuery: any) => typeof initialQuery;
/**********************************************************************
* Node specific parameters:
*
* These attributes are specific to nodes (in graph or query viewer)
* for a given label.
* But they can be customized for nodes of the same label.
* The parameters are defined by a function that will be called with
* the node as parameter.
* In this function the node internal attributes can be used to
* customize the value to return.
**********************************************************************/
/**
* Function returning the display type of a node.
* This type defines how the node will be drawn in the graph.
*
* The result must be one of the following values:
*
* provider.node.DisplayTypes.IMAGE
* In this case the node will be drawn as an image and "getImagePath"
* function is required to return the node image path.
*
* provider.node.DisplayTypes.SVG
* In this case the node will be drawn as SVG paths and "getSVGPaths"
*
* provider.node.DisplayTypes.TEXT
* In this case the node will be drawn as a simple circle.
*
* Default value is TEXT.
*
* @param node the node to extract its type.
* @returns one value from provider.node.DisplayTypes
*/
getDisplayType: (node: Node) => number;
/**
* Function defining the size of the node in graph.
*
* The size define the radius of the circle defining the node.
* other elements (menu, counts...) will scale on this size.
*
* Default value is 50.
*
* @param node
*/
getSize: (node: Node) => number;
/**
* Return a color for the node.
*
* @param node
* @returns node's color
*/
getColor: (node: Node) => string;
/**
* Generate a CSS class for the node depending on its type.
*
* @param node
* @param element
* @return string
*/
getCSSClass: (node: Node, element: SVGGElement) => string;
/**
* Function defining whether the node is a group node.
* In this case no count are displayed and no value can be selected on
* the node.
*
* Default value is false.
*/
getIsGroup: (node: Node) => boolean;
/**
* Function defining whether the node text representation must be
* displayed on graph.
* If true the value returned for getTextValue on node will be displayed
* on graph.
*
* This text will be added in addition to the getDisplayType
* representation.
* It can be displayed on all type of node display, images, SVG or text.
*
* Default value is true
*
* @param node the node to display on graph.
* @returns true if text must be displayed on graph for the
* node.
*/
getIsTextDisplayed: (node: Node) => boolean;
/**
* Function used to return the text representation of a node.
*
* The default behavior is to return the label of the node
* or the value of constraint attribute of the node if it contains
* value.
*
* The returned value is truncated using
* graph.node.NODE_MAX_CHARS property.
*
* @param node the node to represent as text.
* @param maxLength used to truncate the text.
* @returns the text representation of the node.
*/
getTextValue: (node: Node, maxLength: number) => string;
/**
* Function used to return a descriptive text representation of a link.
* This representation should be more complete than getTextValue and can
* contain semantic data.
* This function is used for example to generate the label in the query
* viewer.
*
* The default behavior is to return the getTextValue not truncated.
*
* @param node the node to represent as text.
* @returns the text semantic representation of the node.
*/
getSemanticValue: (node: Node) => string;
/**
* Function returning the image file path to use for a node.
* This function is only used for provider.node.DisplayTypes.IMAGE
* type nodes.
*
* @param node
* @returns image paths
*/
getImagePath: (node: Node) => string;
/**
* Function returning a array of path objects to display in the node.
*
* @param node
* @returns svg paths
*/
getSVGPaths: (node: Node) => any[];
/**
* Function returning the image width of the node.
* This function is only used for provider.node.DisplayTypes.IMAGE
* type nodes.
*
* @param node
* @returns image width
*/
getImageWidth: (node: Node) => number;
/**
* Function returning the image height of the node.
* This function is only used for provider.node.DisplayTypes.IMAGE
* type nodes.
*
* @param node
* @returns image height
*/
getImageHeight: (node: Node) => number;
/**
* Filters the query generated to retrieve the values on a node.
*
* @param node
* @param initialQuery contains the query as an object structure.
* @returns filtered node value query
*/
filterNodeValueQuery: (node: Node, initialQuery: any) => typeof initialQuery;
/**
* Filters the query generated to retrieve the values on a node.
*
* @param node
* @param initialQuery contains the query as an object structure.
* @returns filtered node count query
*/
filterNodeCountQuery: (node: Node, initialQuery: any) => typeof initialQuery;
/**
* Filters the query used to retrieve the values on a node.
*
* @param node
* @param initialQuery contains the query as an object structure.
* @returns filtered node relation query
*/
filterNodeRelationQuery: (node: Node, initialQuery: any) => typeof initialQuery;
/**
* Customize, in query, the generated constraint for the node.
*
* If undefined use default constraint generation.
*/
generateNodeValueConstraints: undefined | any[];
/**
* Customize, in query, the generated negative constraint for the node.
*
* If undefined use default negative constraint generation.
*/
generateNegativeNodeValueConstraints: undefined | any[];
/**********************************************************************
* Results specific parameters:
*
* These attributes are specific to result display.
**********************************************************************/
/**
* Generate the result entry content using d3.js mechanisms.
*
* The parameter of the function is the <p> selected with d3.js
*
* The default behavior is to generate a <table> containing all
* the return attributes in a <th> and their value in a <td>.
*
* @param pElmt the <p> element generated in the result list.
*/
displayResults: (pElmt: SVGPathElement) => void;
/**
* Define the different type of rendering of a node for a given label.
* TEXT: default rendering type, the node will be displayed with an ellipse and a text in it.
* IMAGE: the node is displayed as an image using the image tag in the svg graph.
* In this case an image path is required.
* SVG: the node is displayed using a list of svg path, each path can contain its own color.
*/
DisplayTypes: Readonly<{
TEXT: 0
IMAGE: 1
SVG: 2
SYMBOL: 3
}>;
/**
* Get the label provider for the given label.
* If no provider is defined for the label:
* First search in parent provider.
* Then if not found will create one from default provider.
*
* @param label to retrieve the corresponding label provider.
* @returns corresponding label provider.
*/
getProvider: (label: string) => Node;
/**
* Get the property or function defined in node label provider.
* If the property is not found search is done in parents.
* If not found in parent, property defined in provider.node.DEFAULT_PROVIDER is returned.
* If not found in default provider, defaultValue is set and returned.
*
* @param label node label to get the property in its provider.
* @param name name of the property to retrieve.
* @returns node property defined in its label provider.
*/
getProperty: (label: string, name: string) => any;
/**
*
* @param label
*/
getIsAutoLoadValue: (label: string) => boolean;
/**
* Return the "isSearchable" property for the node label provider.
* Is Searchable defines whether the label can be used as graph query builder root.
* If true the label can be displayed in the taxonomy filter.
*
* @param label
* @returns boolean
*/
getIsSearchable: (label: string) => boolean;
/**
* Return the "autoExpandRelations" property for the node label provider.
* Auto expand relations defines whether the label will automatically add its relations when displayed on graph.
*
* @param label
* @returns boolean
*/
getIsAutoExpandRelations: (label: string) => boolean;
getSchema: (label: string) => any;
/**
* Return the list of attributes defined in node label provider.
* Parents return attributes are also returned.
*
* @param label used to retrieve parent attributes.
* @returns list of return attributes for a node.
*/
getReturnAttributes: (label: string) => any[];
/**
* Return the attribute to use as constraint attribute for a node defined in its label provider.
*
* @param label
* @returns constraint attributes
*/
getConstraintAttribute: (label: string) => any;
getDisplayAttribute: (label: string) => any;
getValueOrderByAttribute: (label: string) => any;
getResultOrderByAttribute: (label: string) => any;
/**
* Check in label provider if text must be displayed with images nodes.
* @param node
* @returns wether or not text is displayed
*/
isTextDisplayed: (node: Node) => boolean;
/**
* Return the node display type.
* can be TEXT, IMAGE, SVG or GROUP.
*
* @param node
* @returns node display type
*/
getNodeDisplayType: (node: Node) => any;
getGenerateNodeValueConstraints: (node: Node) => any;
getGenerateNegativeNodeValueConstraints: (node: Node) => string[];
/**
* Return the displayResults function defined in label parameter's provider.
*
* @param label
* @returns display results
*/
getDisplayResults: (label: string) => any;
}
export interface Provider {
/**
* Default color scale generator.
* Used in getColor link and node providers.
*/
colorScale: d3.ScaleOrdinal<string, ReadonlyArray<string>>;
colorLuminance: (hex: string, lum: number) => string;
link: Link & {
/**
* Label provider used by default if none have been defined for a label.
* This provider can be changed if needed to customize default behavior.
* If some properties are not found in user customized providers, default values will be extracted from this provider.
*/
DEFAULT_PROVIDER: Link;
Provider: Link;
};
taxonomy: Taxonomy & {
/**
* Label provider used by default if none have been defined for a label.
* This provider can be changed if needed to customize default behavior.
* If some properties are not found in user customized providers, default values will be extracted from this provider.
*/
DEFAULT_PROVIDER: Taxonomy;
Provider: Taxonomy;
};
node: Node & {
/**
* Label provider used by default if none have been defined for a label.
* This provider can be changed if needed to customize default behavior.
* If some properties are not found in user customized providers, default
* values will be extracted from this provider.
*/
DEFAULT_PROVIDER: Node;
Provider: { [key: string]: Partial<Node> };
};
} | the_stack |
import {Constants} from "../../../constants";
import {ObjectUtils} from "../../../objectUtils";
import {OperationResult} from "../../../operationResult";
import {PdfPreviewInfo} from "../../../previewInfo";
import {StringUtils} from "../../../stringUtils";
import {UrlUtils} from "../../../urlUtils";
import {SmartValue} from "../../../communicator/smartValue";
import {FullPageScreenshotResult} from "../../../contentCapture/fullPageScreenshotHelper";
import {PdfScreenshotHelper, PdfScreenshotResult} from "../../../contentCapture/pdfScreenshotHelper";
import {DomUtils} from "../../../domParsers/domUtils";
import {ExtensionUtils} from "../../../extensions/extensionUtils";
import {Localization} from "../../../localization/localization";
import {ClipMode} from "../../clipMode";
import {ClipperStateProp, DataResult} from "../../clipperState";
import {Status} from "../../status";
import {RotatingMessageSpriteAnimation} from "../../components/rotatingMessageSpriteAnimation";
import {PdfPreviewAttachment} from "./pdfPreviewAttachment";
import {PdfPreviewPage} from "./pdfPreviewPage";
import {PreviewComponentBase} from "./previewComponentBase";
import {PreviewViewerPdfHeader} from "./previewViewerPdfHeader";
import * as _ from "lodash";
type IndexToDataUrlMap = { [index: number]: string; }
interface PdfPreviewState {
showPageNumbers?: boolean;
renderedPageIndexes?: IndexToDataUrlMap;
}
class PdfPreviewClass extends PreviewComponentBase<PdfPreviewState, ClipperStateProp> {
private static latestScrollListener: (event: UIEvent) => void;
private static scrollListenerTimeout: number;
private initPageRenderCalled: boolean = false;
constructor(props: ClipperStateProp) {
super(props);
// We need to do this on every constructor to ensure the reference to the state
// object is correct
this.addScrollListener();
}
getInitialState(): PdfPreviewState {
return {
showPageNumbers: false,
renderedPageIndexes: {},
};
}
private searchForVisiblePageBoundary(allPages: NodeListOf<Element>, initPageIndex: number, incrementer: number): number {
let pageIndexToTest = initPageIndex;
let guessAtPageBoundary = allPages[pageIndexToTest] as HTMLDivElement;
while (guessAtPageBoundary && this.pageIsVisible(guessAtPageBoundary)) {
pageIndexToTest += incrementer;
guessAtPageBoundary = allPages[pageIndexToTest] as HTMLDivElement;
}
// result of adding last incrementer was a non-visible page, so return the page num from before that
return Math.max(pageIndexToTest -= incrementer, 0);
}
/**
* Get an approximation of the centermost visible page currently in the viewport (based on scroll percentage).
* If the page is indeed in the viewport, search up and down for the visible page boundaries.
* If the page approximation was incorrect and the page is not visible, begin a fan-out search of the area around the approximate page
* for a visible page. When a visible page boundary is found, find the other visible page boundary.
*/
private getIndicesOfVisiblePages(): number[] {
let allPages = document.querySelectorAll("div[data-pageindex]");
const initGuessAtCurrentPageIndexer: number = Math.floor(DomUtils.getScrollPercent(document.getElementById("previewContentContainer"), true /* asDecimalValue */) * (allPages.length - 1));
let firstVisiblePageIndexer: number;
let lastVisiblePageIndexer: number;
if (this.pageIsVisible(allPages[initGuessAtCurrentPageIndexer] as HTMLDivElement)) {
firstVisiblePageIndexer = this.searchForVisiblePageBoundary(allPages, initGuessAtCurrentPageIndexer, -1);
lastVisiblePageIndexer = this.searchForVisiblePageBoundary(allPages, initGuessAtCurrentPageIndexer, 1);
} else {
let incrementer = 1;
let guessAtVisiblePageIndexer = initGuessAtCurrentPageIndexer + incrementer;
let guessAtVisiblePageBoundary = allPages[guessAtVisiblePageIndexer] as HTMLDivElement;
while (!this.pageIsVisible(guessAtVisiblePageBoundary)) {
if (incrementer > 0) {
incrementer *= -1;
} else {
incrementer = (incrementer * -1) + 1;
}
guessAtVisiblePageIndexer = initGuessAtCurrentPageIndexer + incrementer;
guessAtVisiblePageBoundary = allPages[guessAtVisiblePageIndexer] as HTMLDivElement;
}
if (incrementer > 0) {
firstVisiblePageIndexer = guessAtVisiblePageIndexer;
lastVisiblePageIndexer = this.searchForVisiblePageBoundary(allPages, firstVisiblePageIndexer, 1);
} else {
lastVisiblePageIndexer = guessAtVisiblePageIndexer;
firstVisiblePageIndexer = this.searchForVisiblePageBoundary(allPages, lastVisiblePageIndexer, -1);
}
}
// _.range does not include the end number, so add 1
return _.range(firstVisiblePageIndexer, lastVisiblePageIndexer + 1);
}
private setDataUrlsOfImagesInViewportInState() {
let pageIndicesToRender: number[] = this.getIndicesOfVisiblePages();
// Pad pages to each end of the list to increase the scroll distance before the user hits a blank page
if (pageIndicesToRender.length > 0) {
let first = pageIndicesToRender[0];
let extraPagesToPrepend = _.range(Math.max(first - Constants.Settings.pdfExtraPageLoadEachSide, 0), first);
let afterLast = pageIndicesToRender[pageIndicesToRender.length - 1] + 1;
let extraPagesToAppend = _.range(afterLast, Math.min(afterLast + Constants.Settings.pdfExtraPageLoadEachSide, this.props.clipperState.pdfResult.data.get().pdf.numPages()));
pageIndicesToRender = extraPagesToPrepend.concat(pageIndicesToRender).concat(extraPagesToAppend);
}
this.setDataUrlsOfImagesInState(pageIndicesToRender);
}
private pageIsVisible(element: HTMLElement): boolean {
if (!element) {
return false;
}
let rect = element.getBoundingClientRect();
return rect.top <= window.innerHeight && rect.bottom >= 0;
}
private setDataUrlsOfImagesInState(pageIndicesToRender: number[]) {
this.props.clipperState.pdfResult.data.get().pdf.getPageListAsDataUrls(pageIndicesToRender).then((dataUrls) => {
let renderedIndexes: IndexToDataUrlMap = {};
for (let i = 0; i < dataUrls.length; i++) {
renderedIndexes[pageIndicesToRender[i]] = dataUrls[i];
}
this.setState({
renderedPageIndexes: renderedIndexes
});
});
}
/**
* Gets the page components to be rendered in the preview
*/
private getPageComponents(): any[] {
let pages = [];
let pdfResult = this.props.clipperState.pdfResult.data.get();
// Determine which pages should be marked as selected vs unselected
let pagesToShow: number[];
let parsePageRangeOperation = StringUtils.parsePageRange(this.props.clipperState.pdfPreviewInfo.selectedPageRange);
if (parsePageRangeOperation.status !== OperationResult.Succeeded) {
pagesToShow = [];
} else {
// If the operation Succeeded, the result should always be a number[]
pagesToShow = parsePageRangeOperation.result as number[];
}
pagesToShow = pagesToShow.map((ind) => { return ind - 1; });
for (let i = 0; i < pdfResult.pdf.numPages(); i++) {
pages.push(<PdfPreviewPage showPageNumber={this.state.showPageNumbers} isSelected={this.props.clipperState.pdfPreviewInfo.allPages || pagesToShow.indexOf(i) >= 0}
viewportDimensions={pdfResult.viewportDimensions[i]} imgUrl={this.state.renderedPageIndexes[i]} index={i} />);
}
return pages;
}
private addScrollListener() {
if (PdfPreviewClass.latestScrollListener) {
window.removeEventListener("scroll", PdfPreviewClass.latestScrollListener, true);
}
// When we detect a scroll, show page numbers immediately.
// When the user doesn't scroll for some period of time, fade them out.
PdfPreviewClass.latestScrollListener = (event) => {
let element = event.target as HTMLElement;
if (!!element && element.id === Constants.Ids.previewContentContainer) {
if (ObjectUtils.isNumeric(PdfPreviewClass.scrollListenerTimeout)) {
clearTimeout(PdfPreviewClass.scrollListenerTimeout);
}
PdfPreviewClass.scrollListenerTimeout = setTimeout(() => {
this.setState({
showPageNumbers: false
});
// We piggyback the scroll listener to determine what pages the user is looking at, then render them
if (this.props.clipperState.currentMode.get() === ClipMode.Pdf && this.props.clipperState.pdfResult.status === Status.Succeeded) {
this.setDataUrlsOfImagesInViewportInState();
}
}, Constants.Settings.timeUntilPdfPageNumbersFadeOutAfterScroll);
// A little optimization to prevent us from calling render a large number of times
if (!this.state.showPageNumbers) {
this.setState({
showPageNumbers: true
});
}
}
};
// TODO does this work on touch and pageup/down too?
window.addEventListener("scroll", PdfPreviewClass.latestScrollListener, true /* allows the listener to listen to all elements */);
}
protected getContentBodyForCurrentStatus(): any[] {
let state = this.props.clipperState;
if (state.pdfResult.status === Status.InProgress || state.pdfResult.status === Status.NotStarted) {
return [this.getSpinner()];
}
return this.convertPdfResultToContentData(state.pdfResult);
}
protected getHeader(): any {
return <PreviewViewerPdfHeader dummy />;
}
protected getStatus(): Status {
if (!this.props.clipperState.pageInfo) {
return Status.NotStarted;
}
return this.props.clipperState.pdfResult.status;
}
protected getTitleTextForCurrentStatus(): string {
let noContentFoundString = Localization.getLocalizedString("WebClipper.Preview.NoContentFound");
let failureMessage: string;
let previewStatus = this.getStatus();
let pdfResult = this.props.clipperState.pdfResult;
switch (previewStatus) {
case Status.Succeeded:
// TODO: verify this is actually what happens
if (pdfResult && !pdfResult.data.get()) {
return Localization.getLocalizedString("WebClipper.Preview.NoContentFound");
}
return this.props.clipperState.previewGlobalInfo.previewTitleText;
case Status.NotStarted:
case Status.InProgress:
return Localization.getLocalizedString("WebClipper.Preview.LoadingMessage");
default:
case Status.Failed:
failureMessage = this.props.clipperState.pdfResult.data.get().failureMessage;
return !!failureMessage ? failureMessage : noContentFoundString;
}
}
private convertPdfResultToContentData(result: DataResult<SmartValue<PdfScreenshotResult>>): any[] {
let contentBody = [];
switch (result.status) {
case Status.Succeeded:
if (!this.initPageRenderCalled) {
// Load the first n pages (or fewer if numPages < n) as soon as we are able to
this.initPageRenderCalled = true;
this.setDataUrlsOfImagesInState(_.range(Math.min(Constants.Settings.pdfInitialPageLoadCount, result.data.get().pdf.numPages())));
}
// In OneNote we don't display the extension
let shouldAttachPdf = this.props.clipperState.pdfPreviewInfo.shouldAttachPdf;
let defaultAttachmentName = "Original.pdf";
let fullAttachmentName = this.props.clipperState.pageInfo ? UrlUtils.getFileNameFromUrl(this.props.clipperState.pageInfo.rawUrl, defaultAttachmentName) : defaultAttachmentName;
if (shouldAttachPdf) {
contentBody.push(<PdfPreviewAttachment name={fullAttachmentName.split(".")[0]}/>);
}
contentBody = contentBody.concat(this.getPageComponents());
break;
case Status.NotStarted:
case Status.InProgress:
contentBody.push(this.getSpinner());
break;
default:
case Status.Failed:
break;
}
return contentBody;
}
private getSpinner(): any {
let spinner = <RotatingMessageSpriteAnimation
spriteUrl={ExtensionUtils.getImageResourceUrl("spinner_loop_colored.png") }
imageHeight={65}
imageWidth={45}
totalFrameCount={21}
loop={true}
shouldDisplayMessage={false} />;
return <div className={Constants.Classes.centeredInPreview}>{spinner}</div>;
}
}
let component = PdfPreviewClass.componentize();
export {component as PdfPreview}; | the_stack |
import graphlib from 'graphlib';
import { Logger, cloneDeep, has } from '@terascope/utils';
import { nanoid } from 'nanoid';
import { OperationsManager } from '../index';
import {
OperationConfig,
ValidationResults,
ExtractionProcessingDict,
StateDict,
OperationConfigInput,
SelectorConfig,
ExtractionConfig,
PostProcessConfig,
} from '../interfaces';
const {
Graph,
alg: { topsort, findCycles },
} = graphlib;
function makeSelectorTag(name: string) {
return `selector:${name}`;
}
export function parseConfig(
configList: OperationConfig[],
opsManager: OperationsManager,
logger: Logger
) {
const graph = new Graph();
const tagMapping: StateDict = {};
const graphEdges: StateDict = {};
configList.forEach((config) => {
const configId = config.__id;
if (config.tags) {
config.tags.forEach((tag) => {
if (!tagMapping[tag]) {
tagMapping[tag] = [];
}
if (isPrimaryConfig(config) && !hasPrimaryExtractions(config)) {
tagMapping[tag].push(makeSelectorTag(config.selector as string));
} else {
tagMapping[tag].push(configId);
}
});
}
if (isPrimaryConfig(config)) {
const selectorNode = makeSelectorTag(config.selector as string);
if (!graph.hasNode(selectorNode)) {
graph.setNode(selectorNode, config);
}
if (hasPrimaryExtractions(config)) {
graph.setNode(configId, config);
graph.setEdge(selectorNode, configId);
}
}
if (hasPostProcess(config)) {
// config may be out of order so we build edges later
graph.setNode(configId, config);
if (!graphEdges[config.follow as string]) {
graphEdges[config.follow as string] = [configId];
} else {
graphEdges[config.follow as string].push(configId);
}
}
});
// config may be out of order so we build edges after the fact on post processors
for (const [key, ids] of Object.entries(graphEdges)) {
ids.forEach((id) => {
const matchingTags: string[] = tagMapping[key];
if (matchingTags == null) {
throw new Error(`rule attempts to follow a tag that doesn't exist: ${JSON.stringify(graph.node(id))}`);
}
matchingTags.forEach((tag) => graph.setEdge(tag, id));
});
}
const cycles = findCycles(graph);
if (cycles.length > 0) {
const errMsg = 'A cyclic tag => follow sequence has been found, cycles: ';
const errList: string[] = [];
cycles.forEach((cycleList) => {
const list = cycleList.map((id) => graph.node(id));
errList.push(JSON.stringify(list, null, 4));
});
throw new Error(`${errMsg}${errList.join(' \n cycle: ')}`);
}
const sortList = topsort(graph);
const configListOrder: OperationConfig[] = sortList.map((id) => graph.node(id));
// we are mutating the config to make sure it has all the necessary fields
const normalizedConfig = normalizeConfig(configListOrder, opsManager, tagMapping);
const results = createResults(normalizedConfig);
validateOtherMatchRequired(results.extractions, logger);
return results;
}
function normalizeConfig(
configList: OperationConfig[],
opsManager: OperationsManager,
tagMapping: StateDict
): OperationConfig[] {
const results: OperationConfig[] = [];
return configList.reduce((list, config) => {
if (hasPostProcess(config)) {
const targetField = config.target;
// we search inside the list of altered normalized configs.
// This works becuase topsort orders them
const fieldsConfigs = findConfigs(config, list, tagMapping);
if (isOneToOne(opsManager, config)) {
const stuff = createMatchingConfig(fieldsConfigs, config, tagMapping);
list.push(...stuff);
} else {
const [pipeline] = fieldsConfigs.map((obj) => obj.pipeline);
config.__pipeline = pipeline;
config.sources = [...new Set(fieldsConfigs.map((obj) => obj.source))];
if (targetField && !Array.isArray(targetField)) {
config.target = targetField;
} else {
checkForTarget(config);
}
list.push(config);
}
} else {
list.push(config);
}
return list;
}, results);
}
interface FieldSourceConfigs {
source: string;
pipeline: string;
}
function findConfigs(
config: OperationConfig,
configList: OperationConfig[],
tagMapping: StateDict
): FieldSourceConfigs[] {
const identifier = config.follow || config.__id;
const nodeIds: string[] = tagMapping[identifier];
const mapping = {};
const results: FieldSourceConfigs[] = [];
configList
.filter((obj) => {
let selectorId;
if (obj.selector) selectorId = makeSelectorTag(obj.selector);
const foundNode = nodeIds.includes(obj.__id)
|| (selectorId && nodeIds.includes(selectorId));
return foundNode;
})
.forEach((obj) => {
if (!mapping[obj.__id]) {
mapping[obj.__id] = true;
const pipeline = obj.__pipeline || obj.selector;
results.push({ pipeline: pipeline as string, source: obj.target as string });
}
});
return results;
}
function createMatchingConfig(
fieldsConfigs: FieldSourceConfigs[],
config: OperationConfig,
tagMapping: StateDict
): OperationConfig[] {
// we clone the original to preserve the __id in reference to tag mappings and the like
const original = cloneDeep(config);
return fieldsConfigs.map((obj: FieldSourceConfigs, index: number) => {
let resultsObj: Partial<OperationConfig> = {};
const pipelineConfig = { __pipeline: obj.pipeline };
if (index === 0) {
resultsObj = Object.assign(original, pipelineConfig);
} else {
resultsObj = Object.assign({}, config, { __id: nanoid() }, pipelineConfig);
if (resultsObj.tags) {
resultsObj.tags.forEach((tag) => {
if (!tagMapping[tag]) {
tagMapping[tag] = [];
}
tagMapping[tag].push(resultsObj.__id as string);
});
}
}
if (!resultsObj.source) resultsObj.source = obj.source;
if (config.target === undefined) {
resultsObj.target = obj.source;
} else if (Array.isArray(config.target)) {
resultsObj.target = config.target[index];
} else {
resultsObj.target = config.target;
}
checkForSource(resultsObj as OperationConfig);
checkForTarget(resultsObj as OperationConfig);
return resultsObj as OperationConfig;
});
}
function validateOtherMatchRequired(configDict: ExtractionProcessingDict, logger: Logger) {
for (const [selector, opsList] of Object.entries(configDict)) {
const hasMatchRequired = opsList.find((op) => !!op.other_match_required) != null;
if (hasMatchRequired && opsList.length === 1) {
logger.warn(
`
There is only a single extraction for selector ${selector} and it has other_match_required set to true.
This will return empty results unless the data matches another selector that has reqular extractions
`.trim()
);
}
}
}
function checkForSource(config: OperationConfig) {
if (!config.source
&& (config.sources == null || config.sources.length === 0)) {
throw new Error(`could not find source fields for config ${JSON.stringify(config)}`);
}
}
function isOneToOne(opsManager: OperationsManager, config: OperationConfig): boolean {
if (isOnlySelector(config)) return true;
const processType = config.validation || config.post_process || 'extraction';
const Operation = opsManager.getTransform(processType as string);
return Operation.cardinality === 'one-to-one';
}
function checkForTarget(config: OperationConfig) {
if (!config.target) {
throw new Error(`could not find target fields for config ${JSON.stringify(config)}`);
}
}
type Config = OperationConfig | OperationConfigInput;
export function isPrimaryConfig(config: Config) {
return hasSelector(config) && !hasPostProcess(config);
}
export function needsDefaultSelector(config: Config) {
return !hasSelector(config) && !hasFollow(config);
}
function isPrimarySelector(config: Config) {
return hasSelector(config) && !hasPostProcess(config);
}
function isOnlySelector(config: Config) {
return hasSelector(config) && !hasExtractions(config) && !hasPostProcess(config);
}
function isPostProcessType(config: Config, type: string) {
return config.post_process === type;
}
function hasSelector(config: Config) {
return has(config, 'selector');
}
function hasFollow(config: Config) {
return has(config, 'follow');
}
function hasPostProcess(config: Config): boolean {
return has(config, 'post_process') || has(config, 'validation');
}
export function isDeprecatedCompactConfig(config: Config): boolean {
return !hasFollow(config) && hasPostProcess(config) && hasSelector(config);
}
export function isSimplePostProcessConfig(config: Config) {
return !has(config, 'follow') && hasPostProcess(config);
}
export function hasExtractions(config: Config) {
return has(config, 'source') || has(config, 'exp');
}
function hasPrimaryExtractions(config: Config) {
return hasExtractions(config) && !isPostProcessType(config, 'extraction') && !hasFollow(config);
}
function hasOutputRestrictions(config: Config) {
return config.output === false && config.validation == null;
}
function hasMatchRequirements(config: Config) {
return has(config, 'other_match_required');
}
function createResults(list: OperationConfig[]): ValidationResults {
const results: ValidationResults = {
selectors: [],
extractions: {},
postProcessing: {},
output: {
restrictOutput: {},
matchRequirements: {},
},
};
const { output } = results;
let currentSelector: undefined | string;
const duplicateListing = {};
list.forEach((config) => {
if (duplicateListing[config.__id]) {
return;
}
duplicateListing[config.__id] = true;
if (hasOutputRestrictions(config)) {
const key = config.target || config.source;
output.restrictOutput[key as string] = true;
}
if (isPrimarySelector(config)) {
currentSelector = config.selector;
if (!duplicateListing[config.selector as string]) {
duplicateListing[config.selector as string] = true;
results.selectors.push(config as SelectorConfig);
}
}
if (hasPrimaryExtractions(config)) {
if (!results.extractions[currentSelector as string]) {
results.extractions[currentSelector as string] = [];
}
config.mutate = false;
results.extractions[currentSelector as string].push(config as ExtractionConfig);
}
if (hasPostProcess(config)) {
if (config.__pipeline) currentSelector = config.__pipeline;
if (!results.postProcessing[currentSelector as string]) {
results.postProcessing[currentSelector as string] = [];
}
if (isPostProcessType(config, 'extraction')) {
if (config.mutate == null) config.mutate = true;
}
results.postProcessing[currentSelector as string].push(config as PostProcessConfig);
}
if (hasMatchRequirements(config)) {
const key = config.target || config.source as string;
output.matchRequirements[key] = config.selector ?? config.__pipeline as string;
}
});
return results;
} | the_stack |
import { OvaleDataClass } from "../engine/data";
import { OvaleClass } from "../Ovale";
import { LastSpell, SpellCast, SpellCastModule } from "./LastSpell";
import aceEvent, { AceEvent } from "@wowts/ace_event-3.0";
import { next, pairs, LuaObj, kpairs } from "@wowts/lua";
import { GetSpellCooldown, GetTime, GetSpellCharges } from "@wowts/wow-mock";
import { StateModule, States } from "../engine/state";
import { OvalePaperDollClass, HasteType } from "./PaperDoll";
import { LuaArray } from "@wowts/lua";
import { AceModule } from "@wowts/tsaddon";
import { DebugTools, Tracer } from "../engine/debug";
import { isNumber } from "../tools/tools";
const globalCooldown = 61304;
const cooldownThreshold = 0.1;
// "Spell Haste" affects cast speed and spell GCD (spells, not melee abilities), but not hasted cooldowns (cd_haste in Ovale's SpellInfo)
// "Melee Haste" is in game as "Attack Speed" and affects white swing speed only, not the GCD
// "Ranged Haste" looks to be no longer used and matches "Melee Haste" usually, DK talent Icy Talons for example; Suppression Aura in BWL does not affect Ranged Haste but does Melee Haste as of 7/29/18
interface GcdInfo {
[1]: number;
[2]: HasteType;
}
const baseGcds = {
["DEATHKNIGHT"]: <GcdInfo>{
1: 1.5,
2: "base",
},
["DEMONHUNTER"]: <GcdInfo>{
1: 1.5,
2: "base",
},
["DRUID"]: <GcdInfo>{
1: 1.5,
2: "spell",
},
["HUNTER"]: <GcdInfo>{
1: 1.5,
2: "base",
},
["MAGE"]: <GcdInfo>{
1: 1.5,
2: "spell",
},
["MONK"]: <GcdInfo>{
1: 1.0,
2: "none",
},
["PALADIN"]: <GcdInfo>{
1: 1.5,
2: "spell",
},
["PRIEST"]: <GcdInfo>{
1: 1.5,
2: "spell",
},
["ROGUE"]: <GcdInfo>{
1: 1.0,
2: "none",
},
["SHAMAN"]: <GcdInfo>{
1: 1.5,
2: "spell",
},
["WARLOCK"]: <GcdInfo>{
1: 1.5,
2: "spell",
},
["WARRIOR"]: <GcdInfo>{
1: 1.5,
2: "base",
},
};
export interface Cooldown {
serial?: number;
start: number;
charges: number;
duration: number;
enable: boolean;
maxCharges: number;
chargeStart: number;
chargeDuration: number;
}
export class CooldownData {
cd: LuaObj<Cooldown> = {};
}
export class OvaleCooldownClass
extends States<CooldownData>
implements SpellCastModule, StateModule
{
serial = 0;
sharedCooldown: LuaObj<LuaArray<boolean>> = {};
gcd = {
serial: 0,
start: 0,
duration: 0,
};
private module: AceModule & AceEvent;
private tracer: Tracer;
constructor(
private ovalePaperDoll: OvalePaperDollClass,
private ovaleData: OvaleDataClass,
private lastSpell: LastSpell,
private ovale: OvaleClass,
ovaleDebug: DebugTools
) {
super(CooldownData);
this.module = ovale.createModule(
"OvaleCooldown",
this.handleInitialize,
this.handleDisable,
aceEvent
);
this.tracer = ovaleDebug.create("OvaleCooldown");
}
private handleInitialize = () => {
this.module.RegisterEvent("ACTIONBAR_UPDATE_COOLDOWN", this.update);
this.module.RegisterEvent("BAG_UPDATE_COOLDOWN", this.update);
this.module.RegisterEvent("PET_BAR_UPDATE_COOLDOWN", this.update);
this.module.RegisterEvent("SPELL_UPDATE_CHARGES", this.update);
this.module.RegisterEvent("SPELL_UPDATE_USABLE", this.update);
this.module.RegisterEvent("UNIT_SPELLCAST_CHANNEL_START", this.update);
this.module.RegisterEvent("UNIT_SPELLCAST_CHANNEL_STOP", this.update);
this.module.RegisterEvent(
"UNIT_SPELLCAST_INTERRUPTED",
this.handleUnitSpellCastInterrupted
);
this.module.RegisterEvent("UNIT_SPELLCAST_START", this.update);
this.module.RegisterEvent("UNIT_SPELLCAST_SUCCEEDED", this.update);
this.module.RegisterEvent("UPDATE_SHAPESHIFT_COOLDOWN", this.update);
this.lastSpell.registerSpellcastInfo(this);
};
private handleDisable = () => {
this.lastSpell.unregisterSpellcastInfo(this);
this.module.UnregisterEvent("ACTIONBAR_UPDATE_COOLDOWN");
this.module.UnregisterEvent("BAG_UPDATE_COOLDOWN");
this.module.UnregisterEvent("PET_BAR_UPDATE_COOLDOWN");
this.module.UnregisterEvent("SPELL_UPDATE_CHARGES");
this.module.UnregisterEvent("SPELL_UPDATE_USABLE");
this.module.UnregisterEvent("UNIT_SPELLCAST_CHANNEL_START");
this.module.UnregisterEvent("UNIT_SPELLCAST_CHANNEL_STOP");
this.module.UnregisterEvent("UNIT_SPELLCAST_INTERRUPTED");
this.module.UnregisterEvent("UNIT_SPELLCAST_START");
this.module.UnregisterEvent("UNIT_SPELLCAST_SUCCEEDED");
this.module.UnregisterEvent("UPDATE_SHAPESHIFT_COOLDOWN");
};
private handleUnitSpellCastInterrupted = (event: string, unit: string) => {
if (unit == "player" || unit == "pet") {
this.update(event, unit);
this.tracer.debug("Resetting global cooldown.");
const cd = this.gcd;
cd.start = 0;
cd.duration = 0;
}
};
private update = (event: string, unit: string) => {
if (!unit || unit == "player" || unit == "pet") {
// Increments the serial: cooldowns stored in this.next.cd will be refreshed
// TODO as ACTIONBAR_UPDATE_COOLDOWN is sent some time before UNIT_SPELLCAST_SUCCEEDED
// it refreshes the cooldown before power updates
this.serial = this.serial + 1;
this.ovale.needRefresh();
this.tracer.debug(event, this.serial);
}
};
resetSharedCooldowns() {
for (const [, spellTable] of pairs(this.sharedCooldown)) {
for (const [spellId] of pairs(spellTable)) {
delete spellTable[spellId];
}
}
}
isSharedCooldown(name: string | number) {
const spellTable = this.sharedCooldown[name];
return spellTable && next(spellTable) != undefined;
}
addSharedCooldown(name: string, spellId: number) {
this.sharedCooldown[name] = this.sharedCooldown[name] || {};
this.sharedCooldown[name][spellId] = true;
}
getGlobalCooldown(now?: number): [number, number] {
const cd = this.gcd;
if (!cd.start || !cd.serial || cd.serial < this.serial) {
now = now || GetTime();
if (now >= cd.start + cd.duration) {
[cd.start, cd.duration] = GetSpellCooldown(globalCooldown);
}
}
return [cd.start, cd.duration];
}
getSpellCooldown(
spellId: number | string,
atTime: number | undefined
): [number, number, boolean] {
if (atTime) {
const cd = this.getCD(spellId, atTime);
return [cd.start, cd.duration, cd.enable];
}
let [cdStart, cdDuration, cdEnable] = [0, 0, true];
if (this.sharedCooldown[spellId]) {
for (const [id] of pairs(this.sharedCooldown[spellId])) {
const [start, duration, enable] = this.getSpellCooldown(
id,
atTime
);
if (start) {
[cdStart, cdDuration, cdEnable] = [start, duration, enable];
break;
}
}
} else {
let [start, duration, enable] = GetSpellCooldown(spellId);
this.tracer.log(
"Call GetSpellCooldown which returned %f, %f, %d",
start,
duration,
enable
);
if (start !== undefined && start > 0) {
const [gcdStart, gcdDuration] = this.getGlobalCooldown();
this.tracer.log(
"GlobalCooldown is %d, %d",
gcdStart,
gcdDuration
);
if (start + duration > gcdStart + gcdDuration) {
[cdStart, cdDuration, cdEnable] = [start, duration, enable];
} else {
cdStart = start + duration;
cdDuration = 0;
cdEnable = enable;
}
} else {
[cdStart, cdDuration, cdEnable] = [
start || 0,
duration || 0,
enable,
];
}
}
return [cdStart - cooldownThreshold, cdDuration, cdEnable];
}
getBaseGCD(): [number, HasteType] {
let gcd: number, haste: HasteType;
const baseGCD = baseGcds[this.ovale.playerClass];
if (baseGCD) {
[gcd, haste] = [baseGCD[1], baseGCD[2]];
} else {
[gcd, haste] = [1.5, "spell"];
}
return [gcd, haste];
}
copySpellcastInfo = (spellcast: SpellCast, dest: SpellCast) => {
if (spellcast.offgcd) {
dest.offgcd = spellcast.offgcd;
}
};
saveSpellcastInfo = (spellcast: SpellCast, atTime: number) => {
const spellId = spellcast.spellId;
if (spellId) {
const gcd = this.ovaleData.getSpellInfoProperty(
spellId,
spellcast.start,
"gcd",
spellcast.targetGuid
);
if (gcd && gcd == 0) {
spellcast.offgcd = true;
}
}
};
getCD(spellId: number | string, atTime: number) {
let cdName: string | number = spellId;
const si = this.ovaleData.spellInfo[spellId];
if (si && si.shared_cd) {
cdName = si.shared_cd;
}
if (!this.next.cd[cdName]) {
this.next.cd[cdName] = {
start: 0,
duration: 0,
enable: false,
chargeDuration: 0,
chargeStart: 0,
charges: 0,
maxCharges: 0,
};
}
const cd = this.next.cd[cdName];
if (!cd.start || !cd.serial || cd.serial < this.serial) {
this.tracer.log(
"Didn't find an existing cd in next, look for one in current"
);
let [start, duration, enable] = this.getSpellCooldown(
spellId,
undefined
);
if (si && si.forcecd) {
[start, duration] = this.getSpellCooldown(
si.forcecd,
undefined
);
}
this.tracer.log("It returned %f, %f", start, duration);
cd.serial = this.serial;
cd.start = start - cooldownThreshold;
cd.duration = duration;
cd.enable = enable;
if (isNumber(spellId)) {
const [charges, maxCharges, chargeStart, chargeDuration] =
GetSpellCharges(spellId);
if (charges) {
cd.charges = charges;
cd.maxCharges = maxCharges;
cd.chargeStart = chargeStart;
cd.chargeDuration = chargeDuration;
}
}
}
const now = atTime;
if (cd.start) {
if (cd.start + cd.duration <= now) {
this.tracer.log("Spell cooldown is in the past");
cd.start = 0;
cd.duration = 0;
}
}
if (cd.charges) {
let charges = cd.charges;
const maxCharges = cd.maxCharges;
let chargeStart = cd.chargeStart;
const chargeDuration = cd.chargeDuration;
while (
chargeStart + chargeDuration <= now &&
charges < maxCharges
) {
chargeStart = chargeStart + chargeDuration;
charges = charges + 1;
}
cd.charges = charges;
cd.chargeStart = chargeStart;
}
this.tracer.log(
"Cooldown of spell %d is %f + %f",
spellId,
cd.start,
cd.duration
);
return cd;
}
getSpellCooldownDuration(
spellId: number,
atTime: number,
targetGUID: string
) {
let [start, duration] = this.getSpellCooldown(spellId, atTime);
if (duration > 0 && start + duration > atTime) {
this.tracer.log(
"Spell %d is on cooldown for %fs starting at %s.",
spellId,
duration,
start
);
} else {
[duration] = this.ovaleData.getSpellInfoPropertyNumber(
spellId,
atTime,
"cd",
targetGUID
);
if (duration !== undefined) {
if (duration < 0) {
duration = 0;
}
} else {
duration = 0;
}
this.tracer.log(
"Spell %d has a base cooldown of %fs.",
spellId,
duration
);
if (duration > 0) {
const haste = this.ovaleData.getSpellInfoProperty(
spellId,
atTime,
"cd_haste",
targetGUID
);
if (haste) {
const multiplier =
this.ovalePaperDoll.getBaseHasteMultiplier(atTime);
duration = duration / multiplier;
}
}
}
return duration;
}
getSpellCharges(
spellId: number,
atTime: number
): [number, number, number, number] {
const cd = this.getCD(spellId, atTime);
let charges = cd.charges;
const maxCharges = cd.maxCharges;
let chargeStart = cd.chargeStart;
const chargeDuration = cd.chargeDuration;
if (charges) {
while (
chargeStart + chargeDuration <= atTime &&
charges < maxCharges
) {
chargeStart = chargeStart + chargeDuration;
charges = charges + 1;
}
}
return [charges, maxCharges, chargeStart, chargeDuration];
}
applySpellStartCast = (
spellId: number,
targetGUID: string,
startCast: number,
endCast: number,
isChanneled: boolean,
spellcast: SpellCast
) => {
if (isChanneled) {
this.applyCooldown(spellId, targetGUID, startCast);
}
};
applySpellAfterCast = (
spellId: number,
targetGUID: string,
startCast: number,
endCast: number,
isChanneled: boolean,
spellcast: SpellCast
) => {
if (!isChanneled) {
this.applyCooldown(spellId, targetGUID, endCast);
}
};
initializeState() {
this.next.cd = {};
}
resetState() {
for (const [, cd] of pairs(this.next.cd)) {
cd.serial = undefined;
}
}
cleanState() {
for (const [spellId, cd] of pairs(this.next.cd)) {
for (const [k] of kpairs(cd)) {
delete cd[k];
}
delete this.next.cd[spellId];
}
}
private applyCooldown(spellId: number, targetGUID: string, atTime: number) {
const cd = this.getCD(spellId, atTime);
const duration = this.getSpellCooldownDuration(
spellId,
atTime,
targetGUID
);
if (duration == 0) {
cd.start = 0;
cd.duration = 0;
cd.enable = true;
} else {
cd.start = atTime;
cd.duration = duration;
cd.enable = true;
}
if (cd.charges && cd.charges > 0) {
cd.chargeStart = cd.start;
cd.charges = cd.charges - 1;
if (cd.charges == 0) {
cd.duration = cd.chargeDuration;
}
}
this.tracer.log(
"Spell %d cooldown info: start=%f, duration=%f, charges=%s",
spellId,
cd.start,
cd.duration,
cd.charges || "(nil)"
);
}
debugCooldown() {
for (const [spellId, cd] of pairs(this.next.cd)) {
if (cd.start) {
if (cd.charges) {
this.tracer.print(
"Spell %s cooldown: start=%f, duration=%f, charges=%d, maxCharges=%d, chargeStart=%f, chargeDuration=%f",
spellId,
cd.start,
cd.duration,
cd.charges,
cd.maxCharges,
cd.chargeStart,
cd.chargeDuration
);
} else {
this.tracer.print(
"Spell %s cooldown: start=%f, duration=%f",
spellId,
cd.start,
cd.duration
);
}
}
}
}
} | the_stack |
import * as SmartContracts from '@requestnetwork/smart-contracts';
import { StorageTypes } from '@requestnetwork/types';
import Utils from '@requestnetwork/utils';
import { EventEmitter } from 'events';
import { EthereumStorage } from '../src/ethereum-storage';
import { IpfsStorage } from '../src/ipfs-storage';
import IpfsConnectionError from '../src/ipfs-connection-error';
/* eslint-disable no-magic-numbers */
// eslint-disable-next-line @typescript-eslint/no-var-requires
const web3HttpProvider = require('web3-providers-http');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const web3Utils = require('web3-utils');
const ipfsGatewayConnection: StorageTypes.IIpfsGatewayConnection = {
host: 'localhost',
port: 5001,
protocol: StorageTypes.IpfsGatewayProtocol.HTTP,
timeout: 1000,
};
const provider = new web3HttpProvider('http://localhost:8545');
const web3Connection: StorageTypes.IWeb3Connection = {
networkId: StorageTypes.EthereumNetwork.PRIVATE,
timeout: 1000,
web3Provider: provider,
};
const invalidHostNetworkProvider = new web3HttpProvider('http://nonexistentnetwork:8545');
const invalidHostWeb3Connection: StorageTypes.IWeb3Connection = {
networkId: StorageTypes.EthereumNetwork.PRIVATE,
timeout: 1000,
web3Provider: invalidHostNetworkProvider,
};
// eslint-disable-next-line @typescript-eslint/no-var-requires
const web3Eth = require('web3-eth');
const eth = new web3Eth(provider);
const contractHashSubmitter = new eth.Contract(
SmartContracts.requestHashSubmitterArtifact.getContractAbi(),
SmartContracts.requestHashSubmitterArtifact.getAddress('private'),
);
const addressRequestHashSubmitter = contractHashSubmitter._address;
const content1 = 'this is a little test !';
const hash1 = 'QmNXA5DyFZkdf4XkUT81nmJSo3nS2bL25x7YepxeoDa6tY';
const realSize1 = 29;
const realSize1Bytes32Hex = web3Utils.padLeft(web3Utils.toHex(realSize1), 64);
const fakeSize1 = 50;
const fakeSize1Bytes32Hex = web3Utils.padLeft(web3Utils.toHex(fakeSize1), 64);
const content2 = 'content\nwith\nspecial\ncharacters\n';
const hash2 = 'QmQj8fQ9T16Ddrxfij5eyRnxXKTVxRXyQuazYnezt9iZpy';
const realSize2 = 38;
const realSize2Bytes32Hex = web3Utils.padLeft(web3Utils.toHex(realSize2), 64);
const fakeSize2 = 0;
const fakeSize2Bytes32Hex = web3Utils.padLeft(web3Utils.toHex(fakeSize2), 64);
// Define a mock for getPastEvents to be independent of the state of ganache instance
const pastEventsMock = [
{
blockNumber: 1,
event: 'NewHash',
returnValues: {
feesParameters: realSize1Bytes32Hex,
hash: hash1,
hashSubmitter: addressRequestHashSubmitter,
},
transactionHash: '0xa',
},
{
blockNumber: 1,
event: 'NewHash',
returnValues: {
feesParameters: fakeSize1Bytes32Hex,
hash: hash1,
hashSubmitter: addressRequestHashSubmitter,
},
transactionHash: '0xa',
},
{
blockNumber: 2,
event: 'NewHash',
returnValues: {
feesParameters: realSize2Bytes32Hex,
hash: hash2,
hashSubmitter: addressRequestHashSubmitter,
},
transactionHash: '0xb',
},
{
blockNumber: 3,
event: 'NewHash',
returnValues: {
feesParameters: fakeSize2Bytes32Hex,
hash: hash2,
hashSubmitter: addressRequestHashSubmitter,
},
transactionHash: '0xc',
},
{
blockNumber: 3,
event: 'NewHash',
returnValues: {
feesParameters: fakeSize2Bytes32Hex,
hash: 'notAHash',
hashSubmitter: addressRequestHashSubmitter,
},
transactionHash: '0xc',
},
];
/* eslint-disable */
const getPastEventsMock = () => pastEventsMock;
const ipfsStorage = new IpfsStorage({ ipfsGatewayConnection });
describe('EthereumStorage', () => {
beforeEach(() => {
jest.resetAllMocks();
});
describe('initialize', () => {
it('cannot use functions when not initialized', async () => {
const ethereumStorageNotInitialized = new EthereumStorage(
'localhost',
ipfsStorage,
web3Connection,
);
await expect(ethereumStorageNotInitialized.getData()).rejects.toThrowError(
'Ethereum storage must be initialized',
);
await expect(ethereumStorageNotInitialized.append('')).rejects.toThrowError(
'Ethereum storage must be initialized',
);
await expect(ethereumStorageNotInitialized.read('')).rejects.toThrowError(
'Ethereum storage must be initialized',
);
});
it('cannot initialize if ethereum node not reachable', async () => {
const ethereumStorageNotInitialized = new EthereumStorage(
'localhost',
ipfsStorage,
invalidHostWeb3Connection,
);
await expect(ethereumStorageNotInitialized.initialize()).rejects.toThrowError(
'Ethereum node is not accessible: Error: Error when trying to reach Web3 provider: Error: Invalid JSON RPC response: ""',
);
});
it('cannot initialize if ethereum node not listening', async () => {
const ethereumStorageNotInitialized = new EthereumStorage(
'localhost',
ipfsStorage,
web3Connection,
);
ethereumStorageNotInitialized.smartContractManager.eth.net.isListening = async () => false;
await expect(ethereumStorageNotInitialized.initialize()).rejects.toThrowError(
'Ethereum node is not accessible: Error: The Web3 provider is not listening',
);
});
it('cannot initialize if contracts are not deployed', async () => {
const ethereumStorageNotInitialized = new EthereumStorage(
'localhost',
ipfsStorage,
web3Connection,
);
const invalidHashStorageAddress = '0x0000000000000000000000000000000000000000';
const invalidHashSubmitterAddress = '0x0000000000000000000000000000000000000000';
// Initialize smart contract instance
ethereumStorageNotInitialized.smartContractManager.requestHashStorage = new eth.Contract(
SmartContracts.requestHashStorageArtifact.getContractAbi(),
invalidHashStorageAddress,
);
ethereumStorageNotInitialized.smartContractManager.requestHashSubmitter = new eth.Contract(
SmartContracts.requestHashSubmitterArtifact.getContractAbi(),
invalidHashSubmitterAddress,
);
await expect(ethereumStorageNotInitialized.initialize()).rejects.toThrowError(
'Contracts are not deployed or not well configured:',
);
});
});
describe('append/read/getData', () => {
let ethereumStorage: EthereumStorage;
beforeEach(async () => {
const ipfsStorage = new IpfsStorage({ ipfsGatewayConnection });
ethereumStorage = new EthereumStorage('localhost', ipfsStorage, web3Connection);
await ethereumStorage.initialize();
ethereumStorage.smartContractManager.requestHashStorage.getPastEvents = getPastEventsMock;
ethereumStorage.smartContractManager.addHashAndSizeToEthereum =
async (): Promise<StorageTypes.IEthereumMetadata> => {
return {
blockConfirmation: 10,
blockNumber: 10,
blockTimestamp: 1545816416,
cost: '110',
fee: '100',
gasFee: '10',
networkName: 'private',
smartContractAddress: '0x345ca3e014aaf5dca488057592ee47305d9b3e10',
transactionHash: '0x7c45c575a54893dc8dc7230e3044e1de5c8714cd0a1374cf3a66378c639627a3',
};
};
});
it('cannot be initialized twice', async () => {
await expect(ethereumStorage.initialize()).rejects.toThrowError('already initialized');
});
it('allows to append a file', async () => {
jest.useFakeTimers('modern');
jest.setSystemTime(0);
const timestamp = Utils.getCurrentTimestampInSecond();
const result = await ethereumStorage.append(content1);
const resultExpected: StorageTypes.IAppendResult = Object.assign(new EventEmitter(), {
content: content1,
id: hash1,
meta: {
ipfs: {
size: realSize1,
},
local: { location: 'localhost' },
state: StorageTypes.ContentState.PENDING,
storageType: StorageTypes.StorageSystemType.LOCAL,
timestamp,
},
});
expect(result).toMatchObject(resultExpected);
jest.useRealTimers();
});
it('throws when append and addHashAndSizeToEthereum throws', (done) => {
ethereumStorage.smartContractManager.addHashAndSizeToEthereum =
async (): Promise<StorageTypes.IEthereumMetadata> => {
throw Error('fake error');
};
expect.assertions(1);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
ethereumStorage.append(content1).then((result) => {
result
.on('confirmed', () => {
fail('addHashAndSizeToEthereum must have thrown');
})
.on('error', (error) => {
expect(error.message).toEqual('fake error');
done();
});
});
});
it(`allows to save dataId's Ethereum metadata into the metadata cache when append is called`, async () => {
await expect(
ethereumStorage.ethereumMetadataCache.metadataCache.get(hash1),
).resolves.toBeUndefined();
const result = await ethereumStorage.append(content1);
await expect(ethereumStorage.ethereumMetadataCache.metadataCache.get(hash1)).resolves.toEqual(
result.meta.ethereum,
);
});
it(`prevents already saved dataId's Ethereum metadata to be erased in the metadata cache when append is called`, async () => {
await expect(
ethereumStorage.ethereumMetadataCache.metadataCache.get(hash1),
).resolves.toBeUndefined();
const result1 = await ethereumStorage.append(content1);
// Ethereum metadata is determined by the return data of addHashAndSizeToEthereum
// We change the return data of this function to ensure the second call of append contain different metadata
ethereumStorage.smartContractManager.addHashAndSizeToEthereum =
async (): Promise<StorageTypes.IEthereumMetadata> => {
return {
blockConfirmation: 20,
blockNumber: 11,
blockTimestamp: 1545816416,
cost: '110',
fee: '1',
gasFee: '100',
networkName: 'private',
smartContractAddress: '0x345ca3e014aaf5dca488057592ee47305d9b3e10',
transactionHash: '0x7c45c575a54893dc8dc7230e3044e1de5c8714cd0a1374cf3a66378c639627a3',
};
};
const result2 = await ethereumStorage.append(content1);
result1.on('confirmed', (resultConfirmed1) => {
result2.on('confirmed', async (resultConfirmed2) => {
expect(resultConfirmed1).not.toMatchObject(resultConfirmed2);
await expect(
ethereumStorage.ethereumMetadataCache.metadataCache.get(hash1),
).resolves.toEqual(resultConfirmed1.meta.ethereum);
});
});
});
it('allows to read a file', async () => {
const appendResult = await ethereumStorage.append(content1);
const confirmation = new Promise((r) => appendResult.on('confirmed', r));
const resultBeforeConfirmation = await ethereumStorage.read(hash1);
expect(resultBeforeConfirmation.meta.ethereum).not.toBeDefined();
expect(resultBeforeConfirmation.meta.state).toBe(StorageTypes.ContentState.PENDING);
await confirmation;
const result = await ethereumStorage.read(hash1);
expect(result.meta.ethereum).toBeDefined();
expect(result.meta.state).toBe(StorageTypes.ContentState.CONFIRMED);
expect(result.content).toBe(content1);
expect(result.meta.ipfs).toMatchObject({ size: realSize1 });
expect(result.meta.ethereum?.blockNumber).toEqual(10);
expect(result.meta.ethereum?.networkName).toEqual('private');
expect(result.meta.ethereum?.smartContractAddress).toEqual(
'0x345ca3e014aaf5dca488057592ee47305d9b3e10',
);
expect(result.meta.ethereum?.blockConfirmation).toBeGreaterThan(1);
expect(result.meta.ethereum?.blockTimestamp).toBeDefined();
});
it('cannot append if ipfs read fail', async () => {
jest.spyOn((ethereumStorage as any).ipfsStorage, 'read').mockImplementation(() => {
throw Error('expected error');
});
await ethereumStorage.append(content1);
await expect(ethereumStorage.read(hash1)).rejects.toThrowError(`expected error`);
});
it('allows to retrieve all data id (even if pin fail)', async () => {
// These contents have to be appended in order to check their size
await ethereumStorage.append(content1);
await ethereumStorage.append(content2);
const { entries } = await ethereumStorage.getData();
if (!entries[0].meta.ethereum) {
fail('entries[0].meta.ethereum does not exist');
return;
}
expect(entries[0].meta.ipfs).toMatchObject({
size: realSize1,
});
expect(entries[0].meta.ethereum.blockNumber).toEqual(pastEventsMock[0].blockNumber);
expect(entries[0].meta.ethereum.networkName).toEqual('private');
expect(entries[0].meta.ethereum.smartContractAddress).toEqual(
'0x345ca3e014aaf5dca488057592ee47305d9b3e10',
);
expect(entries[0].meta.ethereum.blockNumber).toEqual(pastEventsMock[0].blockNumber);
expect(entries[0].meta.ethereum.blockConfirmation).toBeGreaterThanOrEqual(1);
expect(entries[0].meta.ethereum.blockTimestamp).toBeDefined();
if (!entries[1].meta.ethereum) {
fail('entries[1].meta.ethereum does not exist');
return;
}
expect(entries[1].meta.ipfs).toMatchObject({
size: realSize1,
});
expect(entries[1].meta.ethereum.blockNumber).toEqual(pastEventsMock[1].blockNumber);
expect(entries[1].meta.ethereum.networkName).toEqual('private');
expect(entries[1].meta.ethereum.smartContractAddress).toEqual(
'0x345ca3e014aaf5dca488057592ee47305d9b3e10',
);
expect(entries[1].meta.ethereum.blockNumber).toEqual(pastEventsMock[1].blockNumber);
expect(entries[1].meta.ethereum.blockConfirmation).toBeGreaterThanOrEqual(1);
expect(entries[1].meta.ethereum.blockTimestamp).toBeDefined();
if (!entries[2].meta.ethereum) {
fail('entries[2].meta.ethereum does not exist');
return;
}
expect(entries[2].meta.ipfs).toMatchObject({
size: realSize2,
});
expect(entries[2].meta.ethereum.blockNumber).toEqual(pastEventsMock[2].blockNumber);
expect(entries[2].meta.ethereum.networkName).toEqual('private');
expect(entries[2].meta.ethereum.smartContractAddress).toEqual(
'0x345ca3e014aaf5dca488057592ee47305d9b3e10',
);
expect(entries[2].meta.ethereum.blockNumber).toEqual(pastEventsMock[2].blockNumber);
expect(entries[2].meta.ethereum.blockConfirmation).toBeGreaterThanOrEqual(1);
expect(entries[2].meta.ethereum.blockTimestamp).toBeDefined();
expect(entries.map(({ id }) => id)).toMatchObject([hash1, hash1, hash2]);
});
it('allows to retrieve all data', async () => {
// For this test, we don't want to use the ethereum metadata cache
// We want to force the retrieval of metadata with getPastEvents function
ethereumStorage.ethereumMetadataCache.saveDataIdMeta = async (_dataId, _meta) => {};
// These contents have to be appended in order to check their size
await ethereumStorage.append(content1);
await ethereumStorage.append(content2);
const { entries } = await ethereumStorage.getData();
if (!entries[0].meta.ethereum) {
fail('entries[0].meta.ethereum does not exist');
return;
}
expect(entries[0].meta.ipfs).toMatchObject({
size: realSize1,
});
expect(entries[0].meta.ethereum.blockNumber).toEqual(pastEventsMock[0].blockNumber);
expect(entries[0].meta.ethereum.networkName).toEqual('private');
expect(entries[0].meta.ethereum.smartContractAddress).toEqual(
'0x345ca3e014aaf5dca488057592ee47305d9b3e10',
);
expect(entries[0].meta.ethereum.blockNumber).toEqual(pastEventsMock[0].blockNumber);
expect(entries[0].meta.ethereum.blockConfirmation).toBeGreaterThanOrEqual(1);
expect(entries[0].meta.ethereum.blockTimestamp).toBeDefined();
if (!entries[1].meta.ethereum) {
fail('entries[1].meta.ethereum does not exist');
return;
}
expect(entries[1].meta.ipfs).toMatchObject({
size: realSize1,
});
expect(entries[1].meta.ethereum.blockNumber).toEqual(pastEventsMock[0].blockNumber);
expect(entries[1].meta.ethereum.networkName).toEqual('private');
expect(entries[1].meta.ethereum.smartContractAddress).toEqual(
'0x345ca3e014aaf5dca488057592ee47305d9b3e10',
);
expect(entries[1].meta.ethereum.blockNumber).toEqual(pastEventsMock[0].blockNumber);
expect(entries[1].meta.ethereum.blockConfirmation).toBeGreaterThanOrEqual(1);
expect(entries[1].meta.ethereum.blockTimestamp).toBeDefined();
if (!entries[2].meta.ethereum) {
fail('entries[2].meta.ethereum does not exist');
return;
}
expect(entries[2].meta.ipfs).toMatchObject({
size: realSize2,
});
expect(entries[2].meta.ethereum.blockNumber).toEqual(pastEventsMock[2].blockNumber);
expect(entries[2].meta.ethereum.networkName).toEqual('private');
expect(entries[2].meta.ethereum.smartContractAddress).toEqual(
'0x345ca3e014aaf5dca488057592ee47305d9b3e10',
);
expect(entries[2].meta.ethereum.blockNumber).toEqual(pastEventsMock[2].blockNumber);
expect(entries[2].meta.ethereum.blockConfirmation).toBeGreaterThanOrEqual(1);
expect(entries[2].meta.ethereum.blockTimestamp).toBeDefined();
expect(entries.map(({ content }) => content)).toMatchObject([content1, content1, content2]);
expect(entries.map(({ id }) => id)).toMatchObject([hash1, hash1, hash2]);
});
it('doest get meta data if the fees are too low', async () => {
// For this test, we don't want to use the ethereum metadata cache
// We want to force the retrieval of metadata with getPastEvents function
ethereumStorage.ethereumMetadataCache.saveDataIdMeta = async (_dataId, _meta) => {};
ethereumStorage.smartContractManager.getEntriesFromEthereum =
async (): Promise<StorageTypes.IEthereumEntriesWithLastTimestamp> => {
return {
ethereumEntries: [
{
feesParameters: { contentSize: 1 },
hash: hash1,
meta: {
blockConfirmation: 1561192254600,
blockNumber: 1,
blockTimestamp: 1561191682,
networkName: 'private',
smartContractAddress: '0x345ca3e014aaf5dca488057592ee47305d9b3e10',
transactionHash: '0xa',
},
},
],
lastTimestamp: 0,
};
};
const result = await ethereumStorage.getData();
expect(result.entries.length).toBe(0);
});
it('append and read with no parameter should throw an error', async () => {
await expect(ethereumStorage.append('')).rejects.toThrowError('No content provided');
await expect(ethereumStorage.read('')).rejects.toThrowError('No id provided');
});
it('append content with an invalid web3 connection should throw an error', async () => {
await expect(
ethereumStorage.updateEthereumNetwork(invalidHostWeb3Connection),
).rejects.toThrowError(
'Ethereum node is not accessible: Error: Error when trying to reach Web3 provider: Error: Invalid JSON RPC response: ""',
);
});
it('getData should throw an error when data from getEntriesFromEthereum are incorrect', async () => {
// Mock getEntriesFromEthereum of smartContractManager to return unexpected promise value
ethereumStorage.smartContractManager.getEntriesFromEthereum = (): Promise<any> => {
return Promise.resolve({
ethereumEntries: [
{
feesParameters: { contentSize: 10 },
meta: {} as StorageTypes.IEthereumMetadata,
} as StorageTypes.IEthereumEntry,
],
lastTimestamp: 0,
});
};
await expect(ethereumStorage.getData()).rejects.toThrowError(
'The event log has no hash or feesParameters',
);
// Test with no meta
ethereumStorage.smartContractManager.getEntriesFromEthereum =
(): Promise<StorageTypes.IEthereumEntriesWithLastTimestamp> => {
return Promise.resolve({
ethereumEntries: [
{
feesParameters: { contentSize: 10 },
hash: '0xad',
} as StorageTypes.IEthereumEntry,
],
lastTimestamp: 0,
});
};
await expect(ethereumStorage.getData()).rejects.toThrowError('The event log has no metadata');
});
it('allows to read several files', async () => {
const content = [content1, content2];
const realSizes = [realSize1, realSize2];
const r1 = await ethereumStorage.append(content1);
await new Promise((r) => r1.on('confirmed', r));
const r2 = await ethereumStorage.append(content2);
await new Promise((r) => r2.on('confirmed', r));
const results = await ethereumStorage.readMany([hash1, hash2]);
results.forEach((result, index) => {
expect(result.meta.ethereum).toBeDefined();
expect(result.content).toBe(content[index]);
expect(result.meta.ipfs).toMatchObject({
size: realSizes[index],
});
expect(result.meta.ethereum?.blockNumber).toEqual(10);
expect(result.meta.ethereum?.networkName).toEqual('private');
expect(result.meta.ethereum?.smartContractAddress).toEqual(
'0x345ca3e014aaf5dca488057592ee47305d9b3e10',
);
expect(result.meta.ethereum?.blockConfirmation).toBeGreaterThanOrEqual(1);
expect(result.meta.ethereum?.blockTimestamp).toBeDefined();
});
});
it('allows to read hash on IPFS with retries', async () => {
// Mock to test IPFS read retry
ethereumStorage.smartContractManager.getEntriesFromEthereum =
(): Promise<StorageTypes.IEthereumEntriesWithLastTimestamp> => {
return Promise.resolve({
ethereumEntries: [
{
feesParameters: { contentSize: 10 },
hash: '0x0',
meta: {},
} as StorageTypes.IEthereumEntry,
{
feesParameters: { contentSize: 10 },
hash: '0x1',
meta: {},
} as StorageTypes.IEthereumEntry,
{
feesParameters: { contentSize: 10 },
hash: '0x2',
meta: {},
} as StorageTypes.IEthereumEntry,
{
feesParameters: { contentSize: 10 },
hash: '0x3',
meta: {},
} as StorageTypes.IEthereumEntry,
{
feesParameters: { contentSize: 10 },
hash: '0x4',
meta: {},
} as StorageTypes.IEthereumEntry,
{
feesParameters: { contentSize: 10 },
hash: '0x5',
meta: {},
} as StorageTypes.IEthereumEntry,
{
feesParameters: { contentSize: 10 },
hash: '0x6',
meta: {},
} as StorageTypes.IEthereumEntry,
],
lastTimestamp: 0,
});
};
// Store how many time we tried to read a specific hash
const hashTryCount: any = {};
// This mock simulates ipfsManager.read() when we try to read the hash on IPFS differente times
jest
.spyOn((ethereumStorage as any).ipfsStorage, 'read')
.mockImplementation(async (hash: any) => {
hashTryCount[hash] ? hashTryCount[hash]++ : (hashTryCount[hash] = 1);
switch (hash) {
case '0x0':
throw new Error(`File size (1) exceeds maximum file size of 0`);
case '0x1':
throw new Error('Ipfs object get request response cannot be parsed into JSON format');
case '0x2':
throw new Error('Ipfs object get failed');
case '0x3':
return {
content: '0000',
ipfsSize: 20,
} as StorageTypes.IIpfsObject;
case '0x4':
if (hashTryCount[hash] < 2) {
throw new IpfsConnectionError('Timeout');
}
return {
content: '0000',
ipfsSize: 10,
} as StorageTypes.IIpfsObject;
case '0x5':
if (hashTryCount[hash] < 3) {
throw new IpfsConnectionError('Timeout');
}
return {
content: '0000',
ipfsSize: 10,
} as StorageTypes.IIpfsObject;
case '0x6':
if (hashTryCount[hash] < 10) {
throw new IpfsConnectionError('Timeout');
}
return {
content: '0000',
ipfsSize: 10,
} as StorageTypes.IIpfsObject;
default:
fail(`ipfsManager.read() unrocognized hash: ${hash}`);
}
throw Error('expected error');
});
await ethereumStorage.getData();
// Check how many time we tried to get hashes
expect(hashTryCount).toMatchObject({
'0x0': 1,
'0x1': 1,
'0x2': 1,
'0x3': 1,
'0x4': 2,
'0x5': 2,
'0x6': 2,
});
});
it('getData returns an empty array if no hash was found', async () => {
ethereumStorage.smartContractManager.requestHashStorage.getPastEvents = () => [];
const result = await ethereumStorage.getData({ from: 10000, to: 10001 });
expect(result.entries).toMatchObject([]);
expect(typeof result.lastTimestamp).toBe('number');
});
});
describe('getIgnoredData', () => {
it('cannot get ignored data if not initialized', async () => {
const ethereumStorage = new EthereumStorage('localhost', ipfsStorage, web3Connection);
await expect(ethereumStorage.getIgnoredData()).rejects.toThrowError(
'Ethereum storage must be initialized',
);
});
it('can get ignored data', async () => {
const ethereumStorage = new EthereumStorage('localhost', ipfsStorage, web3Connection);
await ethereumStorage.initialize();
ethereumStorage.ignoredDataIds.getDataIdsToRetry = async (): Promise<
StorageTypes.IEthereumEntry[]
> => [
{
error: {
message: 'Ipfs read request response error: test purpose',
type: StorageTypes.ErrorEntries.IPFS_CONNECTION_ERROR,
},
feesParameters: {
contentSize: 3,
},
hash: 'hConnectionError',
meta: { blockTimestamp: 123 } as any,
},
];
jest.spyOn((ethereumStorage as any).ipfsStorage, 'read').mockImplementation(
async (): Promise<StorageTypes.IIpfsObject> => ({
content: 'ok',
ipfsLinks: [],
ipfsSize: 2,
}),
);
const entries = await ethereumStorage.getIgnoredData();
expect(entries.length).toBe(1);
expect(entries[0]).toEqual({
content: 'ok',
id: 'hConnectionError',
meta: {
ethereum: {
blockTimestamp: 123,
},
ipfs: {
size: 2,
},
state: 'confirmed',
storageType: 'ethereumIpfs',
timestamp: 123,
},
});
});
it('can get ignored data even if empty', async () => {
const ethereumStorage = new EthereumStorage('localhost', ipfsStorage, web3Connection);
await ethereumStorage.initialize();
const entries = await ethereumStorage.getIgnoredData();
// 'config wrong'
expect(entries.length).toBe(0);
});
});
describe('_getStatus()', () => {
it('can get status', async () => {
const ethereumStorage = new EthereumStorage('localhost', ipfsStorage, web3Connection);
await ethereumStorage.initialize();
await ethereumStorage.append(content1);
await ethereumStorage.getData();
const status = await ethereumStorage._getStatus();
expect(status.dataIds.count).toBeGreaterThanOrEqual(0);
expect(status.ignoredDataIds.count).toBeGreaterThanOrEqual(0);
expect(status.ethereum).toEqual({
creationBlockNumberHashStorage: 0,
currentProvider: 'http://localhost:8545',
hashStorageAddress: '0x345ca3e014aaf5dca488057592ee47305d9b3e10',
hashSubmitterAddress: '0xf25186b5081ff5ce73482ad761db0eb0d25abfbf',
maxConcurrency: 5,
maxRetries: undefined,
networkName: 'private',
retryDelay: undefined,
});
expect(status.ipfs).toBeDefined();
}, 10000);
});
}); | the_stack |
import {
convertSpotEventPluginSettings,
convertToBoolean,
convertToBooleanOptional,
convertToInt,
convertToIntOptional,
isValidDeviceMapping,
isValidInstanceProfile,
isValidSecurityGroup,
isValidTagSpecification,
validateArray,
validateProperty,
validateString,
validateStringOptional,
} from '../conversion';
import {
PluginSettings,
SpotFleetSecurityGroupId,
BlockDeviceMappingProperty,
SpotFleetInstanceProfile,
} from '../types';
describe('convertSpotEventPluginSettings()', () => {
test('does not convert properties with correct types', () => {
// GIVEN
const defaultPluginConfig = {
AWSInstanceStatus: 'Disabled',
DeleteInterruptedSlaves: false,
DeleteTerminatedSlaves: false,
IdleShutdown: 10,
Logging: 'Standard',
PreJobTaskMode: 'Conservative',
Region: 'eu-west-1',
ResourceTracker: true,
StaggerInstances: 50,
State: 'Disabled',
StrictHardCap: false,
};
const defaultConvertedPluginConfig = {
AWSInstanceStatus: 'Disabled',
DeleteInterruptedSlaves: false,
DeleteTerminatedSlaves: false,
IdleShutdown: 10,
Logging: 'Standard',
PreJobTaskMode: 'Conservative',
Region: 'eu-west-1',
ResourceTracker: true,
StaggerInstances: 50,
State: 'Disabled',
StrictHardCap: false,
};
// WHEN
const returnValue = convertSpotEventPluginSettings(defaultPluginConfig);
// THEN
expect(returnValue).toEqual(defaultConvertedPluginConfig);
});
test('converts properties of type string', () => {
// GIVEN
const defaultPluginConfig = {
AWSInstanceStatus: 'Disabled',
DeleteInterruptedSlaves: 'false',
DeleteTerminatedSlaves: 'false',
IdleShutdown: '10',
Logging: 'Standard',
PreJobTaskMode: 'Conservative',
Region: 'eu-west-1',
ResourceTracker: 'true',
StaggerInstances: '50',
State: 'Disabled',
StrictHardCap: 'false',
};
const defaultConvertedPluginConfig = {
AWSInstanceStatus: 'Disabled',
DeleteInterruptedSlaves: false,
DeleteTerminatedSlaves: false,
IdleShutdown: 10,
Logging: 'Standard',
PreJobTaskMode: 'Conservative',
Region: 'eu-west-1',
ResourceTracker: true,
StaggerInstances: 50,
State: 'Disabled',
StrictHardCap: false,
};
// WHEN
// Need this trick so TS allows to pass config with string properties.
const config = (defaultPluginConfig as unknown) as PluginSettings;
const returnValue = convertSpotEventPluginSettings(config);
// THEN
expect(returnValue).toEqual(defaultConvertedPluginConfig);
});
});
describe('convertToInt()', () => {
test.each<[any, number]>([
['10', 10],
[10, 10],
])('correctly converts %p to %p', (input: any, expected: number) => {
// WHEN
const returnValue = convertToInt(input, 'propertyName');
// THEN
expect(returnValue).toBe(expected);
});
test.each([
10.6,
[],
{},
'string',
undefined,
])('throws an error with %p', input => {
// WHEN
const propertyName = 'propertyName';
function callingConvertToInt() {
convertToInt(input, propertyName);
}
// THEN
expect(callingConvertToInt).toThrowError(`The value of ${propertyName} should be an integer. Received: ${input}`);
});
});
describe('convertToIntOptional()', () => {
test.each<[any, number | undefined]>([
['10', 10],
[10, 10],
[undefined, undefined],
])('correctly converts %p to %p', (input: any, expected: number | undefined) => {
// WHEN
const returnValue = convertToIntOptional(input, 'propertyName');
// THEN
expect(returnValue).toBe(expected);
});
test.each([
10.6,
[],
{},
'string',
])('throws an error with %p', input => {
// WHEN
const propertyName = 'propertyName';
function callingConvertToIntOptional() {
convertToIntOptional(input, propertyName);
}
// THEN
expect(callingConvertToIntOptional).toThrowError(`The value of ${propertyName} should be an integer. Received: ${input}`);
});
});
describe('convertToBoolean()', () => {
test.each<[any, boolean]>([
[true, true],
['true', true],
[false, false],
['false', false],
])('correctly converts %p to %p', (input: any, expected: boolean) => {
// WHEN
const returnValue = convertToBoolean(input, 'property');
// THEN
expect(returnValue).toBe(expected);
});
test.each([
10.6,
[],
{},
'string',
undefined,
])('throws an error with %p', input => {
// WHEN
const propertyName = 'propertyName';
function callingConvertToBoolean() {
convertToBoolean(input, propertyName);
}
// THEN
expect(callingConvertToBoolean).toThrowError(`The value of ${propertyName} should be a boolean. Received: ${input}`);
});
});
describe('convertToBooleanOptional()', () => {
test.each<[any, boolean | undefined]>([
[true, true],
['true', true],
[false, false],
['false', false],
[undefined, undefined],
])('correctly converts %p to %p', (input: any, expected: boolean | undefined) => {
// WHEN
const returnValue = convertToBooleanOptional(input, 'property');
// THEN
expect(returnValue).toBe(expected);
});
test.each([
10.6,
[],
{},
'string',
])('throws an error with %p', input => {
// WHEN
const propertyName = 'propertyName';
function callingConvertToBooleanOptional() {
convertToBooleanOptional(input, propertyName);
}
// THEN
expect(callingConvertToBooleanOptional).toThrowError(`The value of ${propertyName} should be a boolean. Received: ${input}`);
});
});
describe('validateString()', () => {
test.each<[any, string]>([
['string', 'string'],
['10', '10'],
['true', 'true'],
])('correctly converts %p to %p', (input: any, expected: string) => {
// WHEN
const returnValue = validateString(input, 'propertyName');
// THEN
expect(returnValue).toBe(expected);
});
test.each([
10,
[],
{},
undefined,
])('throws an error with %p', input => {
// WHEN
const propertyName = 'propertyName';
function callingValidateString() {
validateString(input, propertyName);
}
// THEN
expect(callingValidateString).toThrowError(`The value of ${propertyName} should be a string. Received: ${input} of type ${typeof(input)}`);
});
});
describe('validateStringOptional()', () => {
test.each<[any, string | undefined]>([
['string', 'string'],
['10', '10'],
['true', 'true'],
[undefined, undefined],
])('correctly converts %p to %p', (input: any, expected: string | undefined) => {
// WHEN
const returnValue = validateStringOptional(input, 'propertyName');
// THEN
expect(returnValue).toBe(expected);
});
test.each([
10,
[],
{},
])('throws an error with %p', input => {
// WHEN
const propertyName = 'propertyName';
function callingValidateStringOptional() {
validateStringOptional(input, propertyName);
}
// THEN
expect(callingValidateStringOptional).toThrowError(`The value of ${propertyName} should be a string. Received: ${input} of type ${typeof(input)}`);
});
});
describe('validateArray', () => {
test.each([
undefined,
{},
[],
])('throws with invalid input %p', (invalidInput: any) => {
// WHEN
const propertyName = 'propertyName';
function callingValidateArray() {
validateArray(invalidInput, propertyName);
}
// THEN
expect(callingValidateArray).toThrowError(`${propertyName} should be an array with at least one element.`);
});
test('passes with not empty array', () => {
// GIVEN
const nonEmptyArray = ['value'];
// WHEN
function callingValidateArray() {
validateArray(nonEmptyArray, 'propertyName');
}
// THEN
expect(callingValidateArray).not.toThrowError();
});
});
describe('isValidSecurityGroup', () => {
// Valid security groups
const validSecurityGroup: SpotFleetSecurityGroupId = {
GroupId: 'groupId',
};
// Invalid security groups
const groupIdNotString = {
GroupId: 10,
};
const noGroupId = {
};
test.each([
undefined,
[],
'',
groupIdNotString,
noGroupId,
])('returns false with invalid input %p', (invalidInput: any) => {
// WHEN
const result = isValidSecurityGroup(invalidInput);
// THEN
expect(result).toBeFalsy();
});
test('returns true with a valid input', () => {
// WHEN
const result = isValidSecurityGroup(validSecurityGroup);
// THEN
expect(result).toBeTruthy();
});
});
describe('isValidTagSpecification', () => {
// Valid tag specifications
const validTagSpecification = {
ResourceType: 'type',
Tags: [{
Key: 'key',
Value: 'value',
}],
};
// Invalid tag specifications
const noResourceType = {
};
const resourceTypeNotSting = {
ResourceType: 10,
};
const noTags = {
ResourceType: 'type',
};
const tagsNotArray = {
ResourceType: 'type',
Tags: '',
};
const tagElementUndefined = {
ResourceType: 'type',
Tags: [undefined],
};
const tagElementWrongType = {
ResourceType: 'type',
Tags: [''],
};
const tagElementNoKey = {
ResourceType: 'type',
Tags: [{
}],
};
const tagElementKeyNotString = {
ResourceType: 'type',
Tags: [{
Key: 10,
}],
};
const tagElementNoValue = {
ResourceType: 'type',
Tags: [{
Key: 'key',
}],
};
const tagElementValueNotString = {
ResourceType: 'type',
Tags: [{
Key: 'key',
Value: 10,
}],
};
test.each([
undefined,
[],
'',
noResourceType,
resourceTypeNotSting,
noTags,
tagsNotArray,
tagElementUndefined,
tagElementWrongType,
tagElementNoKey,
tagElementKeyNotString,
tagElementNoValue,
tagElementValueNotString,
])('returns false with invalid input %p', (invalidInput: any) => {
// WHEN
const result = isValidTagSpecification(invalidInput);
// THEN
expect(result).toBeFalsy();
});
test('returns true with a valid input', () => {
// WHEN
const result = isValidTagSpecification(validTagSpecification);
// THEN
expect(result).toBeTruthy();
});
});
describe('isValidDeviceMapping', () => {
test.each([
undefined,
[],
'',
])('returns false with invalid input %p', (invalidInput: any) => {
// WHEN
const result = isValidDeviceMapping(invalidInput);
// THEN
expect(result).toBeFalsy();
});
test('returns true with a valid input', () => {
// GIVEN
const anyObject = {} as unknown;
// WHEN
const result = isValidDeviceMapping(anyObject as BlockDeviceMappingProperty);
// THEN
expect(result).toBeTruthy();
});
});
describe('isValidInstanceProfile', () => {
// Valid instance profiles
const validInstanceProfile: SpotFleetInstanceProfile = {
Arn: 'arn',
};
// Invalid instance profiles
const noArn = {
};
const arnNotString = {
Arn: 10,
};
test.each([
undefined,
[],
'',
noArn,
arnNotString,
])('returns false with invalid input %p', (invalidInput: any) => {
// WHEN
const result = isValidInstanceProfile(invalidInput);
// THEN
expect(result).toBeFalsy();
});
test('returns true with a valid input', () => {
// WHEN
const result = isValidInstanceProfile(validInstanceProfile);
// THEN
expect(result).toBeTruthy();
});
});
describe('validateProperty', () => {
test('throws with invalid input', () => {
// WHEN
const propertyName = 'propertyName';
function returnFalse(_input: any) {
return false;
}
function callingValidateProperty() {
validateProperty(returnFalse, 'anyValue', propertyName);
}
// THEN
expect(callingValidateProperty).toThrowError(`${propertyName} type is not valid.`);
});
test('passes with a valid input', () => {
// WHEN
function returnTrue(_input: any) {
return true;
}
function callingValidateProperty() {
validateProperty(returnTrue, 'anyValue', 'propertyName');
}
// THEN
expect(callingValidateProperty).not.toThrowError();
});
}); | the_stack |
import * as React from 'react';
import { useState, useEffect, useReducer } from 'react';
import styled from 'styled-components';
import * as actions from '../../actions/actions';
import Tables from '../../components/mainpanel/Tables';
import changePinnedStatus from '../../reducers/ChangePinnedStatus';
import { Text } from "grommet";
import { Pin, CircleInformation, Halt } from 'grommet-icons';
const SEmptyState = styled.div`
margin: auto;
text-align: center;
padding: 20px;
`
const TableTitle = styled.p`
text-align: center;
font-size: 90%;
padding: 5px;
overflow-wrap: break-word;
:hover {
transform: scale(1.01);
}
`;
const STabWrapper = styled.span`
font-size: 14px;
transition: all 0.2s;
:hover {
transform: scale(1.1);
}
`
const SIndTablButtons = styled.div`
width: 100%;
display: flex;
align-items: center;
justify-content: center;
border-bottom: 1px solid grey;
padding-top: 3px;
`
const TempWrapper = styled.div`
overflow: scroll;
height: 100%;
width: 100%;
display: flex;
flex-wrap: wrap;
padding: 5px 15px;
`
interface ITableWrapperProps {
highlightForRelationship: string;
}
const TableWrapper = styled.div<ITableWrapperProps>`
width: 150px;
max-height: 200px;
border-radius: 3px;
overflow: hidden;
margin: 8px;
border: ${({ highlightForRelationship }) => (highlightForRelationship == 'true' ? '1px solid transparent' : '1px solid grey')};
box-shadow: ${({ highlightForRelationship }) => (highlightForRelationship == 'true' ? '0px 0px 8px #4B70FE' : 'none')};
`;
interface IForeignKey {
table: string;
column: string;
}
let isPrimaryKey: string;
let isForeignKey: string;
let primaryKeyTableForForeignKey: string;
let primaryKeyColumn: string;
let selectedTableName: string;
let selectedColumnName: string;
interface ITablesContainerProps {
data: any;
userInputForTables: string;
activeTableInPanel: any;
selectedForQueryTables: any;
relationships: any;
captureSelectedTable: (any) => any;
captureQuerySelections: (any) => any;
}
const TablesContainer: React.SFC<ITablesContainerProps> = ({
userInputForTables,
activeTableInPanel,
selectedForQueryTables,
data,
captureSelectedTable,
captureQuerySelections,
relationships
}) => {
const [mouseOver, setMouseOver] = useState(); //data to detect if mouse is over a pk or fk
const [filteredTables, setFilteredTables] = useState([]);
const [pinnedTables, setPinnedTables] = useState([]);
const [pinnedTableNames, dispatchPinned] = useReducer(changePinnedStatus, []);
const [foreignKeysAffected, setForeignKeysAffected] = useState([]);
const [primaryKeyAffected, setPrimaryKeyAffected] = useState([
{
primaryKeyTable: '',
primaryKeyColumn: ''
}
]);
const [tablesRelated, setTablesRelated] = useState([]);
useEffect(() => {
const temptables = [];
for (let table in relationships) {
temptables.push(table);
for (let i = 0; i < relationships[table].length; i++) {
temptables.push(relationships[table][i].fktablename)
}
setTablesRelated(temptables);
}
setTablesRelated(temptables);
}, [captureQuerySelections])
useEffect(() => {
if (!mouseOver) {
//Resets all relationships
setPrimaryKeyAffected([{ primaryKeyTable: '', primaryKeyColumn: '' }]);
setForeignKeysAffected([]);
}
//Determines which rows should be highlighted
if (mouseOver) {
if (isForeignKey == 'true') {
setPrimaryKeyAffected([
{
primaryKeyTable: primaryKeyTableForForeignKey,
primaryKeyColumn: primaryKeyColumn
}
]);
}
if (isPrimaryKey === 'true') {
const allForeignKeys: IForeignKey[] = [];
data.forEach((table): void => {
table.foreignKeys.forEach((foreignkey): void => {
if (
foreignkey.foreign_table_name === selectedTableName &&
foreignkey.foreign_column_name === selectedColumnName
)
allForeignKeys.push({
table: foreignkey.table_name,
column: foreignkey.column_name
});
});
});
setForeignKeysAffected(allForeignKeys);
}
}
}, [data, mouseOver, selectedForQueryTables]);
//Builds out tables to display
useEffect((): void => {
const pinned = [];
const filtered = [];
if (data.length > 0) {
const regex = new RegExp(userInputForTables);
data.forEach(table => {
let highlightForRelationship = 'false';
if (tablesRelated.includes(table.table_name)) {
highlightForRelationship = 'true';
}
if (pinnedTableNames.includes(table.table_name)) {
pinned.push(
<TableWrapper highlightForRelationship={highlightForRelationship}>
<TableTitle data-tablename={table.table_name}>{table.table_name}</TableTitle>
<SIndTablButtons>
<STabWrapper>
<Pin
style={{ height: '15px', cursor: 'pointer' }}
data-pinned={table.table_name}
onClick={() =>
dispatchPinned(actions.removeFromPinned(table.table_name))
}
pinned='true'
color="#FF98BB"
/>
</STabWrapper>
<STabWrapper>
<CircleInformation
style={{ height: '15px', cursor: 'pointer' }}
onClick={captureSelectedTable}
data-tablename={table.table_name}
color={(table.table_name === activeTableInPanel.table_name) ? "#149BD2" : '#485360'}
/>
</STabWrapper>
</SIndTablButtons>
<Tables
selectedForQueryTables={selectedForQueryTables}
captureQuerySelections={captureQuerySelections}
activeTableInPanel={activeTableInPanel}
tableName={table.table_name}
columns={table.columns}
primarykey={table.primaryKey}
foreignkeys={table.foreignKeys}
primaryKeyAffected={primaryKeyAffected}
foreignKeysAffected={foreignKeysAffected}
captureMouseEnter={e => {
isPrimaryKey = e.target.dataset.isprimarykey;
isForeignKey = e.target.dataset.isforeignkey;
primaryKeyTableForForeignKey =
e.target.dataset.foreignkeytable;
primaryKeyColumn = e.target.dataset.foreignkeycolumn;
selectedTableName = e.target.dataset.tablename;
selectedColumnName = e.target.dataset.columnname;
setMouseOver(true);
}}
captureMouseExit={() => {
setMouseOver(false);
}}
key={table.table_name}
/>
</TableWrapper>
);
} else if (regex.test(table.table_name)) {
filtered.push(
<TableWrapper highlightForRelationship={highlightForRelationship}>
<TableTitle data-tablename={table.table_name}>{table.table_name}</TableTitle>
<SIndTablButtons>
<STabWrapper>
<Pin
style={{ height: '15px', cursor: 'pointer' }}
data-pinned={table.table_name}
onClick={() =>
dispatchPinned(actions.addToPinned(table.table_name))
}
pinned='false'
color="#485360"
/>
</STabWrapper>
<STabWrapper>
<CircleInformation
onClick={captureSelectedTable}
data-tablename={table.table_name}
style={{ height: '15px', cursor: 'pointer' }}
color={(table.table_name === activeTableInPanel.table_name) ? "#149BD2" : '#485360'}
/>
</STabWrapper>
</SIndTablButtons>
<Tables
selectedForQueryTables={selectedForQueryTables}
captureQuerySelections={captureQuerySelections}
activeTableInPanel={activeTableInPanel}
tableName={table.table_name}
columns={table.columns}
primarykey={table.primaryKey}
foreignkeys={table.foreignKeys}
primaryKeyAffected={primaryKeyAffected}
foreignKeysAffected={foreignKeysAffected}
captureMouseEnter={e => {
isPrimaryKey = e.target.dataset.isprimarykey;
isForeignKey = e.target.dataset.isforeignkey;
primaryKeyTableForForeignKey =
e.target.dataset.foreignkeytable;
primaryKeyColumn = e.target.dataset.foreignkeycolumn;
selectedTableName = e.target.dataset.tablename;
selectedColumnName = e.target.dataset.columnname;
setMouseOver(true);
}}
captureMouseExit={() => {
setMouseOver(false);
}}
key={table.table_name}
/>
</TableWrapper>
);
}
});
setFilteredTables(filtered);
setPinnedTables(pinned);
}
}, [
data,
foreignKeysAffected,
primaryKeyAffected,
userInputForTables,
pinnedTableNames,
activeTableInPanel,
selectedForQueryTables
]);
if (pinnedTables.length || filteredTables.length) {
return (
<TempWrapper>
{pinnedTables}
{filteredTables}
</TempWrapper>
)
}
return (
<SEmptyState>
<Text>
<Halt /><br />
Sorry, there are no tables that matched your search. <br /> Please search again.
</Text>
</SEmptyState>
)
}
export default TablesContainer; | the_stack |
import path = require('path');
import underscore = require('underscore');
import agile_keychain = require('./agile_keychain');
import agile_keychain_crypto = require('./agile_keychain_crypto');
import asyncutil = require('./base/asyncutil');
import crypto = require('./base/crypto');
import exportLib = require('./export');
import item_builder = require('./item_builder');
import item_store = require('./item_store');
import key_agent = require('./key_agent');
import nodefs = require('./vfs/node');
import password_gen = require('./password_gen');
import testLib = require('./test');
import vfs = require('./vfs/vfs');
import vfs_util = require('./vfs/util');
class TestCase {
/** Relative path to the vault within the test data dir */
path: string;
/** Master password for the test vault. */
password: string;
/** Path to .1pif file containing expected
* decrypted data.
*/
itemDataPath: string;
}
const TEST_VAULTS: TestCase[] = [
{
path: 'test.agilekeychain',
password: 'logMEin',
itemDataPath: 'test.1pif',
},
];
let fs = new nodefs.FileVFS('lib/test-data');
class ItemAndContent {
item: item_store.Item;
content: item_store.ItemContent;
}
function createEmptyVault() {
const VAULT_PASS = 'logMEin';
const VAULT_PASS_ITER = 100;
let fs = new nodefs.FileVFS('/');
let vault: agile_keychain.Vault;
return vfs_util
.mktemp(fs, testLib.tempDir(), 'vault.XXX')
.then(path => {
return agile_keychain.Vault.createVault(
fs,
path,
VAULT_PASS,
'',
VAULT_PASS_ITER
);
})
.then(vault_ => {
vault = vault_;
return vault_.unlock(VAULT_PASS);
})
.then(() => vault);
}
function createTestVault() {
let sourcePath = path.resolve('lib/test-data');
let copyPath = testLib.tempDir() + '/copy.agilekeychain';
let vault: agile_keychain.Vault;
let fs = new nodefs.FileVFS('/');
return vfs_util
.rmrf(fs, copyPath)
.then(() => {
return fs.stat(sourcePath + '/test.agilekeychain');
})
.then(srcFolder => {
return vfs_util.cp(fs, srcFolder, copyPath);
})
.then(() => {
var newVault = new agile_keychain.Vault(fs, copyPath);
vault = newVault;
return newVault.unlock('logMEin');
})
.then(() => {
return vault;
});
}
testLib.addTest('Import item from .1pif file', assert => {
var importer = new exportLib.PIFImporter();
var actualItems = importer.importItems(fs, 'test.1pif');
return actualItems.then(items => {
assert.equal(items.length, 1, 'Imported expected number of items');
var expectedItem = agile_keychain.fromAgileKeychainItem(null, {
updatedAt: 1398413120,
title: 'Facebook',
securityLevel: 'SL5',
secureContents: {
sections: [],
URLs: [
{
label: 'website',
url: 'facebook.com',
},
],
notesPlain: '',
fields: [
{
value: 'john.doe@gmail.com',
id: '',
name: 'username',
type: 'T',
designation: 'username',
},
{
value: 'Wwk-ZWc-T9MO',
id: '',
name: 'password',
type: 'P',
designation: 'password',
},
],
htmlMethod: '',
htmlAction: '',
htmlID: '',
},
typeName: 'webforms.WebForm',
uuid: 'CA20BB325873446966ED1F4E641B5A36',
createdAt: 1398413120,
location: 'facebook.com',
folderUuid: '',
faveIndex: 0,
trashed: false,
openContents: {
tags: null,
scope: '',
},
});
var diff = testLib.compareObjects(items[0], expectedItem);
assert.equal(diff.length, 0, 'Actual/expected imported items match');
});
});
// set of tests which open a vault, unlock it,
// fetch all items and compare to an expected set
// of items in .1pif format
testLib.addTest('Compare vaults against .1pif files', assert => {
var importer = new exportLib.PIFImporter();
var done = TEST_VAULTS.map(tst => {
var expectedItems = importer.importItems(fs, tst.itemDataPath);
var vault = new agile_keychain.Vault(fs, tst.path);
var items: item_store.Item[];
var actualItems = vault
.unlock(tst.password)
.then(() => {
return vault.listItems();
})
.then(_items => {
items = _items;
var contents: Promise<item_store.ItemContent>[] = [];
items.forEach(item => {
contents.push(item.getContent());
});
return Promise.all(contents);
})
.then(contents => {
var itemContents: ItemAndContent[] = [];
items.forEach((item, index) => {
itemContents.push({ item: item, content: contents[index] });
});
return itemContents;
});
return asyncutil
.all2([expectedItems, actualItems])
.then(expectedActual => {
var expectedAry = <item_store.Item[]>expectedActual[0];
var actualAry = <ItemAndContent[]>expectedActual[1];
expectedAry.sort((itemA, itemB) => {
return itemA.uuid.localeCompare(itemB.uuid);
});
actualAry.sort((itemA, itemB) => {
return itemA.item.uuid.localeCompare(itemB.item.uuid);
});
assert.equal(
expectedAry.length,
actualAry.length,
'actual and expected vault item counts match'
);
for (var i = 0; i < expectedAry.length; i++) {
var expectedItem = expectedAry[i];
var actualItem = actualAry[i].item;
actualItem.setContent(actualAry[i].content);
var diff = testLib.compareObjects(
expectedItem,
actualItem,
['root/store', 'root/encrypted', 'root/revision'],
[
'root/securityLevel',
'root/createdAt',
'root/faveIndex',
'root/openContents',
]
);
if (diff.length > 0) {
console.log(diff);
}
assert.equal(
diff.length,
0,
'actual and expected item contents match'
);
}
});
});
return Promise.all(done);
});
function createCryptos(): agile_keychain_crypto.Crypto[] {
return [new agile_keychain_crypto.NodeCrypto()];
}
testLib.addTest('AES encrypt/decrypt', assert => {
let done: Promise<void>[] = [];
let impls = createCryptos();
for (var impl of impls) {
var plainText = 'foo bar';
var key = 'ABCDABCDABCDABCD';
var iv = 'EFGHEFGHEFGHEFGH';
var cipherText = impl.aesCbcEncrypt(key, plainText, iv);
done.push(
cipherText
.then(cipherText => {
return impl.aesCbcDecrypt(key, cipherText, iv);
})
.then(decrypted => {
assert.equal(decrypted, plainText);
})
);
}
return Promise.all(done);
});
testLib.addTest('Encrypt/decrypt item data', assert => {
let impls = createCryptos();
let done: Promise<void>[] = [];
for (let impl of impls) {
let itemData = JSON.stringify({ secret: 'secret-data' });
let itemPass = 'item password';
let encrypted = agile_keychain_crypto.encryptAgileKeychainItemData(
impl,
itemPass,
itemData
);
done.push(
encrypted
.then(encrypted => {
return agile_keychain_crypto.decryptAgileKeychainItemData(
impl,
itemPass,
encrypted
);
})
.then(decrypted => {
assert.equal(decrypted, itemData);
})
);
}
return Promise.all(done);
});
testLib.addTest('New item UUID', assert => {
var item = new item_store.Item();
assert.ok(item.uuid.match(/[0-9A-F]{32}/) != null);
});
testLib.addTest('Save item', assert => {
return createTestVault().then(vault => {
let item = new item_store.Item(vault);
item.title = 'New Test Item';
item.locations.push('mysite.com');
let content = item_store.ContentUtil.empty();
content.urls.push({
url: 'mysite.com',
label: 'website',
});
item.setContent(content);
return item
.save()
.then(() => {
return vault.loadItem(item.uuid);
})
.then(loadedItem => {
// check overview data matches
assert.equal(item.title, loadedItem.item.title);
// check item content matches
testLib.assertEqual(assert, content, loadedItem.content);
// check new item appears in vault list
return vault.listItems().then(items => {
// check that selected properties match
var comparedProps: any[] = [
'title',
'uuid',
'trashed',
'typeName',
'location',
'updatedAt',
];
var actualOverview = underscore.find(
items,
item => item.uuid == loadedItem.item.uuid
);
testLib.assertEqual(
assert,
actualOverview,
loadedItem.item,
comparedProps
);
});
});
});
});
testLib.addTest('Update item', assert => {
return createTestVault().then(vault => {
var item = new item_store.Item(vault);
item.title = 'Original item title';
let content = item_store.ContentUtil.empty();
content.formFields.push({
id: '',
name: 'password',
type: item_store.FormFieldType.Password,
designation: 'password',
value: 'original-password',
});
content.urls.push({
label: 'website',
url: 'mysite.com',
});
item.setContent(content);
// get a date a couple of seconds in the past.
// After saving we'll check that the item's save date
// was updated to the current time.
//
// Note that item save dates are rounded down to the nearest
// second on save.
var originalSaveDate = new Date(Date.now() - 2000);
var loadedItem: item_store.ItemAndContent;
return item
.save()
.then(() => {
return vault.loadItem(item.uuid);
})
.then(loadedItem_ => {
loadedItem = loadedItem_;
var passwordField = underscore.find(
loadedItem.content.formFields,
field => {
return field.name == 'password';
}
);
assert.notEqual(passwordField, null);
assert.equal(passwordField.value, 'original-password');
assert.equal(
passwordField.type,
item_store.FormFieldType.Password
);
assert.equal(
item_store.ContentUtil.password(content),
'original-password'
);
loadedItem.item.title = 'New Item Title';
loadedItem.item.faveIndex = 42;
loadedItem.content.urls[0].url = 'newsite.com';
loadedItem.item.trashed = true;
passwordField.value = 'new-password';
loadedItem.item.setContent(loadedItem.content);
return loadedItem.item.save();
})
.then(() => {
return vault.loadItem(item.uuid);
})
.then(loadedItem_ => {
loadedItem = loadedItem_;
assert.equal(loadedItem.item.title, 'New Item Title');
assert.equal(loadedItem.item.faveIndex, 42);
assert.equal(loadedItem.item.trashed, true);
// check that Item.location property is updated
// to match URL list on save
assert.deepEqual(loadedItem.item.locations, ['newsite.com']);
// check that Item.updatedAt is updated on save
assert.ok(loadedItem.item.updatedAt > originalSaveDate);
let passwordField = underscore.find(
loadedItem.content.formFields,
field => {
return field.name == 'password';
}
);
assert.notEqual(passwordField, null);
assert.equal(passwordField.value, 'new-password');
assert.equal(
item_store.ContentUtil.password(loadedItem.content),
'new-password'
);
});
});
});
testLib.addTest('Remove item', assert => {
let item: item_store.Item;
let vault: agile_keychain.Vault;
return createTestVault()
.then(vault_ => {
vault = vault_;
return vault.loadItem('CA20BB325873446966ED1F4E641B5A36');
})
.then(item_ => {
item = item_.item;
assert.equal(item.title, 'Facebook');
assert.equal(item.typeName, item_store.ItemTypes.LOGIN);
assert.ok(item.isRegularItem());
var content = item_.content;
testLib.assertEqual(assert, content.urls, [
{ label: 'website', url: 'facebook.com' },
]);
var passwordField = underscore.find(content.formFields, field => {
return field.designation == 'password';
});
assert.ok(passwordField != null);
assert.equal(passwordField.value, 'Wwk-ZWc-T9MO');
return item.remove();
})
.then(() => {
// check that all item-specific data has been erased.
// Only a tombstone should be left behind
assert.ok(item.isTombstone());
assert.ok(!item.isRegularItem());
assert.equal(item.title, 'Unnamed');
assert.equal(item.typeName, item_store.ItemTypes.TOMBSTONE);
return asyncutil.result(
vault.fs.stat(
`${vault.path}/data/default/${item.uuid}.1password`
)
);
})
.then(statResult => {
// the .1password file should have been removed, with
// just a tombstone entry left in the contents.js file
assert.equal(statResult.value, undefined);
assert.ok(statResult.error instanceof vfs.VfsError);
assert.equal(
(<vfs.VfsError>statResult.error).type,
vfs.ErrorType.FileNotFound
);
});
});
testLib.addTest('listItems() should not list tombstones', assert => {
let testVault: TestVault;
return createTestVaultWithNItems(1)
.then(testVault_ => {
testVault = testVault_;
return testVault_.vault.listItems();
})
.then(listedItems => {
assert.equal(listedItems.length, 1);
return testVault.items[0].remove();
})
.then(() => {
return testVault.vault.listItems();
})
.then(listedItems => {
assert.equal(listedItems.length, 0);
return testVault.vault.listItems({ includeTombstones: true });
})
.then(listedItems => {
assert.equal(listedItems.length, 1);
});
});
testLib.addTest('Generate Passwords', assert => {
var usedPasswords = new Set<string>();
for (var len = 4; len < 20; len++) {
for (var k = 0; k < 10; k++) {
var pass = password_gen.generatePassword(len);
assert.ok(pass.match(/[A-Z]/) != null);
assert.ok(pass.match(/[a-z]/) != null);
assert.ok(pass.match(/[0-9]/) != null);
assert.equal(pass.length, len);
assert.ok(!usedPasswords.has(pass));
usedPasswords.add(pass);
}
}
});
testLib.addTest('Encrypt/decrypt key (sync)', async assert => {
let password = 'test-pass';
let iterations = 100;
let salt = crypto.randomBytes(8);
let masterKey = crypto.randomBytes(1024);
const derivedKey = await key_agent.keyFromPassword(
password,
salt,
iterations
);
const encryptedKey = await key_agent.encryptKey(derivedKey, masterKey);
const decryptedKey = await key_agent.decryptKey(
derivedKey,
encryptedKey.key,
encryptedKey.validation
);
assert.equal(decryptedKey, masterKey);
const derivedKey2 = await key_agent.keyFromPassword(
'wrong-pass',
salt,
iterations
);
const result = await asyncutil.result(
key_agent.decryptKey(
derivedKey2,
encryptedKey.key,
encryptedKey.validation
)
);
assert.ok(result.error != null);
});
testLib.addTest('Encrypt/decrypt key (async)', assert => {
var password = ' test-pass-2';
var iterations = 100;
var salt = crypto.randomBytes(8);
var masterKey = crypto.randomBytes(1024);
let derivedKey: string;
return key_agent
.keyFromPassword(password, salt, iterations)
.then(derivedKey_ => {
derivedKey = derivedKey_;
return key_agent.encryptKey(derivedKey, masterKey);
})
.then(encryptedKey => {
return key_agent.decryptKey(
derivedKey,
encryptedKey.key,
encryptedKey.validation
);
})
.then(decryptedKey => {
assert.equal(decryptedKey, masterKey);
});
});
testLib.addTest('Create new vault', assert => {
let fs = new nodefs.FileVFS(testLib.tempDir());
let pass = 'test-new-vault-pass';
let hint = 'the-password-hint';
let vault: agile_keychain.Vault;
let keyIterations = 100;
let vaultDir = '/new-vault';
return vfs_util
.rmrf(fs, vaultDir + '.agilekeychain')
.then(() => {
return agile_keychain.Vault.createVault(
fs,
vaultDir,
pass,
hint,
keyIterations
);
})
.then(vault_ => {
vault = vault_;
return vault.unlock(pass);
})
.then(() => {
return vault.listItems();
})
.then(items => {
assert.equal(items.length, 0);
let item = new item_store.Item(vault);
item.title = 'Item in new vault';
let content = item_store.ContentUtil.empty();
content.urls.push({
url: 'foobar.com',
label: 'website',
});
item.setContent(content);
return item.save();
})
.then(() => {
return vault.listItems();
})
.then(items => {
assert.equal(items.length, 1);
return items[0].getContent();
})
.then(content => {
assert.equal(content.urls.length, 1);
assert.equal(content.urls[0].url, 'foobar.com');
return vault.passwordHint();
})
.then(savedHint => {
assert.equal(savedHint, hint);
});
});
testLib.addTest('Change vault password', assert => {
var vault: agile_keychain.Vault;
return createTestVault()
.then(vault_ => {
vault = vault_;
return vault.changePassword('wrong-pass', 'new-pass', 'new-hint');
})
.catch(err => {
assert.ok(err instanceof key_agent.DecryptionError);
return vault
.changePassword('logMEin', 'new-pass', 'new-hint')
.then(() => {
return vault.unlock('new-pass');
})
.then(() => {
return vault.passwordHint();
})
.then(hint => {
assert.equal(hint, 'new-hint');
});
});
});
testLib.addTest('Save existing item to new vault', assert => {
var vault: agile_keychain.Vault;
var item: item_store.Item;
return createTestVault()
.then(vault_ => {
vault = vault_;
item = new item_store.Item();
item.title = 'Existing Item';
item.locations.push('somesite.com');
item.setContent(item_store.ContentUtil.empty());
return item.saveTo(vault);
})
.then(() => {
assert.equal(item.uuid.length, 32);
return vault.loadItem(item.uuid);
})
.then(loadedItem => {
assert.equal(item.title, loadedItem.item.title);
});
});
testLib.addTest('Item content account and password accessors', assert => {
let content = item_store.ContentUtil.empty();
content.formFields.push(
{
id: '',
name: 'password',
type: item_store.FormFieldType.Password,
designation: 'password',
value: 'the-item-password',
},
{
id: '',
name: 'email',
type: item_store.FormFieldType.Text,
designation: 'username',
value: 'jim.smith@gmail.com',
}
);
assert.equal(
item_store.ContentUtil.account(content),
'jim.smith@gmail.com'
);
assert.equal(item_store.ContentUtil.password(content), 'the-item-password');
});
testLib.addTest('Item field value formatting', assert => {
var dateField = agile_keychain.fromAgileKeychainField({
k: 'date',
n: 'dob',
t: 'Date of Birth',
v: 567278822,
});
assert.ok(
item_store.fieldValueString(dateField).match(/Dec 23 1987/) != null
);
var monthYearField = agile_keychain.fromAgileKeychainField({
k: 'monthYear',
n: 'expdate',
t: 'Expiry Date',
v: 201405,
});
assert.equal(item_store.fieldValueString(monthYearField), '05/14');
});
testLib.addTest('Default item properties', assert => {
var item = new item_store.Item();
assert.deepEqual(item.locations, []);
assert.strictEqual(item.trashed, false);
assert.equal(item.uuid.length, 32);
// check that new items get different IDs
var item2 = new item_store.Item();
assert.notEqual(item.uuid, item2.uuid);
});
testLib.addTest('createVault() fails if directory exists', assert => {
var fs = new nodefs.FileVFS(testLib.tempDir());
var pass = 'pass-1';
var hint = 'test-new-vault-hint';
var keyIterations = 100;
var path = '/new-vault-twice.agilekeychain';
var vault: agile_keychain.Vault;
return vfs_util
.rmrf(fs, path)
.then(() => {
return agile_keychain.Vault.createVault(
fs,
path,
pass,
hint,
keyIterations
);
})
.then(vault_ => {
vault = vault_;
var newPass = 'pass-2';
return asyncutil.result(
agile_keychain.Vault.createVault(
fs,
path,
newPass,
hint,
keyIterations
)
);
})
.then(result => {
assert.ok(result.error instanceof vfs.VfsError);
// check that the original vault has not been modified
return vault.unlock(pass);
});
});
function createTestLoginItem(id: number) {
return item_builder.createItem({
title: `Login ${id}`,
username: `user${id}`,
password: `pass${id}`,
url: `https://foobar.com/users/${id}`,
});
}
interface TestVault {
vault: agile_keychain.Vault;
items: item_store.Item[];
}
function createTestVaultWithNItems(n: number): Promise<TestVault> {
let vault: agile_keychain.Vault;
let items: item_store.Item[] = [];
return createEmptyVault()
.then(_vault => {
vault = _vault;
let saved: Promise<void>[] = [];
for (let i = 0; i < n; i++) {
var item = createTestLoginItem(i);
items.push(item);
saved.push(item.saveTo(vault));
}
return Promise.all(saved);
})
.then(() => ({
vault: vault,
items: items,
}));
}
testLib.addTest('listItemStates() matches listItems() output', assert => {
let vault: agile_keychain.Vault;
return createTestVaultWithNItems(3)
.then(result => {
vault = result.vault;
return asyncutil.all2([vault.listItemStates(), vault.listItems()]);
})
.then((items: [item_store.ItemState[], item_store.Item[]]) => {
assert.equal(items[0].length, items[1].length);
items[0].sort((a, b) => a.uuid.localeCompare(b.uuid));
items[1].sort((a, b) => a.uuid.localeCompare(b.uuid));
for (let i = 0; i < items[0].length; i++) {
assert.deepEqual(items[0][i].uuid, items[1][i].uuid);
assert.deepEqual(items[0][i].revision, items[1][i].revision);
assert.deepEqual(
items[0][i].deleted,
items[1][i].isTombstone()
);
}
});
});
// if the contents.js files and .1password files get out of sync, the .1password
// file is the source of truth
testLib.addTest(
'listItemStates(), listItems() should not list item if .1password file is not present',
assert => {
let testVault: TestVault;
return createTestVaultWithNItems(3)
.then(testVault_ => {
testVault = testVault_;
return testVault.vault.fs.list(
testVault.vault.path + '/data/default'
);
})
.then(entries => {
let itemID = testVault.items[0].uuid;
let itemPath = testVault.vault.itemPath(itemID);
return testVault.vault.fs.rm(itemPath);
})
.then(() => {
return testVault.vault.listItemStates();
})
.then(items => {
assert.equal(items.length, 2);
return testVault.vault.listItems();
})
.then(items => {
assert.equal(items.length, 2);
});
}
);
testLib.addTest('Removing item succeeds if file is already removed', assert => {
let testVault: TestVault;
return createTestVaultWithNItems(1)
.then(testVault_ => {
testVault = testVault_;
let itemPath = testVault.vault.itemPath(testVault.items[0].uuid);
return testVault.vault.fs.rm(itemPath);
})
.then(() => {
return testVault.items[0].remove();
})
.then(() => {
assert.ok(testVault.items[0].isTombstone());
});
});
// items created by some older versions of 1Password have a 'keyID' field
// but no 'securityLevel' field.
// Verify that these items are successfully listed.
// issue #57
testLib.addTest('Should list items with no securityLevel field', assert => {
// create a test vault with an item
let testVault: TestVault;
let keys: key_agent.Key[];
let itemPath: string;
return createTestVaultWithNItems(1)
.then(testVault_ => {
testVault = testVault_;
itemPath = testVault.vault.itemPath(testVault.items[0].uuid);
return testVault.vault.listKeys();
})
.then(_keys => {
keys = _keys;
// read the item's JSON file and clear the `securityLevel` field
return testVault.vault.fs.read(itemPath);
})
.then(json => {
let itemJSON = <any>JSON.parse(json);
// ensure the item has a `keyID` field but no `securityLevel` field
itemJSON.keyID = keys[0].identifier;
itemJSON.securityLevel = undefined;
// save the updated item content, then try to load the item and verify
// that it succeeds
return testVault.vault.fs.write(itemPath, JSON.stringify(itemJSON));
})
.then(() => {
return testVault.vault.loadItem(testVault.items[0].uuid);
})
.then(itemAndContent => {
assert.ok(itemAndContent.content);
});
}); | the_stack |
import fs from 'fs';
import path from 'path';
import fetch, { Headers, Request, Response } from 'node-fetch';
import { S3, GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import {
BlobServiceClient,
StorageSharedKeyCredential,
ContainerSASPermissions,
SASProtocol,
generateBlobSASQueryParameters,
} from '@azure/storage-blob';
import {
DownloadTableCSVData,
} from '@cubejs-backend/query-orchestrator';
import {
JDBCDriver,
JDBCDriverConfiguration,
} from '@cubejs-backend/jdbc-driver';
import { getEnv, pausePromise, CancelablePromise } from '@cubejs-backend/shared';
import { v1, v5 } from 'uuid';
import { DatabricksQuery } from './DatabricksQuery';
import { downloadJDBCDriver } from './installer';
export type DatabricksDriverConfiguration = JDBCDriverConfiguration &
{
readOnly?: boolean,
// common bucket config
bucketType?: string,
exportBucket?: string,
pollInterval?: number,
// AWS bucket config
awsKey?: string,
awsSecret?: string,
awsRegion?: string,
// Azure export bucket
azureKey?: string,
};
async function fileExistsOr(
fsPath: string,
fn: () => Promise<string>,
): Promise<string> {
if (fs.existsSync(fsPath)) {
return fsPath;
}
return fn();
}
type ShowTableRow = {
database: string,
tableName: string,
isTemporary: boolean,
};
type ShowDatabasesRow = {
databaseName: string,
};
const DatabricksToGenericType: Record<string, string> = {
'decimal(10,0)': 'bigint',
};
const jdbcDriverResolver: Promise<string> | null = null;
async function resolveJDBCDriver(): Promise<string> {
if (jdbcDriverResolver) {
return jdbcDriverResolver;
}
return fileExistsOr(
path.join(process.cwd(), 'SparkJDBC42.jar'),
async () => fileExistsOr(
path.join(__dirname, '..', '..', 'download', 'SparkJDBC42.jar'),
async () => {
const pathOrNull = await downloadJDBCDriver(false);
if (pathOrNull) {
return pathOrNull;
}
throw new Error(
'Please download and place SparkJDBC42.jar inside your ' +
'project directory'
);
}
)
);
}
/**
* Databricks driver class.
*/
export class DatabricksDriver extends JDBCDriver {
protected readonly config: DatabricksDriverConfiguration;
public static dialectClass() {
return DatabricksQuery;
}
public constructor(
conf: Partial<DatabricksDriverConfiguration>,
) {
const config: DatabricksDriverConfiguration = {
...conf,
drivername: 'com.simba.spark.jdbc.Driver',
customClassPath: undefined,
properties: {},
dbType: 'databricks',
database: getEnv('dbName', { required: false }),
url: getEnv('databrickUrl'),
// common export bucket config
bucketType:
conf?.bucketType ||
getEnv('dbExportBucketType', { supported: ['s3', 'azure'] }),
exportBucket: conf?.exportBucket || getEnv('dbExportBucket'),
pollInterval: (
conf?.pollInterval || getEnv('dbPollMaxInterval')
) * 1000,
// AWS export bucket config
awsKey: conf?.awsKey || getEnv('dbExportBucketAwsKey'),
awsSecret: conf?.awsSecret || getEnv('dbExportBucketAwsSecret'),
awsRegion: conf?.awsRegion || getEnv('dbExportBucketAwsRegion'),
// Azure export bucket
azureKey: conf?.azureKey || getEnv('dbExportBucketAzureKey'),
};
super(config);
this.config = config;
}
public readOnly() {
return !!this.config.readOnly;
}
protected async getCustomClassPath() {
return resolveJDBCDriver();
}
public async createSchemaIfNotExists(schemaName: string) {
return this.query(`CREATE SCHEMA IF NOT EXISTS ${schemaName}`, []);
}
public quoteIdentifier(identifier: string): string {
return `\`${identifier}\``;
}
public async tableColumnTypes(table: string) {
const [schema, tableName] = table.split('.');
const result = [];
const response: any[] = await this.query(`DESCRIBE ${schema}.${tableName}`, []);
for (const column of response) {
// Databricks describe additional info by default after empty line.
if (column.col_name === '') {
break;
}
result.push({ name: column.col_name, type: this.toGenericType(column.data_type) });
}
return result;
}
public async getTablesQuery(schemaName: string) {
const response = await this.query(`SHOW TABLES IN ${this.quoteIdentifier(schemaName)}`, []);
return response.map((row: any) => ({
table_name: row.tableName,
}));
}
protected async getTables(): Promise<ShowTableRow[]> {
if (this.config.database) {
return <any> this.query(`SHOW TABLES IN ${this.quoteIdentifier(this.config.database)}`, []);
}
const databases: ShowDatabasesRow[] = await this.query('SHOW DATABASES', []);
const allTables: (ShowTableRow[])[] = await Promise.all(
databases.map(async ({ databaseName }) => this.query(
`SHOW TABLES IN ${this.quoteIdentifier(databaseName)}`,
[]
))
);
return allTables.flat();
}
public toGenericType(columnType: string): string {
return DatabricksToGenericType[columnType.toLowerCase()] || super.toGenericType(columnType);
}
public async tablesSchema() {
const tables = await this.getTables();
const metadata: Record<string, Record<string, object>> = {};
await Promise.all(tables.map(async ({ database, tableName }) => {
if (!(database in metadata)) {
metadata[database] = {};
}
const columns = await this.tableColumnTypes(`${database}.${tableName}`);
metadata[database][tableName] = columns;
}));
return metadata;
}
/**
* Determines whether export bucket feature is configured or no.
* @returns {boolean}
*/
public async isUnloadSupported() {
return this.config.exportBucket !== undefined;
}
/**
* Returns databricks API base URL.
*/
private getApiUrl(): string {
let res: string;
try {
// eslint-disable-next-line prefer-destructuring
res = this.config.url
.split(';')
.filter(node => /^jdbc/i.test(node))[0]
.split('/')[2]
.split(':')[0];
} catch (e) {
res = '';
}
if (!res.length) {
throw new Error(
`Error parsing API URL from the CUBEJS_DB_DATABRICKS_URL = ${
this.config.url
}`
);
}
return res;
}
/**
* Returns databricks API token.
*/
private getApiToken(): string {
let res: string;
try {
// eslint-disable-next-line prefer-destructuring
res = this.config.url
.split(';')
.filter(node => /^PWD/i.test(node))[0]
.split('=')[1];
} catch (e) {
res = '';
}
if (!res.length) {
throw new Error(
'Error parsing API token from the CUBEJS_DB_DATABRICKS_URL' +
` = ${this.config.url}`
);
}
return res;
}
/**
* Sleeper method.
*/
private wait(ms: number): CancelablePromise<void> {
return pausePromise(ms);
}
/**
* Assert http response.
*/
private async assertResponse(response: Response): Promise<void> {
if (!response.ok) {
const text = await response.text();
throw new Error(`Databricks API call error: ${
response.status
} - ${
response.statusText
} - ${
text
}`);
}
}
/**
* Fetch API wrapper.
*/
private async fetch(req: Request, count?: number, ms?: number): Promise<Response> {
count = count || 0;
ms = ms || 0;
return new Promise((resolve, reject) => {
this
.wait(ms as number)
.then(() => {
fetch(req)
.then((res) => {
this
.assertResponse(res)
.then(() => { resolve(res); })
.catch((err) => {
if (res.status === 429 && (count as number) < 5) {
this
.fetch(req, (count as number)++, (ms as number) + 1000)
.then((_res) => { resolve(_res); })
.catch((_err) => { reject(_err); });
} else {
reject(err);
}
});
});
});
});
}
/**
* Returns IDs of databricks runned clusters.
*/
private async getClustersIds(): Promise<string[]> {
const url = `https://${
this.getApiUrl()
}/api/2.0/clusters/list`;
const request = new Request(url, {
headers: new Headers({
Accept: '*/*',
Authorization: `Bearer ${this.getApiToken()}`,
}),
});
const response = await this.fetch(request);
const body: {
clusters: {
// eslint-disable-next-line camelcase
cluster_id: string,
state: string,
}[],
} = await response.json();
return body.clusters
.filter(item => item.state === 'RUNNING')
.map(item => item.cluster_id);
}
/**
* Import predefined nodebook to the databricks under specified path.
*/
private async importNotebook(p: string, content: string): Promise<void> {
const url = `https://${
this.getApiUrl()
}/api/2.0/workspace/import`;
const request = new Request(url, {
method: 'POST',
headers: new Headers({
Accept: '*/*',
Authorization: `Bearer ${this.getApiToken()}`,
}),
body: JSON.stringify({
format: 'SOURCE',
language: 'SCALA',
overwrite: true,
content,
path: p,
}),
});
await this.fetch(request);
}
/**
* Create job and returns job id.
*/
private async createJob(cluster: string, p: string): Promise<number> {
const url = `https://${
this.getApiUrl()
}/api/2.0/jobs/create`;
const request = new Request(url, {
method: 'POST',
headers: new Headers({
Accept: '*/*',
Authorization: `Bearer ${this.getApiToken()}`,
}),
body: JSON.stringify({
existing_cluster_id: cluster,
notebook_task: {
notebook_path: p,
},
}),
});
const response = await this.fetch(request);
const body: {
// eslint-disable-next-line camelcase
job_id: number,
} = await response.json();
return body.job_id;
}
/**
* Run job and returns run id.
*/
private async runJob(job: number): Promise<number> {
const url = `https://${
this.getApiUrl()
}/api/2.0/jobs/run-now`;
const request = new Request(url, {
method: 'POST',
headers: new Headers({
Accept: '*/*',
Authorization: `Bearer ${this.getApiToken()}`,
}),
body: JSON.stringify({
job_id: job,
}),
});
const response = await this.fetch(request);
const body: {
// eslint-disable-next-line camelcase
run_id: number,
} = await response.json();
return body.run_id;
}
/**
* Pooling databricks until run in progress and resolve when it's done.
*/
private async waitResult(run: number, ms?: number): Promise<any> {
ms = ms || 1000;
ms = ms <= 10000 ? ms + 1000 : ms;
return new Promise((resolve, reject) => {
const url = `https://${
this.getApiUrl()
}/api/2.0/jobs/runs/get?run_id=${run}`;
const request = new Request(url, {
headers: new Headers({
Accept: '*/*',
Authorization: `Bearer ${this.getApiToken()}`,
}),
});
this
.wait(ms as number)
.then(() => {
this
.fetch(request)
.then((response) => {
response
.json()
.then((body: {
state: {
// eslint-disable-next-line camelcase
life_cycle_state: string,
// eslint-disable-next-line camelcase
result_state: string,
},
}) => {
const { state } = body;
if (
state.life_cycle_state === 'TERMINATED' &&
state.result_state === 'SUCCESS'
) {
resolve(state.result_state);
} else if (
state.life_cycle_state === 'INTERNAL_ERROR' ||
state.result_state === 'FAILED' ||
state.result_state === 'TIMEDOUT' ||
state.result_state === 'CANCELED'
) {
reject(state.result_state);
} else {
this
.waitResult(run, ms)
.then((res) => { resolve(res); })
.catch((err) => { reject(err); });
}
});
});
});
});
}
/**
* Delete job.
*/
private async deleteJob(job: number): Promise<any> {
const url = `https://${
this.getApiUrl()
}/api/2.0/jobs/delete`;
const request = new Request(url, {
method: 'POST',
headers: new Headers({
Accept: '*/*',
Authorization: `Bearer ${this.getApiToken()}`,
}),
body: JSON.stringify({
job_id: job,
}),
});
await this.fetch(request);
}
/**
* Remove nodebook.
*/
private async deleteNotebook(p: string): Promise<any> {
const url = `https://${
this.getApiUrl()
}/api/2.0/workspace/delete`;
const request = new Request(url, {
method: 'POST',
headers: new Headers({
Accept: '*/*',
Authorization: `Bearer ${this.getApiToken()}`,
}),
body: JSON.stringify({
path: p,
recursive: true,
}),
});
await this.fetch(request);
}
/**
* Returns signed temporary URLs for AWS S3 objects.
*/
private async getSignedS3Urls(
pathname: string,
): Promise<string[]> {
const client = new S3({
credentials: {
accessKeyId: this.config.awsKey as string,
secretAccessKey: this.config.awsSecret as string,
},
region: this.config.awsRegion,
});
const url = new URL(pathname);
const list = await client.listObjectsV2({
Bucket: url.host,
Prefix: url.pathname.slice(1),
});
if (list.Contents === undefined) {
throw new Error(`No content in specified path: ${pathname}`);
}
const csvFile = await Promise.all(
list.Contents
.filter(file => file.Key && /.csv$/i.test(file.Key))
.map(async (file) => {
const command = new GetObjectCommand({
Bucket: url.host,
Key: file.Key,
});
return getSignedUrl(client, command, { expiresIn: 3600 });
})
);
return csvFile;
}
/**
* Unload to AWS S3 bucket.
*/
private async unloadS3Command(
table: string,
columns: string,
pathname: string,
): Promise<string[]> {
let result: string[] = [];
let notebook = true;
const filename = `/${v5(pathname, v1()).toString()}.scala`;
const content = Buffer.from(
`sc.hadoopConfiguration.set(
"fs.s3n.awsAccessKeyId", "${this.config.awsKey}"
)
sc.hadoopConfiguration.set(
"fs.s3n.awsSecretAccessKey","${this.config.awsSecret}"
)
sqlContext
.sql("SELECT ${columns} FROM ${table}")
.write
.format("com.databricks.spark.csv")
.option("header", "false")
.save("${pathname}")`,
'utf-8',
).toString('base64');
const cluster = (await this.getClustersIds())[0];
try {
await this.importNotebook(filename, content);
} catch (e) {
notebook = false;
}
if (notebook) {
try {
const job = await this.createJob(cluster, filename);
const run = await this.runJob(job);
await this.waitResult(run);
await this.deleteJob(job);
result = await this.getSignedS3Urls(pathname);
} finally {
await this.deleteNotebook(filename);
}
}
return result;
}
/**
* Returns signed temporary URLs for Azure container objects.
*/
private async getSignedWasbsUrls(
pathname: string,
): Promise<string[]> {
const csvFile: string[] = [];
const [container, account] =
pathname.split('wasbs://')[1].split('.blob')[0].split('@');
const foldername =
pathname.split(`${this.config.exportBucket}/`)[1];
const expr = new RegExp(`${foldername}\\/.*\\.csv$`, 'i');
const credential = new StorageSharedKeyCredential(
account,
this.config.azureKey as string,
);
const blobClient = new BlobServiceClient(
`https://${account}.blob.core.windows.net`,
credential,
);
const containerClient = blobClient.getContainerClient(container);
const blobsList = containerClient.listBlobsFlat();
for await (const blob of blobsList) {
if (blob.name && expr.test(blob.name)) {
const sas = generateBlobSASQueryParameters(
{
containerName: container,
blobName: blob.name,
permissions: ContainerSASPermissions.parse('r'),
startsOn: new Date(new Date().valueOf()),
expiresOn:
new Date(new Date().valueOf() + 1000 * 60 * 60),
protocol: SASProtocol.Https,
version: '2020-08-04',
},
credential,
).toString();
csvFile.push(`https://${
account
}.blob.core.windows.net/${
container
}/${blob.name}?${sas}`);
}
}
return csvFile;
}
/**
* Unload to Azure Blob Container bucket.
*/
private async unloadWasbsCommand(
table: string,
columns: string,
pathname: string,
): Promise<string[]> {
let result: string[] = [];
let notebook = true;
const filename = `/${v5(pathname, v1()).toString()}.scala`;
const storage = pathname.split('@')[1].split('.')[0];
const content = Buffer.from(
`spark.conf.set(
"fs.azure.account.key.${storage}.blob.core.windows.net",
"${this.config.azureKey}"
)
sqlContext
.sql("SELECT ${columns} FROM ${table}")
.write
.format("com.databricks.spark.csv")
.option("header", "false")
.save("${pathname}")`,
'utf-8',
).toString('base64');
// TODO: if there is no cluster should we create new one?
const cluster = (await this.getClustersIds())[0];
try {
await this.importNotebook(filename, content);
} catch (e) {
notebook = false;
}
if (notebook) {
try {
const job = await this.createJob(cluster, filename);
const run = await this.runJob(job);
await this.waitResult(run);
await this.deleteJob(job);
result = await this.getSignedWasbsUrls(pathname);
} finally {
await this.deleteNotebook(filename);
}
}
return result;
}
/**
* Unload table to bucket.
*/
private async unloadCommand(
table: string,
columns: string,
pathname: string,
): Promise<string[]> {
let res;
switch (this.config.bucketType) {
case 's3':
res = await this.unloadS3Command(table, columns, pathname);
break;
case 'azure':
res = await this.unloadWasbsCommand(table, columns, pathname);
break;
default:
throw new Error(`Unsupported export bucket type: ${
this.config.bucketType
}`);
}
return res;
}
/**
* Saves pre-aggs table to the bucket and returns links to download
* results.
*/
public async unload(
tableName: string,
): Promise<DownloadTableCSVData> {
const types = await this.tableColumnTypes(tableName);
const columns = types.map(t => t.name).join(', ');
const pathname = `${this.config.exportBucket}/${tableName}.csv`;
const csvFile = await this.unloadCommand(
tableName,
columns,
pathname,
);
return {
csvFile,
types,
csvNoHeader: true,
};
}
} | the_stack |
import {isLevel} from '../Core/Level';
import {SClass} from '../Core/Decorator';
import EventManager from '../Event/EventManager';
import Component from '../Core/Component';
import {Vector3, Quaternion} from '../Core/Math';
import SceneActor from '../Renderer/ISceneActor';
import ColliderComponent from '../Physic/ColliderComponent';
import {ICollisionEvent, IColliderCollisionEvent, IPickResult, IColliderCommonOptions, ERigidBodyType} from '../types/Physic';
import UnmetRequireException from '../Exception/UnmetRequireException';
import MemberConflictException from '../Exception/MemberConflictException';
import SObject from '../Core/SObject';
/**
* `RigidBodyComponent`的初始化参数类型。
*/
export interface IRigidBodyComponentState {
/**
* 刚体重力。
*/
mass: number;
/**
* 刚体摩擦力。
*/
friction?: number;
/**
* 刚体弹性系数。
*/
restitution?: number;
/**
* 刚体是否处于不可控状态,即父级Actor的transform变换不会影响到物理世界刚体的transform。
* 一般用于纯静态物体,进行性能优化。
*/
unControl?: boolean;
/**
* 物理世界的刚体是否是静态的,这会导致物理世界刚体的transform不会影响到父级Actor的transform。
* 一般用于纯物理静态物体,进行性能优化。
*/
physicStatic?: boolean;
/**
* 初始是否处于睡眠状态。一般用于完全不想让此刚体参与除了拾取外任何碰撞处理的场合。
*
* @default sleeping false
*/
sleeping?: boolean;
/**
* filterMask,一个32bits的整数,用于给分组后的刚体设置碰撞对象范围。
*/
filterMask?: number;
/**
* 一个32bits的整数,用于给刚体分组。
*/
filterGroup?: number;
nativeOptions?: any;
}
/**
* `RigidBodyComponent`的事件定义。
*/
export interface IColliderDefaultEvents {
/**
* 碰撞事件,当两个刚体发生碰撞时触发。
*/
Collision: ICollisionEvent;
/**
* 碰撞事件,当一个刚体进入另一个刚体时触发。
* **只有在开启了高级碰撞事件后才会触发。**
*/
BodyEnter: ICollisionEvent;
/**
* 碰撞事件,当一个刚体离开另一个刚体时触发。
* **只有在开启了高级碰撞事件后才会触发。**
*/
BodyLeave: ICollisionEvent;
/**
* 碰撞事件,当一个碰撞体进入另一个碰撞体时触发。
* **只有在开启了高级碰撞事件后才会触发。**
*/
ColliderEnter: IColliderCollisionEvent;
/**
* 碰撞事件,当一个碰撞体离开另一个碰撞体时触发。
* **只有在开启了高级碰撞事件后才会触发。**
*/
ColliderLeave: IColliderCollisionEvent;
/**
* 拾取事件。需要配合[PhysicPicker](../../classes/physicpicker)一起使用。
*/
Pick: IPickResult;
/**
* 在每一次同步父级Actor的transform到物理世界的刚体后触发。
*/
BeforeStep: RigidBodyComponent;
/**
* 在每一次同步物理世界刚体的transform到父级Actor前触发。
*/
AfterStep: RigidBodyComponent;
}
/**
* 判断一个实例是否为`RigidBodyComponent`。
*/
export function isRigidBodyComponent(value: SObject): value is RigidBodyComponent {
return (value as RigidBodyComponent).isRigidBodyComponent;
}
/**
* @hidden
*/
const vec3Unit = new Vector3(1, 1, 1);
/**
* @hidden
*/
const vec3Zero = new Vector3(0, 0, 0);
/**
* 刚体组件类,为Actor添加物理引擎和碰撞检测、拾取的基本功能。
* **当挂载到Actor后,你可以直接通过`actor.rigidBody`来访问它。**
*
* @noInheritDoc
*/
@SClass({className: 'RigidBodyComponent', classType: 'RigidBody'})
export default class RigidBodyComponent extends Component<IRigidBodyComponentState> {
public isRigidBodyComponent = true;
/**
* 不要自己使用。
*
* @hidden
*/
public needUpdateCollider: boolean = false;
protected _event: EventManager<IColliderDefaultEvents>;
protected _rigidBody: {
component: RigidBodyComponent;
[key: string]: any;
};
protected _owner: SceneActor;
protected _unControl: boolean;
protected _physicStatic: boolean;
protected _disabled: boolean = false;
protected _sleeping: boolean = false;
private _valid: boolean = false;
private _tmpQuat: Quaternion = new Quaternion();
private _tmpQuat2: Quaternion = new Quaternion();
private _tmpScale: Vector3 = new Vector3(1, 1, 1);
private _tmpScale2: Vector3 = new Vector3(1, 1, 1);
private _tmpScale3: Vector3 = new Vector3(1, 1, 1);
/**
* 获取物理世界的刚体,不需要自己使用。
*
* @hidden
*/
get rigidBody() {
return this._rigidBody;
}
/**
* 刚体当前是否有效,不需要自己使用。
*
* @hidden
*/
get valid(): boolean {
return this._valid;
}
/**
* RigidBodyComponent的事件管理器。
*/
get event() {
return this._event;
}
/**
* 设置重力。
*/
set mass(value: number) {
this.getPhysicWorld().setBodyMass(this, value);
}
/**
* 获取重力。
*/
get mass() {
return this.getPhysicWorld().getBodyMass(this);
}
/**
* 设置filterGroup,一个32bits的整数,用于给刚体分组。
*/
set filterGroup(value: number) {
this.getPhysicWorld().setFilterGroup(this, value);
}
/**
* 获取filterGroup。
*/
get filterGroup() {
return this.getPhysicWorld().getFilterGroup(this);
}
/**
* 设置filterMask,一个32bits的整数,用于给分组后的刚体设置碰撞对象范围。
*/
set filterMask(value: number) {
this.getPhysicWorld().setFilterMask(this, value);
}
/**
* 获取filterMask。
*/
get filterMask() {
return this.getPhysicWorld().getFilterMask(this);
}
/**
* 设置刚体摩擦力。
*/
set friction(value: number) {
this.getPhysicWorld().setBodyFriction(this, value);
}
/**
* 获取刚体摩擦力。
*/
get friction() {
return this.getPhysicWorld().getBodyFriction(this);
}
/**
* 设置刚体弹性系数。
*/
set restitution(value: number) {
this.getPhysicWorld().setBodyRestitution(this, value);
}
/**
* 获取刚体弹性系数。
*/
get restitution() {
return this.getPhysicWorld().getBodyRestitution(this);
}
/**
* 设置刚体是否处于不可控状态,详见[IRigidBodyComponentState](../interfaces/irigidbodycomponentstate)。
*/
set unControl(value: boolean) {
this._unControl = value;
}
/**
* 获取刚体是否处于不可控状态,详见[IRigidBodyComponentState](../interfaces/irigidbodycomponentstate)。
*/
get unControl() {
return this._unControl;
}
/**
* 设置刚体是否处于物理静止状态,详见[IRigidBodyComponentState](../interfaces/irigidbodycomponentstate)。
*/
set physicStatic(value: boolean) {
this._physicStatic = value;
this.getPhysicWorld().setBodyType(this, value ? ERigidBodyType.Static : ERigidBodyType.Dynamic);
}
/**
* 获取刚体是否处于物理静止状态,详见[IRigidBodyComponentState](../interfaces/irigidbodycomponentstate)。
*/
get physicStatic() {
return this._physicStatic;
}
/**
* 刚体组件目前是否停止运作。
*/
get disabled() {
return this._disabled;
}
public verifyAdding() {
if (!this.getPhysicWorld()) {
throw new UnmetRequireException(this, 'Physic world is required for adding RigidBodyComponent !');
}
if (this._owner.findComponentByClass(RigidBodyComponent)) {
throw new MemberConflictException(this._owner, 'RigidBodyComponent', this.name, this);
}
}
public onInit(initState: IRigidBodyComponentState) {
this._unControl = initState.unControl || false;
this._physicStatic = initState.physicStatic || false;
if (typeof initState.filterMask !== 'undefined') {
this.filterMask = initState.filterMask;
}
if (typeof initState.filterGroup !== 'undefined') {
this.filterGroup = initState.filterGroup;
}
this._event.register('Pick');
this._event.register('Collision');
this._event.register('BodyEnter');
this._event.register('BodyLeave');
this._event.register('ColliderEnter');
this._event.register('ColliderLeave');
this._event.register('BeforeStep');
this._event.register('AfterStep');
// fixme: hack for performance
(this._owner as any)._rigidBody = this;
}
/**
* 添加到世界,继承请先`super.onAdd()`。
*/
public onAdd(initState: IRigidBodyComponentState) {
this._rigidBody = this.getPhysicWorld().createRigidBody(this, initState);
this.getPhysicWorld().initEvents(this);
this._valid = true;
if (initState.sleeping === true) {
this.sleep();
}
}
/**
* 从世界中暂时移除,继承请先`super.onUnLink()`。
*/
public onUnLink() {
this.disable();
}
/**
* 重连世界,继承请先`super.onReLink()`。
*/
public onReLink() {
this.enable();
}
/**
* 销毁,继承请先`super.onDestroy()`。
*/
public onDestroy() {
this._valid = false;
const physicWorld = this.getPhysicWorld();
setTimeout(() => physicWorld.removeRigidBody(this), 0);
if (this._owner.rigidBody === this) {
(this._owner as any)._rigidBody = null;
}
}
/**
* 暂时使得刚体失去效应,可以用`enable`恢复。
*/
public disable() {
this.getPhysicWorld().disableRigidBody(this);
this._disabled = true;
}
/**
* 使得一个暂时失去效应的刚体恢复。
*/
public enable() {
this.getPhysicWorld().enableRigidBody(this);
this._disabled = false;
}
/**
* 获取质心。
*/
public getMassCenter(): Vector3 {
return this._owner.transform.position;
}
/**
* 设置刚体的父级Actor的`transform`。
*/
public setRootTransform() {
this.getPhysicWorld().setRootTransform(this);
return this;
}
/**
* 设置刚体的`transform`。
*/
public setRigidBodyTransform(newPosition: Vector3, newRotation: Quaternion) {
this.getPhysicWorld().setRigidBodyTransform(this, newPosition, newRotation);
return this;
}
/**
* 设置线速度。
*/
public setLinearVelocity(velocity: Vector3) {
this.getPhysicWorld().setLinearVelocity(this, velocity);
return this;
}
/**
* 设置角速度。
*/
public setAngularVelocity(velocity: Vector3) {
this.getPhysicWorld().setAngularVelocity(this, velocity);
return this;
}
/**
* 获取线速度。
*/
public getLinearVelocity() {
return this.getPhysicWorld().getLinearVelocity(this);
}
/**
* 获取角速度。
*/
public getAngularVelocity() {
return this.getPhysicWorld().getAngularVelocity(this);
}
/**
* 使刚体进入睡眠状态,不会触发任何碰撞事件,但可以正确响应拾取操作。
*/
public sleep() {
this.getPhysicWorld().sleepBody(this);
this._sleeping = true;
return this;
}
/**
* 唤醒刚体。
*/
public wakeUp() {
this.getPhysicWorld().wakeUpBody(this);
this._sleeping = false;
return this;
}
/**
* 强制同步物理刚体的transform到组件父级Actor。
*/
public forceSync() {
this.handleBeforeStep(null, true);
return this;
}
protected getParentsRotationAndScale() {
let parent = this._owner.parent;
this._tmpQuat.set(0, 0, 0, 1);
this._tmpScale.set(1, 1, 1);
while (parent && !isLevel(parent)) {
const actor = parent.getOwner<SceneActor>();
this._tmpQuat2.copy(actor.transform.quaternion);
this._tmpQuat.multiply(this._tmpQuat2);
this._tmpScale2.copy(actor.transform.scale);
this._tmpScale.multiply(this._tmpScale2);
parent = actor.parent;
}
}
/**
* **不要自己调用!!**
*
* @hidden
*/
public handleCollision = ({body, contact}) => {
let other;
let self;
if (body.id === contact.bi.id) {
self = contact.bj;
other = contact.bi;
} else {
self = contact.bi;
other = contact.bj;
}
if (!this._valid || !other.component.valid) {
return;
}
this.event.trigger('Collision', {
selfBody: self.component,
otherBody: other.component,
selfActor: self.component.getOwner(),
otherActor: other.component.getOwner()
});
}
/**
* **不要自己调用!!**
*
* @hidden
*/
public handleBodyEnter = (
selfBody: RigidBodyComponent,
otherBody: RigidBodyComponent
) => {
if (!this._valid || !otherBody.valid) {
return;
}
this.event.trigger('BodyEnter', {selfBody, otherBody, selfActor: selfBody.getOwner(), otherActor: otherBody.getOwner()});
}
/**
* **不要自己调用!!**
*
* @hidden
*/
public handleBodyLeave = (
selfBody: RigidBodyComponent,
otherBody: RigidBodyComponent
) => {
if (!this._valid || !otherBody.valid) {
return;
}
this.event.trigger('BodyLeave', {selfBody, otherBody, selfActor: selfBody.getOwner(), otherActor: otherBody.getOwner()});
}
/**
* **不要自己调用!!**
*
* @hidden
*/
public handleColliderEnter = (
selfBody: RigidBodyComponent,
otherBody: RigidBodyComponent,
selfCollider: ColliderComponent,
otherCollider: ColliderComponent
) => {
if (!this._valid || !otherBody.valid) {
return;
}
this.event.trigger('ColliderEnter', {
selfBody, otherBody, selfCollider, otherCollider,
selfActor: selfBody.getOwner(), otherActor: otherBody.getOwner()
});
}
/**
* **不要自己调用!!**
*
* @hidden
*/
public handleColliderLeave = (
selfBody: RigidBodyComponent,
otherBody: RigidBodyComponent,
selfCollider: ColliderComponent,
otherCollider: ColliderComponent
) => {
if (!this._valid || !otherBody.valid) {
return;
}
this.event.trigger('ColliderLeave', {
selfBody, otherBody, selfCollider, otherCollider,
selfActor: selfBody.getOwner(), otherActor: otherBody.getOwner()
});
}
/**
* **不要自己调用!!**
*
* @hidden
*/
public getCurrentTransform(): [Vector3, Quaternion, Vector3] {
const {transform} = this._owner;
transform.updateMatrixWorld(true);
if (this._owner.parent && !isLevel(this._owner.parent)) {
this.getParentsRotationAndScale();
this._tmpQuat.multiply(transform.quaternion);
this._tmpScale.multiply(transform.scale);
} else {
this._tmpQuat.copy(transform.quaternion);
this._tmpScale.copy(transform.scale);
}
return [transform.absolutePosition, this._tmpQuat, this._tmpScale];
}
/**
* **不要自己调用!!**
*
* @hidden
*/
public handleBeforeStep = (_, forceSync: boolean = false) => {
if (!this._valid) {
return;
}
if (this._physicStatic && !this._sleeping && this.mass !== 0) {
this.setAngularVelocity(vec3Zero);
this.setLinearVelocity(vec3Zero);
}
this.syncTransformToRigidBody(forceSync);
this.event.trigger('BeforeStep', this);
}
private syncTransformToRigidBody(forceSync: boolean) {
// todo: bug: change this.box.transform.position & change this.box.transform.scale.x = .3;
const {transform} = this._owner;
if (this.needUpdateCollider) {
this.getPhysicWorld().updateBounding(this);
this.needUpdateCollider = false;
}
if (!forceSync && this._unControl) {
return;
}
if (forceSync) {
transform.updateMatrixWorld(true);
}
this._tmpScale3.copy(this._tmpScale);
if (this._owner.parent && !isLevel(this._owner.parent)) {
this.getParentsRotationAndScale();
this._tmpQuat.multiply(transform.quaternion);
this._tmpScale.multiply(transform.scale);
} else {
this._tmpQuat.copy(transform.quaternion);
this._tmpScale.copy(transform.scale);
}
const updateScale = (forceSync && !this._tmpScale.equals(vec3Unit)) || !this._tmpScale.equals(this._tmpScale3);
this.getPhysicWorld().setRigidBodyTransform(
this,
transform.absolutePosition,
this._tmpQuat,
updateScale ? this._tmpScale : null
);
if (forceSync) {
this.getPhysicWorld().updateBounding(this);
}
}
/**
* **不要自己调用!!**
*
* @hidden
*/
public handleAfterStep = () => {
if (!this.valid) {
return;
}
if (this._physicStatic || this._sleeping) {
return;
}
const {transform} = this._owner;
this.event.trigger('AfterStep', this);
this.getPhysicWorld().setRootTransform(this);
// object has now its world rotation. needs to be converted to local.
if (this._owner.parent) {
this.getParentsRotationAndScale();
this._tmpQuat.conjugate();
transform.quaternion = this._tmpQuat.multiply(transform.quaternion);
}
// take the position set and make it the absolute position of this object.
transform.absolutePosition = transform.position;
}
/**
* **不要自己调用!!**
*
* @hidden
*/
public handlePick = (result: IPickResult) => {
this.event.trigger('Pick', result);
}
} | the_stack |
import { Type } from "..";
import { Assert, CommonError, MapUtils } from "../../../common";
import { isEqualFunctionSignature, isEqualType } from "./isEqualType";
import { isFieldSpecificationList, isFunctionSignature } from "./isType";
// Returns `${left} is compatible with ${right}. Eg.
// `Type.TextInstance is compatible with Type.AnyInstance` -> true
// `Type.AnyInstance is compatible with Type.TextInstance` -> false
// `Type.NullInstance is compatible with Type.AnyNonNull` -> false
// `Type.TextInstance is compatible with Type.AnyUnion([Type.TextInstance, Type.NumberInstance])` -> true
export function isCompatible(left: Type.TPowerQueryType, right: Type.TPowerQueryType): boolean | undefined {
if (
left.kind === Type.TypeKind.NotApplicable ||
left.kind === Type.TypeKind.Unknown ||
right.kind === Type.TypeKind.NotApplicable ||
right.kind === Type.TypeKind.Unknown
) {
return undefined;
} else if (
left.kind === Type.TypeKind.None ||
right.kind === Type.TypeKind.None ||
(left.isNullable && !right.isNullable)
) {
return false;
} else if (left.kind === Type.TypeKind.Null && right.isNullable) {
return true;
}
switch (right.kind) {
case Type.TypeKind.Action:
case Type.TypeKind.Binary:
case Type.TypeKind.Date:
case Type.TypeKind.DateTime:
case Type.TypeKind.DateTimeZone:
case Type.TypeKind.Duration:
case Type.TypeKind.Time:
return isEqualType(left, right);
case Type.TypeKind.Any:
return isCompatibleWithAny(left, right);
case Type.TypeKind.AnyNonNull:
return left.kind !== Type.TypeKind.Null && !left.isNullable;
case Type.TypeKind.Function:
return isCompatibleWithFunction(left, right);
case Type.TypeKind.List:
return isCompatibleWithList(left, right);
case Type.TypeKind.Logical:
return isCompatibleWithPrimitiveOrLiteral(left, right);
case Type.TypeKind.Number:
return isCompatibleWithPrimitiveOrLiteral(left, right);
case Type.TypeKind.Null:
return left.kind === Type.TypeKind.Null;
case Type.TypeKind.Record:
return isCompatibleWithRecord(left, right);
case Type.TypeKind.Table:
return isCompatibleWithTable(left, right);
case Type.TypeKind.Text:
return isCompatibleWithPrimitiveOrLiteral(left, right);
case Type.TypeKind.Type:
return isCompatibleWithType(left, right);
default:
throw Assert.isNever(right);
}
}
export function isCompatibleWithFunctionSignature(
left: Type.TPowerQueryType,
right: Type.TPowerQueryType & Type.FunctionSignature,
): boolean {
if (!isFunctionSignature(left)) {
return false;
}
return isEqualFunctionSignature(left, right);
}
export function isCompatibleWithFunctionParameter(
left: Type.TPowerQueryType | undefined,
right: Type.FunctionParameter,
): boolean {
if (left === undefined) {
return right.isOptional;
} else if (left.isNullable && !right.isNullable) {
return false;
} else {
return (
!right.maybeType ||
right.maybeType === Type.TypeKind.Any ||
left.kind === Type.TypeKind.Any ||
(left.kind === Type.TypeKind.Null && right.isNullable) ||
left.kind === right.maybeType
);
}
}
function isCompatibleWithAny(left: Type.TPowerQueryType, right: Type.TAny): boolean | undefined {
switch (right.maybeExtendedKind) {
case undefined:
return true;
case Type.ExtendedTypeKind.AnyUnion:
return isCompatibleWithAnyUnion(left, right);
default:
throw Assert.isNever(right);
}
}
function isCompatibleWithAnyUnion(left: Type.TPowerQueryType, right: Type.AnyUnion): boolean | undefined {
for (const subtype of right.unionedTypePairs) {
if (isCompatible(left, subtype)) {
return true;
}
}
return false;
}
function isCompatibleWithDefinedList(left: Type.TPowerQueryType, right: Type.DefinedList): boolean {
if (left.kind !== right.kind) {
return false;
}
switch (left.maybeExtendedKind) {
case undefined:
return false;
case Type.ExtendedTypeKind.DefinedList: {
return isCompatibleDefinedListOrDefinedListType(left, right);
}
default:
throw Assert.isNever(left);
}
}
function isCompatibleWithDefinedListType(left: Type.TPowerQueryType, right: Type.DefinedListType): boolean {
if (left.kind !== right.kind) {
return false;
}
switch (left.maybeExtendedKind) {
case Type.ExtendedTypeKind.DefinedListType:
return isCompatibleDefinedListOrDefinedListType(left, right);
case Type.ExtendedTypeKind.ListType:
return isDefinedListTypeCompatibleWithListType(right, left);
case undefined:
case Type.ExtendedTypeKind.FunctionType:
case Type.ExtendedTypeKind.PrimaryPrimitiveType:
case Type.ExtendedTypeKind.RecordType:
case Type.ExtendedTypeKind.TableTypePrimaryExpression:
case Type.ExtendedTypeKind.TableType:
return false;
default:
throw Assert.isNever(left);
}
}
function isCompatibleWithDefinedRecord(left: Type.TPowerQueryType, right: Type.DefinedRecord): boolean {
if (left.kind !== right.kind) {
return false;
}
switch (left.maybeExtendedKind) {
case undefined:
return false;
case Type.ExtendedTypeKind.DefinedRecord:
return isCompatibleWithFieldSpecificationList(left, right);
default:
throw Assert.isNever(left);
}
}
function isCompatibleWithDefinedTable(left: Type.TPowerQueryType, right: Type.DefinedTable): boolean {
if (left.kind !== right.kind) {
return false;
}
switch (left.maybeExtendedKind) {
case undefined:
return false;
case Type.ExtendedTypeKind.DefinedTable: {
return isCompatibleWithFieldSpecificationList(left, right);
}
default:
throw Assert.isNever(left);
}
}
// TODO: decide what a compatible FieldSpecificationList should look like
function isCompatibleWithFieldSpecificationList(
left: Type.TPowerQueryType,
right: Type.TPowerQueryType & Type.TFieldSpecificationList,
): boolean {
if (!isFieldSpecificationList(left)) {
return false;
}
return MapUtils.isSubsetMap(
left.fields,
right.fields,
(leftValue: Type.TPowerQueryType, rightValue: Type.TPowerQueryType) => {
const result: boolean | undefined = isCompatible(leftValue, rightValue);
return result !== undefined && result;
},
);
}
function isCompatibleWithFunction(left: Type.TPowerQueryType, right: Type.TFunction): boolean {
if (left.kind !== right.kind) {
return false;
}
switch (right.maybeExtendedKind) {
case undefined:
return true;
case Type.ExtendedTypeKind.DefinedFunction:
return isCompatibleWithFunctionSignature(left, right);
default:
throw Assert.isNever(right);
}
}
function isCompatibleWithList(left: Type.TPowerQueryType, right: Type.TList): boolean {
if (left.kind !== right.kind) {
return false;
}
switch (right.maybeExtendedKind) {
case undefined:
return left.maybeExtendedKind === undefined;
case Type.ExtendedTypeKind.DefinedList:
return isCompatibleWithDefinedList(left, right);
default:
throw Assert.isNever(right);
}
}
function isCompatibleWithListType(left: Type.TPowerQueryType, right: Type.ListType): boolean {
if (left.kind !== right.kind) {
return false;
}
switch (left.maybeExtendedKind) {
case Type.ExtendedTypeKind.DefinedListType:
return isDefinedListTypeCompatibleWithListType(left, right);
case Type.ExtendedTypeKind.ListType:
return isEqualType(left.itemType, right.itemType);
case undefined:
case Type.ExtendedTypeKind.FunctionType:
case Type.ExtendedTypeKind.PrimaryPrimitiveType:
case Type.ExtendedTypeKind.RecordType:
case Type.ExtendedTypeKind.TableTypePrimaryExpression:
case Type.ExtendedTypeKind.TableType:
return false;
default:
throw Assert.isNever(left);
}
}
function isCompatibleWithPrimaryPrimitiveType(left: Type.TPowerQueryType, right: Type.PrimaryPrimitiveType): boolean {
if (left.kind !== right.kind) {
return false;
}
switch (left.maybeExtendedKind) {
case Type.ExtendedTypeKind.PrimaryPrimitiveType:
return left.primitiveType === right.primitiveType;
case undefined:
case Type.ExtendedTypeKind.DefinedListType:
case Type.ExtendedTypeKind.ListType:
case Type.ExtendedTypeKind.FunctionType:
case Type.ExtendedTypeKind.RecordType:
case Type.ExtendedTypeKind.TableTypePrimaryExpression:
case Type.ExtendedTypeKind.TableType:
return false;
default:
throw Assert.isNever(left);
}
}
function isCompatibleWithRecord(left: Type.TPowerQueryType, right: Type.TRecord): boolean {
if (left.kind !== right.kind) {
return false;
}
switch (right.maybeExtendedKind) {
case undefined:
return true;
case Type.ExtendedTypeKind.DefinedRecord:
return isCompatibleWithDefinedRecord(left, right);
default:
throw Assert.isNever(right);
}
}
function isCompatibleWithRecordType(left: Type.TPowerQueryType, right: Type.RecordType): boolean {
if (left.kind !== right.kind) {
return false;
}
switch (left.maybeExtendedKind) {
case Type.ExtendedTypeKind.RecordType:
return isCompatibleWithFieldSpecificationList(left, right);
case undefined:
case Type.ExtendedTypeKind.DefinedListType:
case Type.ExtendedTypeKind.PrimaryPrimitiveType:
case Type.ExtendedTypeKind.ListType:
case Type.ExtendedTypeKind.FunctionType:
case Type.ExtendedTypeKind.TableTypePrimaryExpression:
case Type.ExtendedTypeKind.TableType:
return false;
default:
throw Assert.isNever(left);
}
}
function isCompatibleWithTable(left: Type.TPowerQueryType, right: Type.TTable): boolean {
if (left.kind !== right.kind) {
return false;
}
switch (right.maybeExtendedKind) {
case undefined:
return true;
case Type.ExtendedTypeKind.DefinedTable:
return isCompatibleWithDefinedTable(left, right);
default:
throw Assert.isNever(right);
}
}
function isCompatibleWithTableType(left: Type.TPowerQueryType, right: Type.TableType): boolean {
if (left.kind !== right.kind) {
return false;
}
switch (left.maybeExtendedKind) {
case undefined:
return false;
case Type.ExtendedTypeKind.TableType:
return isCompatibleWithFieldSpecificationList(left, right);
case Type.ExtendedTypeKind.DefinedListType:
case Type.ExtendedTypeKind.ListType:
case Type.ExtendedTypeKind.FunctionType:
case Type.ExtendedTypeKind.PrimaryPrimitiveType:
case Type.ExtendedTypeKind.RecordType:
case Type.ExtendedTypeKind.TableTypePrimaryExpression:
return false;
default:
throw Assert.isNever(left);
}
}
function isCompatibleWithTableTypePrimaryExpression(
left: Type.TPowerQueryType,
right: Type.TableTypePrimaryExpression,
): boolean | undefined {
if (left.kind !== right.kind) {
return false;
}
switch (left.maybeExtendedKind) {
case undefined:
return false;
case Type.ExtendedTypeKind.TableTypePrimaryExpression:
return isCompatible(left.primaryExpression, right.primaryExpression);
case Type.ExtendedTypeKind.DefinedListType:
case Type.ExtendedTypeKind.ListType:
case Type.ExtendedTypeKind.FunctionType:
case Type.ExtendedTypeKind.PrimaryPrimitiveType:
case Type.ExtendedTypeKind.RecordType:
case Type.ExtendedTypeKind.TableType:
return false;
default:
throw Assert.isNever(left);
}
}
function isCompatibleWithLiteral<T extends Type.TLiteral>(left: Type.TPowerQueryType, right: T): boolean {
if (left.kind !== right.kind || !left.maybeExtendedKind || left.maybeExtendedKind !== right.maybeExtendedKind) {
return false;
} else {
return left.normalizedLiteral === right.normalizedLiteral;
}
}
function isCompatibleDefinedListOrDefinedListType<T extends Type.DefinedList | Type.DefinedListType>(
left: T,
right: T,
): boolean {
let leftElements: ReadonlyArray<Type.TPowerQueryType>;
let rightElements: ReadonlyArray<Type.TPowerQueryType>;
if (
left.maybeExtendedKind === Type.ExtendedTypeKind.DefinedList &&
right.maybeExtendedKind === Type.ExtendedTypeKind.DefinedList
) {
leftElements = left.elements;
rightElements = right.elements;
} else if (
left.maybeExtendedKind === Type.ExtendedTypeKind.DefinedListType &&
right.maybeExtendedKind === Type.ExtendedTypeKind.DefinedListType
) {
leftElements = left.itemTypes;
rightElements = right.itemTypes;
} else {
throw new CommonError.InvariantError(`unknown scenario for isCompatibleDefinedListOrDefinedListType`, {
leftTypeKind: left.kind,
rightTypeKind: right.kind,
leftMaybeExtendedTypeKind: left.maybeExtendedKind,
rightMaybeExtendedTypeKind: right.maybeExtendedKind,
});
}
if (leftElements.length !== rightElements.length) {
return false;
}
const numElements: number = leftElements.length;
for (let index: number = 0; index < numElements; index += 1) {
if (!isCompatible(leftElements[index], rightElements[index])) {
return false;
}
}
return true;
}
function isCompatibleWithPrimitiveOrLiteral(
left: Type.TPowerQueryType,
right: Type.TLogical | Type.TText | Type.TNumber,
): boolean {
return left.kind === right.kind && (!right.maybeExtendedKind || isCompatibleWithLiteral(left, right));
}
function isCompatibleWithType(
left: Type.TPowerQueryType,
right:
| Type.DefinedListType
| Type.FunctionType
| Type.ListType
| Type.PrimaryPrimitiveType
| Type.RecordType
| Type.TableType
| Type.TableTypePrimaryExpression
| Type.Type,
): boolean | undefined {
if (left.kind !== right.kind) {
return false;
}
switch (right.maybeExtendedKind) {
case undefined:
return true;
case Type.ExtendedTypeKind.FunctionType:
return isCompatibleWithFunctionSignature(left, right);
case Type.ExtendedTypeKind.ListType:
return isCompatibleWithListType(left, right);
case Type.ExtendedTypeKind.DefinedListType:
return isCompatibleWithDefinedListType(left, right);
case Type.ExtendedTypeKind.PrimaryPrimitiveType:
return isCompatibleWithPrimaryPrimitiveType(left, right);
case Type.ExtendedTypeKind.RecordType:
return isCompatibleWithRecordType(left, right);
case Type.ExtendedTypeKind.TableType:
return isCompatibleWithTableType(left, right);
case Type.ExtendedTypeKind.TableTypePrimaryExpression:
return isCompatibleWithTableTypePrimaryExpression(left, right);
default:
throw Assert.isNever(right);
}
}
function isDefinedListTypeCompatibleWithListType(definedList: Type.DefinedListType, listType: Type.ListType): boolean {
const itemTypeCompatabilities: ReadonlyArray<boolean | undefined> = definedList.itemTypes.map(itemType =>
isCompatible(itemType, listType.itemType),
);
return itemTypeCompatabilities.find(value => value === undefined || value === false) !== undefined;
} | the_stack |
import assert from 'assert'
import clamp from 'lodash/clamp'
import pick from 'lodash/pick'
import round from 'lodash/round'
import { getPipetteNameSpecs } from '@opentrons/shared-data'
import {
SOURCE_WELL_BLOWOUT_DESTINATION,
DEST_WELL_BLOWOUT_DESTINATION,
} from '@opentrons/step-generation'
import { getWellRatio } from '../../utils'
import { getDefaultsForStepType } from '../getDefaultsForStepType'
import { makeConditionalPatchUpdater } from './makeConditionalPatchUpdater'
import {
chainPatchUpdaters,
fieldHasChanged,
getChannels,
getDefaultWells,
getAllWellsFromPrimaryWells,
getMaxDisposalVolumeForMultidispense,
volumeInCapacityForMulti,
DISPOSAL_VOL_DIGITS,
} from './utils'
import type {
LabwareEntities,
PipetteEntities,
} from '@opentrons/step-generation'
import { FormData, StepFieldName } from '../../../form-types'
import { FormPatch } from '../../actions/types'
import {
getMinPipetteVolume,
getPipetteCapacity,
} from '../../../pipettes/pipetteData'
// TODO: Ian 2019-02-21 import this from a more central place - see #2926
const getDefaultFields = (...fields: StepFieldName[]): FormPatch =>
pick(getDefaultsForStepType('moveLiquid'), fields)
const wellRatioUpdatesMap = [
{
prevValue: 'n:n',
nextValue: '1:many',
dependentFields: [
{
name: 'changeTip',
prevValue: 'perSource',
nextValue: 'always',
},
{
name: 'changeTip',
prevValue: 'perDest',
nextValue: 'always',
},
],
},
{
prevValue: 'n:n',
nextValue: 'many:1',
dependentFields: [
// no updates, all possible values are OK
],
},
{
prevValue: '1:many',
nextValue: 'n:n',
dependentFields: [
{
name: 'changeTip',
prevValue: 'perSource',
nextValue: 'always',
},
{
name: 'changeTip',
prevValue: 'perDest',
nextValue: 'always',
},
{
name: 'path',
prevValue: 'multiDispense',
nextValue: 'single',
},
],
},
{
prevValue: '1:many',
nextValue: 'many:1',
dependentFields: [
{
name: 'changeTip',
prevValue: 'perSource',
nextValue: 'always',
},
{
name: 'changeTip',
prevValue: 'perDest',
nextValue: 'always',
},
{
name: 'path',
prevValue: 'multiDispense',
nextValue: 'single',
},
],
},
{
prevValue: 'many:1',
nextValue: 'n:n',
dependentFields: [
{
name: 'path',
prevValue: 'multiAspirate',
nextValue: 'single',
},
],
},
{
prevValue: 'many:1',
nextValue: '1:many',
dependentFields: [
{
name: 'changeTip',
prevValue: 'perSource',
nextValue: 'always',
},
{
name: 'path',
prevValue: 'multiAspirate',
nextValue: 'single',
},
],
},
]
const wellRatioUpdater = makeConditionalPatchUpdater(wellRatioUpdatesMap)
export function updatePatchPathField(
patch: FormPatch,
rawForm: FormData,
pipetteEntities: PipetteEntities
): FormPatch {
const { id, stepType, ...stepData } = rawForm
const appliedPatch = { ...(stepData as FormPatch), ...patch }
const { path, changeTip } = appliedPatch
if (!path) {
// invalid well ratio - fall back to 'single'
return { ...patch, path: 'single' }
}
let pipetteCapacityExceeded = false
if (
appliedPatch.volume &&
typeof appliedPatch.pipette === 'string' &&
appliedPatch.pipette in pipetteEntities
) {
pipetteCapacityExceeded = !volumeInCapacityForMulti(
// @ts-expect-error(sa, 2021-6-14): appliedPatch is not of type FormData, address in #3161
appliedPatch,
pipetteEntities
)
}
// changeTip value incompatible with next path value
const incompatiblePath =
(changeTip === 'perSource' && path === 'multiAspirate') ||
(changeTip === 'perDest' && path === 'multiDispense')
if (pipetteCapacityExceeded || incompatiblePath) {
return { ...patch, path: 'single' }
}
return patch
}
const updatePatchOnLabwareChange = (
patch: FormPatch,
rawForm: FormData,
labwareEntities: LabwareEntities,
pipetteEntities: PipetteEntities
): FormPatch => {
const sourceLabwareChanged = fieldHasChanged(
rawForm,
patch,
'aspirate_labware'
)
const destLabwareChanged = fieldHasChanged(rawForm, patch, 'dispense_labware')
if (!sourceLabwareChanged && !destLabwareChanged) return patch
const { id, stepType, ...stepData } = rawForm
const appliedPatch = { ...(stepData as FormPatch), ...patch, id, stepType }
// @ts-expect-error(sa, 2021-6-14): appliedPatch.pipette is type ?unknown. Address in #3161
const pipetteId: string = appliedPatch.pipette
const sourceLabwarePatch: FormPatch = sourceLabwareChanged
? {
...getDefaultFields(
'aspirate_mmFromBottom',
'aspirate_touchTip_mmFromBottom'
),
aspirate_wells: getDefaultWells({
// @ts-expect-error(sa, 2021-6-14): appliedPatch.pipette is type ?unknown. Address in #3161
labwareId: appliedPatch.aspirate_labware,
pipetteId,
labwareEntities,
pipetteEntities,
}),
}
: {}
const destLabwarePatch: FormPatch = destLabwareChanged
? {
...getDefaultFields(
'dispense_mmFromBottom',
'dispense_touchTip_mmFromBottom'
),
dispense_wells: getDefaultWells({
// @ts-expect-error(sa, 2021-6-14): appliedPatch.pipette is type ?unknown. Address in #3161
labwareId: appliedPatch.dispense_labware,
pipetteId,
labwareEntities,
pipetteEntities,
}),
}
: {}
return { ...sourceLabwarePatch, ...destLabwarePatch }
}
const updatePatchOnPipetteChange = (
patch: FormPatch,
rawForm: FormData,
pipetteEntities: PipetteEntities
): FormPatch => {
// when pipette ID is changed (to another ID, or to null),
// set any flow rates, mix volumes, or disposal volumes to null
// and set air gap volume to default (= pipette minimum)
if (fieldHasChanged(rawForm, patch, 'pipette')) {
const newPipette = patch.pipette
let airGapVolume: string | null = null
if (typeof newPipette === 'string' && newPipette in pipetteEntities) {
const pipetteSpec = pipetteEntities[newPipette].spec
airGapVolume = `${pipetteSpec.minVolume}`
}
return {
...patch,
...getDefaultFields(
'aspirate_flowRate',
'dispense_flowRate',
'aspirate_mix_volume',
'dispense_mix_volume',
'disposalVolume_volume',
'aspirate_mmFromBottom',
'dispense_mmFromBottom'
),
aspirate_airGap_volume: airGapVolume,
dispense_airGap_volume: airGapVolume,
}
}
return patch
}
const getClearedDisposalVolumeFields = (): FormPatch =>
getDefaultFields('disposalVolume_volume', 'disposalVolume_checkbox')
const clampAspirateAirGapVolume = (
patch: FormPatch,
rawForm: FormData,
pipetteEntities: PipetteEntities
): FormPatch => {
const patchedAspirateAirgapVolume =
patch.aspirate_airGap_volume ?? rawForm?.aspirate_airGap_volume
const pipetteId = patch.pipette ?? rawForm.pipette
if (
patchedAspirateAirgapVolume &&
typeof pipetteId === 'string' &&
pipetteId in pipetteEntities
) {
const pipetteEntity = pipetteEntities[pipetteId]
const minPipetteVolume = getMinPipetteVolume(pipetteEntity)
const minAirGapVolume = 0 // NOTE: a form level warning will occur if the air gap volume is below the pipette min volume
const maxAirGapVolume = getPipetteCapacity(pipetteEntity) - minPipetteVolume
const clampedAirGapVolume = clamp(
Number(patchedAspirateAirgapVolume),
minAirGapVolume,
maxAirGapVolume
)
if (clampedAirGapVolume === Number(patchedAspirateAirgapVolume))
return patch
return { ...patch, aspirate_airGap_volume: String(clampedAirGapVolume) }
}
return patch
}
const clampDispenseAirGapVolume = (
patch: FormPatch,
rawForm: FormData,
pipetteEntities: PipetteEntities
): FormPatch => {
const { id, stepType, ...stepData } = rawForm
const appliedPatch = { ...(stepData as FormPatch), ...patch, id, stepType }
// @ts-expect-error(sa, 2021-6-14): appliedPatch.pipette does not exist. Address in #3161
const pipetteId: string = appliedPatch.pipette
// @ts-expect-error(sa, 2021-6-14): appliedPatch.disposalVolume_checkbox does not exist. Address in #3161
const disposalVolume = appliedPatch.disposalVolume_checkbox
? // @ts-expect-error(sa, 2021-6-14): appliedPatch.disposalVolume_volume does not exist. Address in #3161
Number(appliedPatch.disposalVolume_volume) || 0
: 0
// @ts-expect-error(sa, 2021-6-14): appliedPatch.volume does not exist. Address in #3161
const transferVolume = Number(appliedPatch.volume)
// @ts-expect-error(sa, 2021-6-14): appliedPatch.dispense_airGap_volume does not exist. Address in #3161
const dispenseAirGapVolume = Number(appliedPatch.dispense_airGap_volume)
if (
// @ts-expect-error(sa, 2021-6-14): appliedPatch.dispense_airGap_volume does not exist. Address in #3161
appliedPatch.dispense_airGap_volume &&
typeof pipetteId === 'string' &&
pipetteId in pipetteEntities
) {
const pipetteEntity = pipetteEntities[pipetteId]
const capacity = getPipetteCapacity(pipetteEntity)
const minAirGapVolume = 0 // NOTE: a form level warning will occur if the air gap volume is below the pipette min volume
const maxAirGapVolume =
// @ts-expect-error(sa, 2021-6-14): appliedPatch.path does not exist. Address in #3161
appliedPatch.path === 'multiDispense'
? capacity - disposalVolume - transferVolume
: capacity
const clampedAirGapVolume = clamp(
dispenseAirGapVolume,
minAirGapVolume,
maxAirGapVolume
)
if (clampedAirGapVolume === dispenseAirGapVolume) return patch
return { ...patch, dispense_airGap_volume: String(clampedAirGapVolume) }
}
return patch
}
const updatePatchDisposalVolumeFields = (
patch: FormPatch,
rawForm: FormData,
pipetteEntities: PipetteEntities
): FormPatch => {
const { id, stepType, ...stepData } = rawForm
const appliedPatch = { ...(stepData as FormPatch), ...patch, id, stepType }
const pathChangedFromMultiDispense =
patch.path &&
patch.path !== 'multiDispense' &&
rawForm.path === 'multiDispense'
if (pathChangedFromMultiDispense || patch.disposalVolume_checkbox === false) {
// clear disposal volume whenever path is changed from multiDispense
// or whenever disposalVolume_checkbox is cleared
return { ...patch, ...getClearedDisposalVolumeFields() }
}
const shouldReinitializeDisposalVolume =
(patch.path === 'multiDispense' && rawForm.path !== 'multiDispense') ||
(patch.pipette && patch.pipette !== rawForm.pipette) ||
patch.disposalVolume_checkbox
if (
shouldReinitializeDisposalVolume &&
// @ts-expect-error(sa, 2021-6-14): appliedPatch.pipette does not exist. Address in #3161
typeof appliedPatch.pipette === 'string'
) {
// @ts-expect-error(sa, 2021-6-14): appliedPatch.pipette does not exist. Address in #3161
const pipetteEntity = pipetteEntities[appliedPatch.pipette]
const pipetteSpec = getPipetteNameSpecs(pipetteEntity.name)
const recommendedMinimumDisposalVol =
(pipetteSpec && pipetteSpec.minVolume) || 0
// reset to recommended vol. Expects `clampDisposalVolume` to reduce it if needed
return {
...patch,
disposalVolume_checkbox: true,
disposalVolume_volume: String(recommendedMinimumDisposalVol || 0),
}
}
return patch
}
// clamp disposal volume so it cannot be negative, or exceed the capacity for multiDispense
// also rounds it to acceptable digits before clamping
const clampDisposalVolume = (
patch: FormPatch,
rawForm: FormData,
pipetteEntities: PipetteEntities
): FormPatch => {
const { id, stepType, ...stepData } = rawForm
const appliedPatch = { ...(stepData as FormPatch), ...patch, id, stepType }
// @ts-expect-error(sa, 2021-6-14): appliedPatch isn't well-typed, address in #3161
const isDecimalString = appliedPatch.disposalVolume_volume === '.'
// @ts-expect-error(sa, 2021-6-14): appliedPatch isn't well-typed, address in #3161
if (appliedPatch.path !== 'multiDispense' || isDecimalString) return patch
const maxDisposalVolume = getMaxDisposalVolumeForMultidispense(
// @ts-expect-error(sa, 2021-6-14): appliedPatch isn't well-typed, address in #3161
appliedPatch,
pipetteEntities
)
if (maxDisposalVolume == null) {
assert(
false,
`clampDisposalVolume got null maxDisposalVolume for pipette, something weird happened`
)
return patch
}
// @ts-expect-error(sa, 2021-6-14): appliedPatch.disposalVolume_volume does not exist. Address in #3161
const candidateDispVolNum = Number(appliedPatch.disposalVolume_volume)
const nextDisposalVolume = clamp(
round(candidateDispVolNum, DISPOSAL_VOL_DIGITS),
0,
maxDisposalVolume
)
if (nextDisposalVolume === candidateDispVolNum) {
// this preserves decimals
return patch
}
if (nextDisposalVolume > 0) {
return { ...patch, disposalVolume_volume: String(nextDisposalVolume) }
}
// clear out if path is new, or set to zero/null depending on checkbox
return rawForm.path === 'multiDispense'
? {
...patch,
// @ts-expect-error(sa, 2021-6-14): appliedPatch.disposalVolume_checkbox does not exist. Address in #3161
disposalVolume_volume: appliedPatch.disposalVolume_checkbox
? '0'
: null,
}
: { ...patch, ...getClearedDisposalVolumeFields() }
}
const updatePatchOnPipetteChannelChange = (
patch: FormPatch,
rawForm: FormData,
labwareEntities: LabwareEntities,
pipetteEntities: PipetteEntities
): FormPatch => {
if (patch.pipette === undefined) return patch
let update: FormPatch = {}
const prevChannels = getChannels(rawForm.pipette, pipetteEntities)
const nextChannels =
typeof patch.pipette === 'string'
? getChannels(patch.pipette, pipetteEntities)
: null
const { id, stepType, ...stepData } = rawForm
const appliedPatch = { ...(stepData as FormPatch), ...patch, id, stepType }
const singleToMulti = prevChannels === 1 && nextChannels === 8
const multiToSingle = prevChannels === 8 && nextChannels === 1
if (patch.pipette === null || singleToMulti) {
// reset all well selection
// @ts-expect-error(sa, 2021-6-14): appliedPatch.pipette does not exist. Address in #3161
const pipetteId: string = appliedPatch.pipette
update = {
aspirate_wells: getDefaultWells({
// @ts-expect-error(sa, 2021-6-14): appliedPatch.aspirate_labware does not exist. Address in #3161
labwareId: appliedPatch.aspirate_labware,
pipetteId,
labwareEntities,
pipetteEntities,
}),
dispense_wells: getDefaultWells({
// @ts-expect-error(sa, 2021-6-14): appliedPatch.dispense_labware does not exist. Address in #3161
labwareId: appliedPatch.dispense_labware,
pipetteId,
labwareEntities,
pipetteEntities,
}),
}
} else if (multiToSingle) {
// multi-channel to single-channel: convert primary wells to all wells
// @ts-expect-error(sa, 2021-06-14): appliedPatch.aspirate_labware is type ?unknown. Address in #3161
const sourceLabwareId: string = appliedPatch.aspirate_labware
// @ts-expect-error(sa, 2021-06-14): appliedPatch.dispense_labware is type ?unknown. Address in #3161
const destLabwareId: string = appliedPatch.dispense_labware
const sourceLabware = sourceLabwareId && labwareEntities[sourceLabwareId]
const sourceLabwareDef = sourceLabware && sourceLabware.def
const destLabware = destLabwareId && labwareEntities[destLabwareId]
const destLabwareDef = destLabware && destLabware.def
update = {
aspirate_wells: getAllWellsFromPrimaryWells(
// @ts-expect-error(sa, 2021-06-14): appliedPatch.aspirate_wells is type ?unknown. Address in #3161
appliedPatch.aspirate_wells, // @ts-expect-error(sa, 2021-06-14): sourceLabwareDef is not typed properly. Address in #3161
sourceLabwareDef
),
dispense_wells: getAllWellsFromPrimaryWells(
// @ts-expect-error(sa, 2021-06-14): appliedPatch.dispense_wells is type ?unknown. Address in #3161
appliedPatch.dispense_wells, // @ts-expect-error(sa, 2021-06-14): destLabwareDef is not typed properly. Address in #3161
destLabwareDef
),
}
}
return { ...patch, ...update }
}
function updatePatchOnWellRatioChange(
patch: FormPatch,
rawForm: FormData
): FormPatch {
const appliedPatch = { ...rawForm, ...patch }
const prevWellRatio = getWellRatio(
rawForm.aspirate_wells,
rawForm.dispense_wells
)
const nextWellRatio = getWellRatio(
appliedPatch.aspirate_wells,
appliedPatch.dispense_wells
)
if (!nextWellRatio || !prevWellRatio) {
// selected invalid well combo (eg 2:3, 0:1, etc). Reset path to 'single' and reset changeTip if invalid
const resetChangeTip = ['perSource', 'perDest'].includes(
appliedPatch.changeTip
)
const resetPath = { ...patch, path: 'single' }
return resetChangeTip ? { ...resetPath, changeTip: 'always' } : resetPath
}
if (nextWellRatio === prevWellRatio) return patch
return {
...patch,
...(wellRatioUpdater(
prevWellRatio,
nextWellRatio,
appliedPatch
) as FormPatch),
}
}
function updatePatchMixFields(patch: FormPatch, rawForm: FormData): FormPatch {
if (patch.path) {
if (patch.path === 'multiAspirate') {
return {
...patch,
...getDefaultFields(
'aspirate_mix_checkbox',
'aspirate_mix_times',
'aspirate_mix_volume'
),
}
}
if (patch.path === 'multiDispense') {
return {
...patch,
...getDefaultFields(
'dispense_mix_checkbox',
'dispense_mix_times',
'dispense_mix_volume'
),
}
}
}
return patch
}
export function updatePatchBlowoutFields(
patch: FormPatch,
rawForm: FormData
): FormPatch {
const { id, stepType, ...stepData } = rawForm
const appliedPatch = { ...(stepData as FormPatch), ...patch, id, stepType }
if (fieldHasChanged(rawForm, patch, 'path')) {
// @ts-expect-error(sa, 2021-06-14): appliedPatch.blowout_location does not exist. Address in #3161
const { path, blowout_location } = appliedPatch
// reset blowout_location when path changes to avoid invalid location for path
// or reset whenever checkbox is toggled
const shouldResetBlowoutLocation =
(path === 'multiAspirate' &&
blowout_location === SOURCE_WELL_BLOWOUT_DESTINATION) ||
(path === 'multiDispense' &&
blowout_location === DEST_WELL_BLOWOUT_DESTINATION)
if (shouldResetBlowoutLocation) {
return { ...patch, ...getDefaultFields('blowout_location') }
}
}
return patch
}
export function dependentFieldsUpdateMoveLiquid(
originalPatch: FormPatch,
rawForm: FormData, // raw = NOT hydrated
pipetteEntities: PipetteEntities,
labwareEntities: LabwareEntities
): FormPatch {
// sequentially modify parts of the patch until it's fully updated
return chainPatchUpdaters(originalPatch, [
chainPatch =>
updatePatchOnLabwareChange(
chainPatch,
rawForm,
labwareEntities,
pipetteEntities
),
chainPatch =>
updatePatchOnPipetteChannelChange(
chainPatch,
rawForm,
labwareEntities,
pipetteEntities
),
chainPatch =>
updatePatchOnPipetteChange(chainPatch, rawForm, pipetteEntities),
chainPatch => updatePatchOnWellRatioChange(chainPatch, rawForm),
chainPatch => updatePatchPathField(chainPatch, rawForm, pipetteEntities),
chainPatch =>
updatePatchDisposalVolumeFields(chainPatch, rawForm, pipetteEntities),
chainPatch =>
clampAspirateAirGapVolume(chainPatch, rawForm, pipetteEntities),
chainPatch => clampDisposalVolume(chainPatch, rawForm, pipetteEntities),
chainPatch => updatePatchMixFields(chainPatch, rawForm),
chainPatch => updatePatchBlowoutFields(chainPatch, rawForm),
chainPatch =>
clampDispenseAirGapVolume(chainPatch, rawForm, pipetteEntities),
])
} | the_stack |
import type { ConsumerOptsBuilder } from "./types.ts";
import {
AckPolicy,
ConsumerAPI,
ConsumerConfig,
ConsumerInfo,
ConsumerInfoable,
ConsumerOpts,
DeliverPolicy,
Destroyable,
Empty,
JetStreamClient,
JetStreamOptions,
JetStreamPublishOptions,
JetStreamPullSubscription,
JetStreamSubscription,
JetStreamSubscriptionOptions,
JsHeaders,
JsMsg,
Msg,
NatsConnection,
PubAck,
Pullable,
PullOptions,
ReplayPolicy,
RequestOptions,
} from "./types.ts";
import { BaseApiClient } from "./jsbaseclient_api.ts";
import {
checkJsError,
isFlowControlMsg,
isHeartbeatMsg,
nanos,
validateDurableName,
validateStreamName,
} from "./jsutil.ts";
import { ConsumerAPIImpl } from "./jsmconsumer_api.ts";
import { JsMsgImpl, toJsMsg } from "./jsmsg.ts";
import {
MsgAdapter,
TypedSubscription,
TypedSubscriptionOptions,
} from "./typedsub.ts";
import { ErrorCode, isNatsError, NatsError } from "./error.ts";
import { SubscriptionImpl } from "./subscription.ts";
import {
IngestionFilterFn,
IngestionFilterFnResult,
QueuedIterator,
QueuedIteratorImpl,
} from "./queued_iterator.ts";
import { Timeout, timeout } from "./util.ts";
import { createInbox } from "./protocol.ts";
import { headers } from "./headers.ts";
import { consumerOpts, isConsumerOptsBuilder } from "./jsconsumeropts.ts";
export interface JetStreamSubscriptionInfoable {
info: JetStreamSubscriptionInfo | null;
}
enum PubHeaders {
MsgIdHdr = "Nats-Msg-Id",
ExpectedStreamHdr = "Nats-Expected-Stream",
ExpectedLastSeqHdr = "Nats-Expected-Last-Sequence",
ExpectedLastMsgIdHdr = "Nats-Expected-Last-Msg-Id",
ExpectedLastSubjectSequenceHdr = "Nats-Expected-Last-Subject-Sequence",
}
export class JetStreamClientImpl extends BaseApiClient
implements JetStreamClient {
api: ConsumerAPI;
constructor(nc: NatsConnection, opts?: JetStreamOptions) {
super(nc, opts);
this.api = new ConsumerAPIImpl(nc, opts);
}
async publish(
subj: string,
data: Uint8Array = Empty,
opts?: Partial<JetStreamPublishOptions>,
): Promise<PubAck> {
opts = opts || {};
opts.expect = opts.expect || {};
const mh = opts?.headers || headers();
if (opts) {
if (opts.msgID) {
mh.set(PubHeaders.MsgIdHdr, opts.msgID);
}
if (opts.expect.lastMsgID) {
mh.set(PubHeaders.ExpectedLastMsgIdHdr, opts.expect.lastMsgID);
}
if (opts.expect.streamName) {
mh.set(PubHeaders.ExpectedStreamHdr, opts.expect.streamName);
}
if (opts.expect.lastSequence) {
mh.set(PubHeaders.ExpectedLastSeqHdr, `${opts.expect.lastSequence}`);
}
if (opts.expect.lastSubjectSequence) {
mh.set(
PubHeaders.ExpectedLastSubjectSequenceHdr,
`${opts.expect.lastSubjectSequence}`,
);
}
}
const to = opts.timeout || this.timeout;
const ro = {} as RequestOptions;
if (to) {
ro.timeout = to;
}
if (opts) {
ro.headers = mh;
}
const r = await this.nc.request(subj, data, ro);
const pa = this.parseJsResponse(r) as PubAck;
if (pa.stream === "") {
throw NatsError.errorForCode(ErrorCode.JetStreamInvalidAck);
}
pa.duplicate = pa.duplicate ? pa.duplicate : false;
return pa;
}
async pull(stream: string, durable: string): Promise<JsMsg> {
validateStreamName(stream);
validateDurableName(durable);
const msg = await this.nc.request(
// FIXME: specify expires
`${this.prefix}.CONSUMER.MSG.NEXT.${stream}.${durable}`,
this.jc.encode({ no_wait: true, batch: 1, expires: nanos(this.timeout) }),
{ noMux: true, timeout: this.timeout },
);
const err = checkJsError(msg);
if (err) {
throw (err);
}
return toJsMsg(msg);
}
/*
* Returns available messages upto specified batch count.
* If expires is set the iterator will wait for the specified
* amount of millis before closing the subscription.
* If no_wait is specified, the iterator will return no messages.
* @param stream
* @param durable
* @param opts
*/
fetch(
stream: string,
durable: string,
opts: Partial<PullOptions> = {},
): QueuedIterator<JsMsg> {
validateStreamName(stream);
validateDurableName(durable);
let timer: Timeout<void> | null = null;
const args: Partial<PullOptions> = {};
args.batch = opts.batch || 1;
args.no_wait = opts.no_wait || false;
const expires = opts.expires || 0;
if (expires) {
args.expires = nanos(expires);
}
if (expires === 0 && args.no_wait === false) {
throw new Error("expires or no_wait is required");
}
const qi = new QueuedIteratorImpl<JsMsg>();
const wants = args.batch;
let received = 0;
// FIXME: this looks weird, we want to stop the iterator
// but doing it from a dispatchedFn...
qi.dispatchedFn = (m: JsMsg | null) => {
if (m) {
received++;
if (timer && m.info.pending === 0) {
// the expiration will close it
return;
}
// if we have one pending and we got the expected
// or there are no more stop the iterator
if (
qi.getPending() === 1 && m.info.pending === 0 || wants === received
) {
qi.stop();
}
}
};
const inbox = createInbox(this.nc.options.inboxPrefix);
const sub = this.nc.subscribe(inbox, {
max: opts.batch,
callback: (err: Error | null, msg) => {
if (err === null) {
err = checkJsError(msg);
}
if (err !== null) {
if (timer) {
timer.cancel();
timer = null;
}
if (
isNatsError(err) && err.code === ErrorCode.JetStream404NoMessages
) {
qi.stop();
} else {
qi.stop(err);
}
} else {
qi.received++;
qi.push(toJsMsg(msg));
}
},
});
// timer on the client the issue is that the request
// is started on the client, which means that it will expire
// on the client first
if (expires) {
timer = timeout<void>(expires);
timer.catch(() => {
if (!sub.isClosed()) {
sub.drain();
timer = null;
}
});
}
(async () => {
// close the iterator if the connection or subscription closes unexpectedly
await (sub as SubscriptionImpl).closed;
if (timer !== null) {
timer.cancel();
timer = null;
}
qi.stop();
})().catch();
this.nc.publish(
`${this.prefix}.CONSUMER.MSG.NEXT.${stream}.${durable}`,
this.jc.encode(args),
{ reply: inbox },
);
return qi;
}
async pullSubscribe(
subject: string,
opts: ConsumerOptsBuilder | Partial<ConsumerOpts> = consumerOpts(),
): Promise<JetStreamPullSubscription> {
const cso = await this._processOptions(subject, opts);
if (cso.ordered) {
throw new Error("pull subscribers cannot be be ordered");
}
if (!cso.attached) {
cso.config.filter_subject = subject;
}
if (cso.config.deliver_subject) {
throw new Error(
"consumer info specifies deliver_subject - pull consumers cannot have deliver_subject set",
);
}
const ackPolicy = cso.config.ack_policy;
if (ackPolicy === AckPolicy.None || ackPolicy === AckPolicy.All) {
throw new Error("ack policy for pull consumers must be explicit");
}
const so = this._buildTypedSubscriptionOpts(cso);
const sub = new JetStreamPullSubscriptionImpl(
this,
cso.deliver,
so,
);
sub.info = cso;
try {
await this._maybeCreateConsumer(cso);
} catch (err) {
sub.unsubscribe();
throw err;
}
return sub as JetStreamPullSubscription;
}
async subscribe(
subject: string,
opts: ConsumerOptsBuilder | Partial<ConsumerOpts> = consumerOpts(),
): Promise<JetStreamSubscription> {
const cso = await this._processOptions(subject, opts);
// this effectively requires deliver subject to be specified
// as an option otherwise we have a pull consumer
if (!cso.config.deliver_subject) {
throw new Error(
"consumer info specifies a pull consumer - deliver_subject is required",
);
}
const so = this._buildTypedSubscriptionOpts(cso);
const sub = new JetStreamSubscriptionImpl(
this,
cso.deliver,
so,
);
sub.info = cso;
try {
await this._maybeCreateConsumer(cso);
} catch (err) {
sub.unsubscribe();
throw err;
}
return sub;
}
async _processOptions(
subject: string,
opts: ConsumerOptsBuilder | Partial<ConsumerOpts> = consumerOpts(),
): Promise<JetStreamSubscriptionInfo> {
const jsi =
(isConsumerOptsBuilder(opts)
? opts.getOpts()
: opts) as JetStreamSubscriptionInfo;
jsi.flow_control = {
heartbeat_count: 0,
fc_count: 0,
consumer_restarts: 0,
};
if (jsi.ordered) {
jsi.ordered_consumer_sequence = { stream_seq: 0, delivery_seq: 0 };
if (
jsi.config.ack_policy !== AckPolicy.NotSet &&
jsi.config.ack_policy !== AckPolicy.None
) {
throw new NatsError(
"ordered consumer: ack_policy can only be set to 'none'",
ErrorCode.ApiError,
);
}
if (jsi.config.durable_name && jsi.config.durable_name.length > 0) {
throw new NatsError(
"ordered consumer: durable_name cannot be set",
ErrorCode.ApiError,
);
}
if (jsi.config.deliver_subject && jsi.config.deliver_subject.length > 0) {
throw new NatsError(
"ordered consumer: deliver_subject cannot be set",
ErrorCode.ApiError,
);
}
if (
jsi.config.max_deliver !== undefined && jsi.config.max_deliver > 1
) {
throw new NatsError(
"ordered consumer: max_deliver cannot be set",
ErrorCode.ApiError,
);
}
if (jsi.config.deliver_group && jsi.config.deliver_group.length > 0) {
throw new NatsError(
"ordered consumer: deliver_group cannot be set",
ErrorCode.ApiError,
);
}
jsi.config.deliver_subject = createInbox();
jsi.config.ack_policy = AckPolicy.None;
jsi.config.max_deliver = 1;
jsi.config.flow_control = true;
jsi.config.idle_heartbeat = jsi.config.idle_heartbeat || nanos(5000);
jsi.config.ack_wait = nanos(22 * 60 * 60 * 1000);
}
if (jsi.config.ack_policy === AckPolicy.NotSet) {
jsi.config.ack_policy = AckPolicy.All;
}
jsi.api = this;
jsi.config = jsi.config || {} as ConsumerConfig;
jsi.stream = jsi.stream ? jsi.stream : await this.findStream(subject);
jsi.attached = false;
if (jsi.config.durable_name) {
try {
const info = await this.api.info(jsi.stream, jsi.config.durable_name);
if (info) {
if (
info.config.filter_subject && info.config.filter_subject !== subject
) {
throw new Error("subject does not match consumer");
}
const qn = jsi.config.deliver_group ?? "";
const rqn = info.config.deliver_group ?? "";
if (qn !== rqn) {
if (rqn === "") {
throw new Error(
`durable requires no queue group`,
);
} else {
throw new Error(
`durable requires queue group '${rqn}'`,
);
}
}
jsi.config = info.config;
jsi.attached = true;
}
} catch (err) {
//consumer doesn't exist
if (err.code !== "404") {
throw err;
}
}
}
if (!jsi.attached) {
jsi.config.filter_subject = subject;
}
jsi.deliver = jsi.config.deliver_subject ||
createInbox(this.nc.options.inboxPrefix);
return jsi;
}
_buildTypedSubscriptionOpts(
jsi: JetStreamSubscriptionInfo,
): TypedSubscriptionOptions<JsMsg> {
const so = {} as TypedSubscriptionOptions<JsMsg>;
so.adapter = msgAdapter(jsi.callbackFn === undefined);
so.ingestionFilterFn = JetStreamClientImpl.ingestionFn(jsi.ordered);
so.protocolFilterFn = (jm, ingest = false): boolean => {
const jsmi = jm as JsMsgImpl;
if (isFlowControlMsg(jsmi.msg)) {
if (!ingest) {
jsmi.msg.respond();
}
return false;
}
return true;
};
if (!jsi.mack && jsi.config.ack_policy !== AckPolicy.None) {
so.dispatchedFn = autoAckJsMsg;
}
if (jsi.callbackFn) {
so.callback = jsi.callbackFn;
}
so.max = jsi.max || 0;
so.queue = jsi.queue;
return so;
}
async _maybeCreateConsumer(jsi: JetStreamSubscriptionInfo): Promise<void> {
if (jsi.attached) {
return;
}
jsi.config = Object.assign({
deliver_policy: DeliverPolicy.All,
ack_policy: AckPolicy.Explicit,
ack_wait: nanos(30 * 1000),
replay_policy: ReplayPolicy.Instant,
}, jsi.config);
const ci = await this.api.add(jsi.stream, jsi.config);
jsi.name = ci.name;
jsi.config = ci.config;
}
static ingestionFn(
ordered: boolean,
): IngestionFilterFn<JsMsg> {
return (jm: JsMsg | null, ctx?: unknown): IngestionFilterFnResult => {
// ctx is expected to be the iterator (the JetstreamSubscriptionImpl)
const jsub = ctx as JetStreamSubscriptionImpl;
// this shouldn't happen
if (!jm) return { ingest: false, protocol: false };
const jmi = jm as JsMsgImpl;
if (isHeartbeatMsg(jmi.msg)) {
const ingest = ordered ? jsub._checkHbOrderConsumer(jmi.msg) : true;
if (!ordered) {
jsub!.info!.flow_control.heartbeat_count++;
}
return { ingest, protocol: true };
} else if (isFlowControlMsg(jmi.msg)) {
jsub!.info!.flow_control.fc_count++;
return { ingest: true, protocol: true };
}
const ingest = ordered ? jsub._checkOrderedConsumer(jm) : true;
return { ingest, protocol: false };
};
}
}
class JetStreamSubscriptionImpl extends TypedSubscription<JsMsg>
implements JetStreamSubscriptionInfoable, Destroyable, ConsumerInfoable {
js: BaseApiClient;
constructor(
js: BaseApiClient,
subject: string,
opts: JetStreamSubscriptionOptions,
) {
super(js.nc, subject, opts);
this.js = js;
}
set info(info: JetStreamSubscriptionInfo | null) {
(this.sub as SubscriptionImpl).info = info;
}
get info(): JetStreamSubscriptionInfo | null {
return this.sub.info as JetStreamSubscriptionInfo;
}
_resetOrderedConsumer(sseq: number): void {
if (this.info === null || this.sub.isClosed()) {
return;
}
const newDeliver = createInbox(this.js.opts.apiPrefix);
const nci = this.js.nc;
nci._resub(this.sub, newDeliver);
const info = this.info;
info.ordered_consumer_sequence.delivery_seq = 0;
info.flow_control.heartbeat_count = 0;
info.flow_control.fc_count = 0;
info.flow_control.consumer_restarts++;
info.deliver = newDeliver;
info.config.deliver_subject = newDeliver;
info.config.deliver_policy = DeliverPolicy.StartSequence;
info.config.opt_start_seq = sseq;
const subj = `${info.api.prefix}.CONSUMER.CREATE.${info.stream}`;
this.js._request(subj, this.info.config)
.catch((err) => {
// to inform the subscription we inject an error this will
// be at after the last message if using an iterator.
const nerr = new NatsError(
`unable to recreate ordered consumer ${info.stream} at seq ${sseq}`,
ErrorCode.RequestError,
err,
);
this.sub.callback(nerr, {} as Msg);
});
}
_checkHbOrderConsumer(msg: Msg): boolean {
const rm = msg.headers!.get(JsHeaders.ConsumerStalledHdr);
if (rm !== "") {
const nci = this.js.nc;
nci.publish(rm);
}
const lastDelivered = parseInt(
msg.headers!.get(JsHeaders.LastConsumerSeqHdr),
10,
);
const ordered = this.info!.ordered_consumer_sequence;
this.info!.flow_control.heartbeat_count++;
if (lastDelivered !== ordered.delivery_seq) {
this._resetOrderedConsumer(ordered.stream_seq + 1);
}
return false;
}
_checkOrderedConsumer(jm: JsMsg): boolean {
const ordered = this.info!.ordered_consumer_sequence;
const sseq = jm.info.streamSequence;
const dseq = jm.info.deliverySequence;
if (dseq != ordered.delivery_seq + 1) {
this._resetOrderedConsumer(ordered.stream_seq + 1);
return false;
}
ordered.delivery_seq = dseq;
ordered.stream_seq = sseq;
return true;
}
async destroy(): Promise<void> {
if (!this.isClosed()) {
await this.drain();
}
const jinfo = this.sub.info as JetStreamSubscriptionInfo;
const name = jinfo.config.durable_name || jinfo.name;
const subj = `${jinfo.api.prefix}.CONSUMER.DELETE.${jinfo.stream}.${name}`;
await jinfo.api._request(subj);
}
async consumerInfo(): Promise<ConsumerInfo> {
const jinfo = this.sub.info as JetStreamSubscriptionInfo;
const name = jinfo.config.durable_name || jinfo.name;
const subj = `${jinfo.api.prefix}.CONSUMER.INFO.${jinfo.stream}.${name}`;
return await jinfo.api._request(subj) as ConsumerInfo;
}
}
class JetStreamPullSubscriptionImpl extends JetStreamSubscriptionImpl
implements Pullable {
constructor(
js: BaseApiClient,
subject: string,
opts: TypedSubscriptionOptions<JsMsg>,
) {
super(js, subject, opts);
}
pull(opts: Partial<PullOptions> = { batch: 1 }): void {
const { stream, config } = this.sub.info as JetStreamSubscriptionInfo;
const consumer = config.durable_name;
const args: Partial<PullOptions> = {};
args.batch = opts.batch || 1;
args.no_wait = opts.no_wait || false;
if (opts.expires && opts.expires > 0) {
args.expires = nanos(opts.expires);
}
if (this.info) {
const api = (this.info.api as BaseApiClient);
const subj = `${api.prefix}.CONSUMER.MSG.NEXT.${stream}.${consumer}`;
const reply = this.sub.subject;
api.nc.publish(
subj,
api.jc.encode(args),
{ reply: reply },
);
}
}
}
interface JetStreamSubscriptionInfo extends ConsumerOpts {
api: BaseApiClient;
attached: boolean;
deliver: string;
"ordered_consumer_sequence": { "delivery_seq": number; "stream_seq": number };
"flow_control": {
"heartbeat_count": number;
"fc_count": number;
"consumer_restarts": number;
};
}
function msgAdapter(iterator: boolean): MsgAdapter<JsMsg> {
if (iterator) {
return iterMsgAdapter;
} else {
return cbMsgAdapter;
}
}
function cbMsgAdapter(
err: NatsError | null,
msg: Msg,
): [NatsError | null, JsMsg | null] {
if (err) {
return [err, null];
}
err = checkJsError(msg);
if (err) {
return [err, null];
}
// assuming that the protocolFilterFn is set!
return [null, toJsMsg(msg)];
}
function iterMsgAdapter(
err: NatsError | null,
msg: Msg,
): [NatsError | null, JsMsg | null] {
if (err) {
return [err, null];
}
// iterator will close if we have an error
// check for errors that shouldn't close it
const ne = checkJsError(msg);
if (ne !== null) {
switch (ne.code) {
case ErrorCode.JetStream404NoMessages:
case ErrorCode.JetStream408RequestTimeout:
case ErrorCode.JetStream409MaxAckPendingExceeded:
return [null, null];
default:
return [ne, null];
}
}
// assuming that the protocolFilterFn is set
return [null, toJsMsg(msg)];
}
function autoAckJsMsg(data: JsMsg | null) {
if (data) {
data.ack();
}
} | the_stack |
import { VideoBase, controlsProperty, autoplayProperty, loopProperty, srcProperty, currentTimeProperty, durationProperty } from './common';
import { Screen, Application, Utils, knownFolders, path } from '@nativescript/core';
import { Source } from '..';
import { isString } from '@nativescript/core/utils/types';
const STATE_IDLE: number = 1;
const STATE_BUFFERING: number = 2;
const STATE_READY: number = 3;
const STATE_ENDED: number = 4;
const MATCH_PARENT = 0xffffffff;
const TYPE = { DETECT: 0, SS: 1, DASH: 2, HLS: 3, OTHER: 4 };
export class Video extends VideoBase {
#container: android.widget.LinearLayout;
#sourceView: Source[] = [];
#playerView: com.google.android.exoplayer2.ui.PlayerView;
#player: com.google.android.exoplayer2.SimpleExoPlayer;
#playerListener: com.google.android.exoplayer2.Player.EventListener;
#videoListener: com.google.android.exoplayer2.video.VideoListener;
#src: string;
#autoplay: boolean;
#loop: boolean;
#textureView: android.view.TextureView;
private static _cache: com.google.android.exoplayer2.upstream.cache.SimpleCache;
private static _leastRecentlyUsedCacheEvictor: com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor;
private static _exoDatabaseProvider: com.google.android.exoplayer2.database.ExoDatabaseProvider;
private static _exoPlayerCacheSize = 100 * 1024 * 1024;
private static _dsf: com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
private static _msf: com.google.android.exoplayer2.source.DefaultMediaSourceFactory;
private static _cdsf: com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory;
_isCustom: boolean = false;
_playing: boolean = false;
_timer: any;
_st: android.graphics.SurfaceTexture;
_surface: android.view.Surface;
_render: any;
_frameListener: any;
_canvas: any;
_frameTimer: any;
_readyState: number = 0;
_videoWidth = 0;
_videoHeight = 0;
private static _didInit = false;
static BUFFER_MS = 500;
constructor() {
super();
try {
java.lang.System.loadLibrary('canvasnative');
} catch (ex) {}
const activity: androidx.appcompat.app.AppCompatActivity = Application.android.foregroundActivity || Application.android.startActivity;
if (!Video._didInit) {
const packageName = activity.getPackageName();
const cacheDir = new java.io.File(path.join(knownFolders.documents().path, 'MEDIA_PLAYER_CACHE'));
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
Video._leastRecentlyUsedCacheEvictor = new com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor(Video._exoPlayerCacheSize);
Video._exoDatabaseProvider = new com.google.android.exoplayer2.database.ExoDatabaseProvider(activity);
Video._cache = new com.google.android.exoplayer2.upstream.cache.SimpleCache(cacheDir, Video._leastRecentlyUsedCacheEvictor, Video._exoDatabaseProvider);
Video._dsf = new com.google.android.exoplayer2.upstream.DefaultDataSourceFactory(activity, com.google.android.exoplayer2.util.Util.getUserAgent(activity, packageName));
Video._cdsf = new com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory(Video._cache,Video._dsf)
Video._msf = new com.google.android.exoplayer2.source.DefaultMediaSourceFactory(Video._cdsf);
Video._didInit = true;
}
const builder = new com.google.android.exoplayer2.SimpleExoPlayer.Builder(activity);
builder.setMediaSourceFactory(Video._msf);
const loadControl = new com.google.android.exoplayer2.DefaultLoadControl.Builder();
loadControl.setBufferDurationsMs(Video.BUFFER_MS, com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_MAX_BUFFER_MS, Video.BUFFER_MS, Video.BUFFER_MS);
builder.setLoadControl(loadControl.build());
this.#player = builder.build();
const ref = new WeakRef(this);
this.#playerListener = new com.google.android.exoplayer2.Player.EventListener({
onIsPlayingChanged: function (isPlaying) {
const owner = ref.get();
if (owner) {
const duration = owner.#player.getDuration();
if (owner.duration != duration) {
durationProperty.nativeValueChange(owner, duration);
owner._notifyListener(Video.durationchangeEvent);
}
owner._playing = isPlaying;
if (isPlaying) {
owner._notifyListener(Video.playingEvent);
owner._notifyVideoFrameCallbacks();
if (owner._timer) {
clearInterval(owner._timer);
}
if (owner._frameTimer) {
clearInterval(owner._frameTimer);
}
owner._timer = setInterval(function () {
const current = owner.#player.getCurrentPosition();
if (current != owner.currentTime) {
currentTimeProperty.nativeValueChange(owner, current);
owner._notifyListener(Video.timeupdateEvent);
owner._notifyVideoFrameCallbacks();
}
}, 1000);
} else {
clearInterval(owner._timer);
clearInterval(owner._frameTimer);
currentTimeProperty.nativeValueChange(owner, owner.#player.getCurrentPosition());
}
}
},
onLoadingChanged: function (isLoading) {
//console.log('onLoadingChanged', isLoading);
},
onPlaybackParametersChanged: function (playbackParameters) {},
onPlaybackSuppressionReasonChanged: function (playbackSuppressionReason) {},
onPlayerError: function (error) {
//console.log('PlayerError', error);
},
onPlayerStateChanged: function (playWhenReady, playbackState) {
// console.log('onPlayerStateChanged', Date.now(), playbackState , STATE_BUFFERING);
// if (playbackState === STATE_READY) {
// playerReady = true;
// } else if (playbackState === STATE_ENDED) {
// playerEnded = true;
// }
},
onPositionDiscontinuity: function (reason) {},
onRepeatModeChanged: function (repeatMode) {},
onSeekProcessed: function () {},
onShuffleModeEnabledChanged: function (shuffleModeEnabled) {},
//@ts-ignore
onTimelineChanged(timeline: com.google.android.exoplayer2.Timeline, manifest: any, reason: number) {},
onTracksChanged: function (trackGroups, trackSelections) {},
});
this.#videoListener = new com.google.android.exoplayer2.video.VideoListener({
onRenderedFirstFrame() {},
onVideoSizeChanged(width: number, height: number, unappliedRotationDegrees: number, pixelWidthHeightRatio: number) {
const owner = ref.get();
if (owner) {
owner._videoWidth = width;
owner._videoHeight = height;
}
},
onSurfaceSizeChanged(width: number, height: number) {},
});
const inflator = activity.getLayoutInflater();
const layout = Video.getResourceId(Application.android.foregroundActivity || Application.android.startActivity, 'player');
this.#player.addListener(this.#playerListener);
this.#playerView = inflator.inflate(layout, null, false) as any; //new com.google.android.exoplayer2.ui.PlayerView(Application.android.foregroundActivity || Application.android.startActivity);
this.#container = new android.widget.LinearLayout(Application.android.foregroundActivity || Application.android.startActivity);
const params = new android.widget.LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT);
this.#textureView = new android.view.TextureView(Application.android.foregroundActivity || Application.android.startActivity);
this.#container.addView(this.#textureView as any, params);
this.setNativeView(this.#container);
this.#player.addVideoListener(this.#videoListener);
}
get readyState() {
return this._readyState;
}
_setSurface(surface) {
this.#player.setVideoSurface(surface);
}
private static getResourceId(context: any, res: string = '') {
if (!context) return 0;
if (isString(res)) {
const packageName = context.getPackageName();
try {
const className = java.lang.Class.forName(`${packageName}.R$layout`);
return parseInt(String(className.getDeclaredField(res).get(null)));
} catch (e) {
return 0;
}
}
return 0;
}
static st_count = 0;
static createCustomView() {
const video = new Video();
video._isCustom = true;
video.width = 300;
video.height = 150;
return video;
}
private _setSrc(value: string) {
try {
if (typeof value === 'string' && value.startsWith('~/')) {
value = path.join(knownFolders.currentApp().path, value.replace('~', ''));
}
this.#player.setMediaItem(com.google.android.exoplayer2.MediaItem.fromUri(android.net.Uri.parse(value)));
this.#player.prepare();
if (this.#autoplay) {
this.#player.setPlayWhenReady(true);
}
} catch (e) {
console.log(e);
}
}
_hasFrame = false;
getCurrentFrame(context?: WebGLRenderingContext) {
if (this.isLoaded) {
const surfaceView = this.#playerView.getVideoSurfaceView();
if (surfaceView instanceof android.view.TextureView) {
const st = surfaceView.getSurfaceTexture();
if (st) {
// @ts-ignore
this._render = org.nativescript.canvas.Utils.createRenderAndAttachToGLContext(context, st);
this._st = st;
}
}
}
if (!this._st) {
// @ts-ignore
const result = org.nativescript.canvas.Utils.createSurfaceTexture(context);
this._st = result[0];
const ref = new WeakRef(this);
this._frameListener = new android.graphics.SurfaceTexture.OnFrameAvailableListener({
onFrameAvailable(param0: android.graphics.SurfaceTexture) {
const owner = ref.get();
if (owner) {
owner._hasFrame = true;
owner._notifyVideoFrameCallbacks();
}
},
});
this._st.setOnFrameAvailableListener(this._frameListener);
this._surface = new android.view.Surface(this._st);
this.#player.setVideoSurface(this._surface);
this._render = result[1];
}
if (this._st) {
if (!this._hasFrame) {
return;
}
// @ts-ignore
org.nativescript.canvas.Utils.updateTexImage(context, this._st, this._render, this._videoWidth, this._videoHeight, arguments[4], arguments[5]);
this._hasFrame = false;
}
}
play() {
this.#player.setPlayWhenReady(true);
}
pause() {
this.#player.setPlayWhenReady(false);
}
get muted() {
return this.#player.isDeviceMuted();
}
set muted(value: boolean) {
this.#player.setDeviceMuted(value);
}
get duration() {
return this.#player.getDuration();
}
get currentTime() {
return this.#player.getCurrentPosition() / 1000;
}
set currentTime(value: number) {
this.#player.seekTo(value * 1000);
}
get src() {
return this.#src;
}
set src(value: string) {
this.#src = value;
this._setSrc(value);
}
//@ts-ignore
get autoplay() {
return this.#autoplay;
}
set autoplay(value: boolean) {
this.#player.setPlayWhenReady(value);
}
get controls() {
return this.#playerView.getUseController();
}
set controls(enabled: boolean) {
this.#playerView.setUseController(enabled);
}
// @ts-ignore
get loop() {
return this.#loop;
}
set loop(value: boolean) {
this.#loop = value;
if (value) {
this.#player.setRepeatMode(com.google.android.exoplayer2.Player.REPEAT_MODE_ALL);
} else {
this.#player.setRepeatMode(com.google.android.exoplayer2.Player.REPEAT_MODE_OFF);
}
}
createNativeView(): Object {
if (!this.#playerView) {
this.#playerView = new com.google.android.exoplayer2.ui.PlayerView(this._context);
}
this.#playerView.setPlayer(this.#player);
return this.#playerView;
}
initNativeView() {
super.initNativeView();
}
_addChildFromBuilder(name: string, value: any) {
if (value instanceof Source) {
this.#sourceView.push(value);
}
}
onLoaded() {
super.onLoaded();
if (this.#sourceView.length > 0) {
this._setSrc(this.#sourceView[0].src);
}
}
// @ts-ignore
get width() {
if (this.getMeasuredWidth() > 0) {
return this.getMeasuredWidth();
}
//@ts-ignore
const width = this.#container.getWidth();
if (width === 0) {
//@ts-ignore
let rootParams = this.#container.getLayoutParams();
if (rootParams) {
return rootParams.width;
}
}
return width;
}
set width(value) {
this.style.width = value;
if (this._isCustom) {
this._layoutNative();
}
}
// @ts-ignore
get height() {
if (this.getMeasuredHeight() > 0) {
return this.getMeasuredHeight();
}
//@ts-ignore
const height = this.#container.getHeight();
if (height === 0) {
//@ts-ignore
let rootParams = this.#container.getLayoutParams();
if (rootParams) {
return rootParams.height;
}
}
return height;
}
set height(value) {
this.style.height = value;
if (this._isCustom) {
this._layoutNative();
}
}
_layoutNative() {
if (!this.parent) {
//@ts-ignore
if ((typeof this.width === 'string' && this.width.indexOf('%')) || (typeof this.height === 'string' && this.height.indexOf('%'))) {
return;
}
if (!this._isCustom) {
return;
}
const size = this._realSize;
size.width = size.width * Screen.mainScreen.scale;
size.height = size.height * Screen.mainScreen.scale;
//@ts-ignore
let rootParams = this.#container.getLayoutParams();
if (rootParams && (size.width || 0) === rootParams.width && (size.height || 0) === rootParams.height) {
return;
}
if ((size.width || 0) !== 0 && (size.height || 0) !== 0) {
if (!rootParams) {
rootParams = new android.widget.FrameLayout.LayoutParams(0, 0);
}
rootParams.width = size.width;
rootParams.height = size.height;
let surfaceParams; // = this._canvas.getSurface().getLayoutParams();
if (!surfaceParams) {
surfaceParams = new android.widget.FrameLayout.LayoutParams(0, 0);
}
// surfaceParams.width = size.width;
// surfaceParams.height = size.height;
//@ts-ignore
this.#container.setLayoutParams(rootParams);
const w = android.view.View.MeasureSpec.makeMeasureSpec(size.width, android.view.View.MeasureSpec.EXACTLY);
const h = android.view.View.MeasureSpec.makeMeasureSpec(size.height, android.view.View.MeasureSpec.EXACTLY);
//@ts-ignore
this.#container.measure(w, h);
//@ts-ignore
this.#container.layout(0, 0, size.width || 0, size.height || 0);
if (this._st) {
this._st.setDefaultBufferSize(size.width || 0, size.height || 0);
}
}
}
}
} | the_stack |
export default function makeDashboard(integrationId: string) {
return {
annotations: {
list: [
{
builtIn: 1,
datasource: "-- Grafana --",
enable: true,
hide: true,
iconColor: "rgba(0, 211, 255, 1)",
name: "Annotations & Alerts",
type: "dashboard"
}
]
},
editable: true,
gnetId: null,
graphTooltip: 0,
iteration: 1624297806854,
links: [],
panels: [
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
description: "",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 8,
w: 24,
x: 0,
y: 0
},
hiddenSeries: false,
id: 2,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(rate(distsender_batches{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
legendFormat: "Batch",
refId: "A"
},
{
exemplar: true,
expr: `sum(rate(distsender_batches_partial{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
legendFormat: "Partial Batches",
refId: "B"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "Batches",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:159",
format: "short",
label: "batches",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:160",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 8,
w: 24,
x: 0,
y: 8
},
hiddenSeries: false,
id: 4,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(rate(distsender_rpc_sent{integration_id="${integrationId}"}[5m]))`,
interval: "",
intervalFactor: 2,
legendFormat: "RPCs Sent",
refId: "A"
},
{
exemplar: true,
expr: `sum(rate(distsender_rpc_sent_local{integration_id="${integrationId}"}[5m]))`,
interval: "",
legendFormat: "Local Fast-path",
refId: "B"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "RPCs",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:309",
format: "short",
label: "rpcs",
logBase: 1,
max: null,
min: null,
show: true
},
{
$$hashKey: "object:310",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 7,
w: 24,
x: 0,
y: 16
},
hiddenSeries: false,
id: 6,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 2,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(rate(distsender_rpc_sent_nextreplicaerror{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
hide: false,
interval: "",
intervalFactor: 1,
legendFormat: "Replica Errors",
refId: "A"
},
{
exemplar: true,
expr: `sum(rate(distsender_errors_notleaseholder{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
intervalFactor: 1,
legendFormat: "Not Lease Holder Errors",
refId: "B"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "RPC Errors",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:83",
format: "short",
label: "errors",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:84",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 7,
w: 24,
x: 0,
y: 23
},
hiddenSeries: false,
id: 8,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(rate(txn_commits{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
intervalFactor: 1,
legendFormat: "Commited",
refId: "A"
},
{
exemplar: true,
expr: `sum(rate(txn_commits1PC{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
hide: false,
interval: "",
intervalFactor: 1,
legendFormat: "Fast-path Commited",
refId: "C"
},
{
exemplar: true,
expr: `sum(rate(txn_aborts{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
legendFormat: "Aborted",
refId: "B"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "KV Transactions",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:668",
format: "short",
label: "transactions",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:669",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 8,
w: 24,
x: 0,
y: 30
},
hiddenSeries: false,
id: 20,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(rate(txn_restarts_writetooold{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
legendFormat: "Write Too Old",
refId: "A"
},
{
exemplar: true,
expr: `sum(rate(txn_restarts_writetoooldmulti{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
hide: false,
interval: "",
legendFormat: "Write Too Old (multiple)",
refId: "B"
},
{
exemplar: true,
expr: `sum(rate(txn_restarts_serializable{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
hide: false,
interval: "",
legendFormat: "Forwarded Timestamp (iso=serializable)",
refId: "C"
},
{
exemplar: true,
expr: `sum(rate(txn_restarts_asyncwritefailure{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
hide: false,
interval: "",
legendFormat: "Async Consensus Failure",
refId: "D"
},
{
exemplar: true,
expr: `sum(rate(txn_restarts_readwithinuncertainty{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
hide: false,
interval: "",
legendFormat: "Read Within Uncertainty Interval",
refId: "E"
},
{
exemplar: true,
expr: `sum(rate(txn_restarts_txnaborted{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
hide: false,
interval: "",
legendFormat: "Aborted",
refId: "F"
},
{
exemplar: true,
expr: `sum(rate(txn_restarts_txnpush{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
hide: false,
interval: "",
legendFormat: "Push Failure",
refId: "G"
},
{
exemplar: true,
expr: `sum(rate(txn_restarts_unknown{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
hide: false,
interval: "",
legendFormat: "Unknown",
refId: "H"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "KV Transaction Restarts",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:437",
format: "short",
label: "restarts",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:438",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
description:
"The 99th percentile of transaction durations over a 1 minute period.",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 7,
w: 24,
x: 0,
y: 38
},
hiddenSeries: false,
id: 12,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `histogram_quantile(0.99,rate(txn_durations_bucket{integration_id="${integrationId}",instance=~"$node"}[1m]))`,
interval: "",
legendFormat: "{{instance}}",
refId: "B"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "KV Transactional Durations: 99th percentile",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:316",
format: "ns",
label: "transaction duration",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:317",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
description:
"The 90th percentile of transaction durations over a 1 minute period.",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 7,
w: 24,
x: 0,
y: 45
},
hiddenSeries: false,
id: 18,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `histogram_quantile(0.90,rate(txn_durations_bucket{integration_id="${integrationId}",instance=~"$node"}[1m]))`,
interval: "",
legendFormat: "{{instance}}",
refId: "A"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "KV Transaction Durations: 90th percentile",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:263",
format: "ns",
label: "transaction duration",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:264",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
description:
"The 99th percentile of latency to heartbeat a node's internal liveness record over a 1 minute period.",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 7,
w: 24,
x: 0,
y: 52
},
hiddenSeries: false,
id: 14,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 2,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `histogram_quantile(0.99,rate(liveness_heartbeatlatency_bucket{integration_id="${integrationId}",instance=~"$node"}[1m]))`,
interval: "",
intervalFactor: 2,
legendFormat: "{{instance}}",
refId: "A"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "Node Heartbeat Latency: 99th percentile ",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:210",
format: "ns",
label: "heartbeat latency",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:211",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
description:
"The 90th percentile of latency to heartbeat a node's internal liveness record over a 1 minute period.",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 7,
w: 24,
x: 0,
y: 59
},
hiddenSeries: false,
id: 16,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `histogram_quantile(0.90,rate(liveness_heartbeatlatency_bucket{integration_id="${integrationId}",instance=~"$node"}[1m]))`,
interval: "",
intervalFactor: 2,
legendFormat: "{{instance}}",
refId: "A"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "Node Heartbeat Latency: 90th percentile",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:157",
format: "ns",
label: "heartbeat latency",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:158",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
}
],
schemaVersion: 27,
style: "dark",
tags: [],
templating: {
list: [
{
allValue: "",
current: {
selected: false,
text: "All",
value: "$__all"
},
datasource: "metrics",
definition: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`,
description: null,
error: null,
hide: 0,
includeAll: true,
label: "Node",
multi: false,
name: "node",
options: [],
query: {
query: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`,
refId: "Prometheus-node-Variable-Query"
},
refresh: 1,
regex: "",
skipUrlSync: false,
sort: 1,
tagValuesQuery: "",
tags: [],
tagsQuery: "",
type: "query",
useTags: false
}
]
},
time: {
from: "now-1h",
to: "now"
},
timepicker: {},
timezone: "browser",
title: "CRDB Console: Distributed",
uid: `dis-${integrationId}`,
version: 3
};
}
export type Dashboard = ReturnType<typeof makeDashboard>; | the_stack |
import Blockly from 'blockly';
import { each, map, isEqual } from 'lodash';
import { addOperand } from './conditions';
import { debuggerContextMenu } from '../utils';
export const lba_if = ifBlock('if');
export const lba_swif = ifBlock('if (on change)');
export const lba_oneif = ifBlock('if (once)');
function ifBlock(type) {
return {
init() {
this.appendValueInput('condition')
.setCheck(['COND', 'LOGIC'])
.appendField(type);
const checks = ['SWITCH', 'LIFE'];
this.appendStatementInput('then_statements').setCheck(checks);
this.disableElseBlock();
this.setInputsInline(true);
this.setPreviousStatement(true, checks);
this.setNextStatement(true, checks);
this.setColour(180);
this.scriptType = 'life';
},
enableElseBlock() {
if (!this.getInput('else_block')) {
this.appendDummyInput('else_block')
.appendField('else');
}
if (!this.getInput('else_statements')) {
this.appendStatementInput('else_statements')
.setCheck(['SWITCH', 'LIFE']);
}
},
disableElseBlock() {
if (this.getInput('else_block')) {
this.removeInput('else_block');
}
if (this.getInput('else_statements')) {
this.removeInput('else_statements');
}
},
customContextMenu(options) {
debuggerContextMenu(this, options);
if (this.getInput('else_block')) {
options.unshift({
text: "Remove 'else' branch",
enabled: true,
callback: () => {
this.disableElseBlock();
},
});
} else {
options.unshift({
text: "Add 'else' branch",
enabled: true,
callback: () => {
this.enableElseBlock();
},
});
}
}
};
}
export const lba_switch = {
init() {
this.appendValueInput('condition')
.setCheck('COND')
.appendField('switch');
// Switch blocks can contain if statements (and, theoretically, anything else!).
const checks = ['SWITCH', 'LIFE'];
this.appendStatementInput('statements').setCheck(checks);
this.setInputsInline(true);
this.setPreviousStatement(true, 'LIFE');
this.setNextStatement(true, 'LIFE');
this.setColour(180);
this.setOnChange((event) => {
if (event instanceof Blockly.Events.Move) {
const e = event as any;
if (e.newParentId === this.id && e.newInputName === 'condition') {
const condBlock = this.getInput('condition').connection.targetBlock();
if (condBlock.getInput('operand')) {
condBlock.removeInput('operand');
}
const operandType = condBlock.data;
each(this.getCases(), (caseBlock) => {
caseBlock.setOperandType(operandType);
});
} else if (e.oldParentId === this.id && e.oldInputName === 'condition') {
const condBlock = this.workspace.getBlockById(e.blockId);
if (condBlock && !condBlock.isDisposed()) {
condBlock.addOperand();
}
each(this.getCases(), (caseBlock) => {
caseBlock.setOperandType(null);
});
}
}
});
this.scriptType = 'life';
},
getCases() {
const search = (connection) => {
const cases = [];
while (connection && connection.targetBlock()) {
const type = connection.targetBlock().type;
if (type === 'lba_case' || type === 'lba_or_case') {
cases.push(connection.targetBlock());
} else if (type === 'lba_if' || type === 'lba_swif' || type === 'lba_oneif') {
cases.push(...search(
connection.targetBlock().getInput('then_statements').connection
));
if (connection.targetBlock().getInput('else_statements')) {
cases.push(...search(
connection.targetBlock().getInput('else_statements').connection
));
}
}
connection = connection.targetBlock().nextConnection;
}
return cases;
};
return search(this.getInput('statements').connection);
},
customContextMenu(options) {
debuggerContextMenu(this, options);
}
};
const allowedOperandTypes = map(
[
'number',
'actor',
'sceneric_zone',
'ladder_zone',
'rail_zone',
'anim',
'body',
'track',
'var_value',
'angle',
'choice_value',
],
type => `operand_${type}`
);
function makeCase(orCase) {
return {
init() {
this.appendValueInput('operand')
.setCheck(allowedOperandTypes)
.appendField('case:');
if (orCase) {
this.appendDummyInput()
.appendField('or');
} else {
this.appendStatementInput('statements')
.setCheck('LIFE');
}
// We have to accept adjacent life script in order to support 'if'
// blocks around cases.
this.setInputsInline(true);
this.setPreviousStatement(true, ['SWITCH', 'LIFE']);
this.setNextStatement(true, ['SWITCH', 'LIFE']);
this.setColour(180);
this.setOnChange((event) => {
if (event instanceof Blockly.Events.Move) {
const e = event as any;
if (e.blockId === this.id && e.newParentId) {
const input = this.getInput('operand');
if (!input.connection.targetBlock()) {
let upperBlock = this.getSurroundParent();
while (upperBlock && upperBlock.type !== 'lba_switch') {
upperBlock = upperBlock.getSurroundParent();
}
if (upperBlock) {
const condBlock = upperBlock.getInput('condition')
.connection
.targetBlock();
if (condBlock) {
const operandType = condBlock.data;
this.setOperandType(operandType);
}
} else {
this.previousConnection.disconnect();
}
}
}
}
});
this.scriptType = 'life';
},
setOperandType(operandType) {
const input = this.getInput('operand');
const check = operandType
? [`operand_${operandType}`]
: allowedOperandTypes;
if (!isEqual(check, input.connection.getCheck())) {
if (operandType
&& input.connection.targetBlock()
&& !isEqual(
input.connection.targetBlock().outputConnection.getCheck(),
check
)) {
input.connection.targetBlock().dispose();
}
input.setCheck(check);
if (operandType && !input.connection.targetBlock()) {
const block = this.workspace.newBlock(`lba_operand_${operandType}`);
block.initSvg();
block.render();
input.connection.connect(block.outputConnection);
}
}
},
customContextMenu(options) {
const input = this.getInput('operand');
debuggerContextMenu(this, options);
if (!input.connection.targetBlock() && input.connection.getCheck().length === 1) {
const check = input.connection.getCheck()[0];
options.unshift({
text: 'Generate operand',
enabled: true,
callback: () => {
const block = this.workspace.newBlock(`lba_${check}`);
block.initSvg();
block.render();
input.connection.connect(block.outputConnection);
},
});
}
}
};
}
export const lba_case = makeCase(false);
export const lba_or_case = makeCase(true);
export const lba_default = {
init() {
this.appendDummyInput()
.appendField('default:');
this.appendStatementInput('statements')
.setCheck('LIFE');
this.setPreviousStatement(true, ['SWITCH', 'LIFE']);
this.setColour(180);
this.scriptType = 'life';
},
customContextMenu(options) {
debuggerContextMenu(this, options);
}
};
export const lba_break = {
init() {
this.appendDummyInput().appendField('break');
this.setPreviousStatement(true, 'LIFE');
this.setColour(180);
this.scriptType = 'life';
},
customContextMenu(options) {
debuggerContextMenu(this, options);
}
};
function makeOperand(type) {
return {
init() {
this.setInputsInline(true);
this.setOutput(true, `operand_${type}`);
this.setColour(15);
const operandInput = this.appendDummyInput('operand');
addOperand(operandInput, type);
this.scriptType = 'life';
},
customContextMenu(options) {
debuggerContextMenu(this, options);
}
};
}
export const lba_operand_number = makeOperand('number');
export const lba_operand_actor = makeOperand('actor');
export const lba_operand_sceneric_zone = makeOperand('sceneric_zone');
export const lba_operand_ladder_zone = makeOperand('ladder_zone');
export const lba_operand_rail_zone = makeOperand('rail_zone');
export const lba_operand_anim = makeOperand('anim');
export const lba_operand_body = makeOperand('body');
export const lba_operand_track = makeOperand('track');
export const lba_operand_var_value = makeOperand('var_value');
export const lba_operand_angle = makeOperand('angle');
export const lba_operand_choice_value = makeOperand('choice_value');
export const lba_and = logicOperator('and');
export const lba_or = logicOperator('or');
function logicOperator(type) {
return {
init() {
this.appendValueInput('arg_0')
.setCheck(['COND', 'LOGIC']);
this.appendValueInput('arg_1')
.appendField(type)
.setCheck(['COND', 'LOGIC']);
this.setInputsInline(false);
this.setOutput(true, 'LOGIC');
this.setColour(180);
this.scriptType = 'life';
},
customContextMenu(options) {
debuggerContextMenu(this, options);
}
};
} | the_stack |
import NoodelState from 'src/types/NoodelState';
import { getActiveChild, getFocalHeight, getFocalWidth } from './getters';
import { hideActiveSubtree, setActiveChild, setFocalParent, showActiveSubtree } from './noodel-mutate';
import { NoodelAxis } from 'src/types/NoodelAxis';
import { Axis } from 'src/types/Axis';
import { shiftFocalLevel, shiftFocalNoode, unsetLimitIndicators } from './noodel-navigate';
import { findCurrentBranchOffset, findCurrentTrunkOffset } from './noodel-animate';
export function startPan(noodel: NoodelState, realAxis: Axis) {
clearTimeout(noodel.limitIndicatorTimeout);
let currentFocalNoode = getActiveChild(noodel.focalParent);
if (!currentFocalNoode) return;
noodel.panStartFocalNoode = currentFocalNoode;
let panAxis: NoodelAxis = null;
let orientation = noodel.options.orientation;
if (orientation === 'ltr' || orientation === 'rtl') {
panAxis = realAxis === 'x' ? 'trunk' : 'branch';
}
else {
panAxis = realAxis === 'y' ? 'trunk' : 'branch';
}
noodel.panAxis = panAxis;
if (panAxis === "trunk") {
let currentTrunkOffset = findCurrentTrunkOffset(noodel);
noodel.applyTrunkMove = false;
noodel.trunkOffset = currentTrunkOffset;
noodel.panOriginTrunk = currentTrunkOffset;
}
else if (panAxis === "branch") {
let currentFocalBranchOffset = findCurrentBranchOffset(noodel, noodel.focalParent);
noodel.focalParent.applyBranchMove = false;
noodel.focalParent.branchOffset = currentFocalBranchOffset;
noodel.panOriginBranch = currentFocalBranchOffset;
}
}
/**
* Make pan movement based on the given delta, changing the focal noode/parent
* and set limit indicators as necessary. Makes no assumption on the magnitude of the movement,
* and aims to be correct regardless of the target offset, bounding the movement to the possible limits.
*/
export function updatePan(noodel: NoodelState, velocityX: number, velocityY: number, deltaX: number, deltaY: number, timestamp: number) {
if (noodel.panAxis === null) return;
let velocity = null;
let delta = null;
let orientation = noodel.options.orientation;
if (noodel.panAxis === "trunk") {
if (orientation === 'ltr') {
velocity = -velocityX;
delta = -deltaX;
}
else if (orientation === 'rtl') {
velocity = velocityX;
delta = deltaX;
}
else if (orientation === 'ttb') {
velocity = -velocityY;
delta = -deltaY;
}
else if (orientation === 'btt') {
velocity = velocityY;
delta = deltaY;
}
updateSwipeVelocityBuffer(noodel, velocity, timestamp);
let targetOffset = noodel.panOriginTrunk + (delta * noodel.options.swipeMultiplierTrunk);
let targetFocalParent = noodel.focalParent;
let trunkStartReached = false;
let trunkEndReached = false;
if (targetOffset === noodel.trunkOffset) {
return;
}
else if (targetOffset > noodel.trunkOffset) { // moving towards trunk axis end
while (targetOffset > targetFocalParent.trunkRelativeOffset + targetFocalParent.branchSize) {
let next = getActiveChild(targetFocalParent);
if (!getActiveChild(next)) break;
targetFocalParent = next;
}
if (!getActiveChild(getActiveChild(targetFocalParent))) {
let limit = targetFocalParent.trunkRelativeOffset + targetFocalParent.branchSize / 2;
if (targetOffset > limit) {
trunkEndReached = true;
targetOffset = limit;
}
}
}
else { // moving towards trunk axis start
while (targetOffset < targetFocalParent.trunkRelativeOffset) {
let prev = targetFocalParent.parent;
if (!prev) break;
targetFocalParent = prev;
}
if (!targetFocalParent.parent) { // is root
let limit = targetFocalParent.branchSize / 2;
if (targetOffset < limit) {
trunkStartReached = true;
targetOffset = limit;
}
}
}
if (targetFocalParent !== noodel.focalParent) {
setFocalParent(noodel, targetFocalParent);
}
noodel.trunkEndReached = trunkEndReached;
noodel.trunkStartReached = trunkStartReached;
noodel.trunkOffset = targetOffset;
}
else if (noodel.panAxis === "branch") {
let branchDirection = noodel.options.branchDirection;
if (orientation === 'ltr' || orientation === 'rtl') {
if (branchDirection === 'normal') {
velocity = -velocityY;
delta = -deltaY;
}
else if (branchDirection === 'reverse') {
velocity = velocityY;
delta = deltaY;
}
}
else if (orientation === 'ttb' || orientation === 'btt') {
if (branchDirection === 'normal') {
velocity = -velocityX;
delta = -deltaX;
}
else if (branchDirection === 'reverse') {
velocity = velocityX;
delta = deltaX;
}
}
updateSwipeVelocityBuffer(noodel, velocity, timestamp);
let targetOffset = noodel.panOriginBranch + (delta * noodel.options.swipeMultiplierBranch);
let focalParent = noodel.focalParent;
let targetIndex = focalParent.activeChildIndex;
let targetNoode = focalParent.children[targetIndex];
let branchStartReached = false;
let branchEndReached = false;
if (targetOffset === noodel.focalParent.branchOffset) {
return;
}
else if (targetOffset > noodel.focalParent.branchOffset) { // moving towards branch axis end
while (targetOffset > targetNoode.branchRelativeOffset + targetNoode.size) {
let nextIndex = targetIndex + 1;
if (nextIndex >= focalParent.children.length) break;
targetIndex = nextIndex;
targetNoode = focalParent.children[targetIndex];
}
if (targetIndex === focalParent.children.length - 1) {
let limit = targetNoode.branchRelativeOffset + targetNoode.size / 2;
if (targetOffset > limit) {
branchEndReached = true;
targetOffset = limit;
}
}
}
else { // moving towards branch axis start
while (targetOffset < targetNoode.branchRelativeOffset) {
let prevIndex = targetIndex - 1;
if (prevIndex < 0) break;
targetIndex = prevIndex;
targetNoode = focalParent.children[targetIndex];
}
if (targetIndex === 0) {
let limit = targetNoode.size / 2;
if (targetOffset < limit) {
branchStartReached = true;
targetOffset = limit;
}
}
}
if (targetIndex !== focalParent.activeChildIndex) {
hideActiveSubtree(getActiveChild(focalParent));
setActiveChild(noodel, focalParent, targetIndex);
showActiveSubtree(noodel, focalParent, noodel.options.visibleSubtreeDepth, noodel.options.subtreeDebounceInterval);
}
noodel.branchStartReached = branchStartReached;
noodel.branchEndReached = branchEndReached;
noodel.focalParent.branchOffset = targetOffset;
}
}
export function releasePan(noodel: NoodelState) {
if (noodel.panAxis === null) return;
if (noodel.panAxis === "trunk") {
noodel.panOriginTrunk = null;
noodel.panAxis = null; // before shiftFocalLevel to prevent extra cancelPan check
shiftFocalLevel(noodel, computeSnapCount(computeSwipeVelocity(noodel), noodel.options.snapMultiplierTrunk));
}
else if (noodel.panAxis === "branch") {
noodel.panOriginBranch = null;
noodel.panAxis = null; // before shiftFocalNoode to prevent extra cancelPan check
shiftFocalNoode(noodel, computeSnapCount(computeSwipeVelocity(noodel), noodel.options.snapMultiplierBranch));
}
unsetLimitIndicators(noodel, 0);
clearSwipeVelocityBuffer(noodel);
}
export function cancelPan(noodel: NoodelState) {
if (noodel.panAxis === null) return;
if (noodel.panAxis === "trunk") {
noodel.panOriginTrunk = null;
noodel.panAxis = null;
shiftFocalLevel(noodel, 0);
}
else if (noodel.panAxis === "branch") {
noodel.panOriginBranch = null;
noodel.panAxis = null;
shiftFocalNoode(noodel, 0);
}
unsetLimitIndicators(noodel, 0);
clearSwipeVelocityBuffer(noodel);
}
/**
* The velocity values obtained from hammerjs is highly unstable and thus need
* to be averaged out by capturing the last 10 velocities in a buffer.
*
* There is also a 60ms threshold for detecting "settle" of the swipe movement.
* If duration between two consecutive events exceed this threshold the buffer will be refreshed.
*
* Direction change of the swipe movement will not cause a buffer refresh for now
* to account for transient directional glitches in the swipe motion.
*/
function updateSwipeVelocityBuffer(noodel: NoodelState, velocity: number, timestamp: number) {
if (noodel.lastPanTimestamp === null || timestamp - noodel.lastPanTimestamp < 60) {
noodel.swipeVelocityBuffer.push(velocity);
if (noodel.swipeVelocityBuffer.length > 10) {
noodel.swipeVelocityBuffer.shift();
}
}
else {
noodel.swipeVelocityBuffer = [];
noodel.swipeVelocityBuffer.push(velocity);
}
noodel.lastPanTimestamp = timestamp;
}
/**
* Computes the average of the last 10 velocities.
*/
function computeSwipeVelocity(noodel: NoodelState) {
let sum = 0;
noodel.swipeVelocityBuffer.forEach(val => sum += val);
return sum / noodel.swipeVelocityBuffer.length;
}
function clearSwipeVelocityBuffer(noodel: NoodelState) {
noodel.lastPanTimestamp = null;
noodel.swipeVelocityBuffer = [];
}
/**
* Calculate how many noodes to snap across depending on swipe velocity.
* The current algorithm is adjusted based on velocities obtained
* from manual tests of swipe motions on mobile and desktop.
* Can be further fine-tuned if necessary.
*/
function computeSnapCount(velocity: number, snapMultiplier: number) {
let absVelocity = Math.abs(velocity) * snapMultiplier;
if (absVelocity < 0.1) {
return 0;
}
else if (absVelocity < 1) {
return (velocity > 0) ? 1 : -1;
}
else {
let count = Math.round((1.4 * Math.log(absVelocity) + 1));
return (velocity > 0) ? count : -count;
}
} | the_stack |
import { query, clear, lookup, addReducers } from "../../core/api";
import { getRandomCollection, idsEqual } from "../integration/helpers";
import { Collection } from "mongodb";
import {
oneToMany,
manyToMany,
oneToOne,
manyToOne,
} from "../../core/quickLinkers";
import { assert } from "chai";
describe("Relational Filtering", () => {
let A: Collection;
let B: Collection;
let C: Collection;
let D: Collection;
let E: Collection;
beforeAll(async () => {
A = await getRandomCollection("A");
B = await getRandomCollection("B");
C = await getRandomCollection("C");
D = await getRandomCollection("D");
E = await getRandomCollection("E");
});
// Cleans the collection and their defined links
afterEach(async () => {
await A.deleteMany({});
await B.deleteMany({});
await C.deleteMany({});
await D.deleteMany({});
await E.deleteMany({});
[A, B, C, D, E].forEach((coll) => clear(coll));
});
it("M:M:D - Simple filtering of nested collection", async () => {
// A has many B.
manyToMany(A, B, {
linkName: "bs",
inversedLinkName: "as",
});
const b1 = await B.insertOne({ name: "B1", number: 5 });
const b2 = await B.insertOne({ name: "B2", number: 10 });
const b3 = await B.insertOne({ name: "B3", number: 50 });
const a1 = await A.insertOne({
name: "A1",
bsIds: [b1.insertedId, b2.insertedId],
});
const a2 = await A.insertOne({
name: "A2",
bsIds: [b2.insertedId, b3.insertedId],
});
const a3 = await A.insertOne({
name: "A3",
bsIds: [b1.insertedId],
});
// We are looking for A's which have exactly 2 B's
const result = await query(A, {
$: {
pipeline: [
lookup(A, "bs"),
{
$match: {
bs: {
$size: 2,
},
},
},
],
},
_id: 1,
bs: {
_id: 1,
},
}).fetch();
assert.lengthOf(result, 2);
// Now I want to get all bs who have at least 2 A's
const result2 = await query(B, {
$: {
pipeline: [
lookup(B, "as"),
{
$match: {
as: {
$size: 2,
},
},
},
],
},
_id: 1,
as: {
_id: 1,
},
}).fetch();
assert.lengthOf(result2, 2);
});
it("1:1 - I want to search users who have at least X in their bank account", async () => {
// A has many B.
const Users = A;
const BankAccounts = B;
oneToOne(Users, BankAccounts, {
linkName: "bankAccount",
inversedLinkName: "user",
});
const b1 = await BankAccounts.insertOne({ name: "B1", amount: 500 });
const b2 = await BankAccounts.insertOne({ name: "B1", amount: 5 });
const u1 = await Users.insertOne({
name: "B1",
number: 5,
bankAccountId: b1.insertedId,
});
const u2 = await Users.insertOne({
name: "B1",
number: 5,
bankAccountId: b2.insertedId,
});
// We are looking for A's which have exactly 2 B's
const result = await query(Users, {
$: {
pipeline: [
lookup(Users, "bankAccount"),
{
$match: {
"bankAccount.amount": {
$gte: 500,
},
},
},
],
},
_id: 1,
bs: {
_id: 1,
},
bsCount: 1,
}).fetch();
assert.lengthOf(result, 1);
assert.equal(u1.insertedId.toString(), result[0]._id.toString());
});
it("Reducers can extend the pipeline and allow fields", async () => {
// A has many B.
const Comments = A;
const Posts = B;
manyToOne(Comments, Posts, {
linkName: "post",
inversedLinkName: "comments",
});
addReducers(Posts, {
commentsCount: {
dependency: { _id: 1 },
pipeline: [
lookup(Posts, "comments"),
{
$addFields: {
commentsCount: { $size: "$comments" },
},
},
],
},
});
const p1 = await Posts.insertOne({ name: "John Post" });
const comments = await Comments.insertMany([
{ title: "1", postId: p1.insertedId },
{ title: "1", postId: p1.insertedId },
{ title: "1", postId: p1.insertedId },
{ title: "1", postId: p1.insertedId },
{ title: "1", postId: p1.insertedId },
]);
const result = await query(Posts, {
commentsCount: 1,
}).fetchOne();
assert.isObject(result);
assert.equal(result.commentsCount, 5);
});
it("We should be able to sort by link value", async () => {
// A has many B.
const Users = A;
const BankAccounts = B;
oneToOne(Users, BankAccounts, {
linkName: "bankAccount",
inversedLinkName: "user",
});
const b1 = await BankAccounts.insertOne({ amount: 500 });
const b2 = await BankAccounts.insertOne({ amount: 5 });
const b3 = await BankAccounts.insertOne({ amount: 600 });
const b4 = await BankAccounts.insertOne({ amount: 0 });
const u1 = await Users.insertOne({ bankAccountId: b1.insertedId });
const u2 = await Users.insertOne({ bankAccountId: b2.insertedId });
const u3 = await Users.insertOne({ bankAccountId: b3.insertedId });
const u4 = await Users.insertOne({ bankAccountId: b4.insertedId });
// We are looking for A's which have exactly 2 B's
const result = await query(Users, {
$: {
pipeline: [
lookup(Users, "bankAccount"),
{
$sort: {
"bankAccount.amount": 1,
},
},
],
},
_id: 1,
}).fetch();
// Order should be: u4, u2, u1, u3
assert.isTrue(idsEqual(result[0]._id, u4.insertedId));
assert.isTrue(idsEqual(result[1]._id, u2.insertedId));
assert.isTrue(idsEqual(result[2]._id, u1.insertedId));
assert.isTrue(idsEqual(result[3]._id, u3.insertedId));
});
it("We should be able to filter by deeper links", async () => {
// Deeper checks, for example, only users belonging to companies with minimum 5 departments
const Users = A;
const Companies = B;
const Departments = C;
manyToOne(Users, Companies, {
linkName: "company",
inversedLinkName: "users",
});
manyToMany(Companies, Departments, {
linkName: "departments",
inversedLinkName: "companies",
});
const d1 = await Departments.insertOne({});
const d2 = await Departments.insertOne({});
const d3 = await Departments.insertOne({});
const d4 = await Departments.insertOne({});
const c1 = await Companies.insertOne({
departmentsIds: [d1.insertedId, d2.insertedId],
});
const c2 = await Companies.insertOne({
departmentsIds: [d1.insertedId, d3.insertedId, d4.insertedId],
});
const c3 = await Companies.insertOne({
departmentsIds: [d1.insertedId],
});
const c4 = await Companies.insertOne({
departmentsIds: null,
});
await Users.insertMany([
{ companyId: c1.insertedId },
{ companyId: c2.insertedId },
{ companyId: c3.insertedId },
{ companyId: c4.insertedId },
{ companyId: c2.insertedId },
{ companyId: c3.insertedId },
{ companyId: c4.insertedId },
{ companyId: c1.insertedId },
{ companyId: c2.insertedId },
{ companyId: c3.insertedId },
{ companyId: c4.insertedId },
{ companyId: c1.insertedId },
]);
// We are looking for A's which have exactly 2 B's
const result = await query(Users, {
$: {
pipeline: [
lookup(Users, "company", {
pipeline: [
lookup(Companies, "departments"),
{
$addFields: {
departmentsCount: { $size: "$departments" },
},
},
],
}),
{
$match: {
"company.departmentsCount": {
$gte: 2,
},
},
},
],
},
_id: 1,
companyId: 1,
}).fetch();
assert.lengthOf(result, 6);
result.forEach((user) => {
assert.isTrue(
idsEqual(user.companyId, c1.insertedId) ||
idsEqual(user.companyId, c2.insertedId)
);
});
});
// I want to fetch all users belonging to companies where they, themselves are director
it("Should be able to work with dynamic filterings", async () => {
const Users = A;
const Companies = B;
manyToOne(Users, Companies, {
linkName: "company",
inversedLinkName: "users",
});
oneToOne(Companies, Users, {
linkName: "director",
});
const c1 = await Companies.insertOne({ name: "ACME" });
const c2 = await Companies.insertOne({ name: "JOHNSON" });
const c3 = await Companies.insertOne({ name: "WAFFLE" });
const u1 = await Users.insertOne({
index: 1,
name: "D",
companyId: c1.insertedId,
});
const u2 = await Users.insertOne({
index: 2,
name: "U",
companyId: c2.insertedId,
});
const u3 = await Users.insertOne({
index: 3,
name: "D",
companyId: c2.insertedId,
});
const u4 = await Users.insertOne({
index: 4,
name: "U",
companyId: c1.insertedId,
});
Companies.updateOne(
{ _id: c1.insertedId },
{
$set: {
directorId: u1.insertedId,
},
}
);
Companies.updateOne(
{ _id: c2.insertedId },
{
$set: {
directorId: u3.insertedId,
},
}
);
const result = await query(Users, {
$: {
options: {
sort: {
index: 1,
},
},
},
_id: 1,
company: {
$(parent) {
return {
filters: {
directorId: parent._id,
},
};
},
},
}).fetch();
assert.lengthOf(result, 4);
result.forEach((user) => {
const isDirector =
idsEqual(user._id, u1.insertedId) || idsEqual(user._id, u3.insertedId);
if (isDirector) {
assert.isObject(user.company);
} else {
assert.isNull(user.company);
}
});
});
// Test the $alias thingie
it("Should allow aliasing collections", async () => {
// A has many B.
const Comments = A;
const Posts = B;
manyToOne(Comments, Posts, {
linkName: "post",
inversedLinkName: "comments",
});
const p1 = await Posts.insertOne({ name: "John Post" });
const comments = await Comments.insertMany([
{ title: "1", postId: p1.insertedId },
{ title: "2", postId: p1.insertedId },
{ title: "3", postId: p1.insertedId },
{ title: "4", postId: p1.insertedId },
{ title: "5", postId: p1.insertedId },
]);
const post = await query(Posts, {
newestComments: {
$alias: "comments",
$: {
options: {
limit: 3,
},
},
title: 1,
},
otherComments: {
$alias: "comments",
$: {
options: { limit: 2 },
},
title: 1,
},
}).fetchOne();
assert.isObject(post);
assert.lengthOf(post.newestComments, 3);
assert.lengthOf(post.otherComments, 2);
post.newestComments.forEach((comment) => {
assert.isString(comment.title);
});
post.otherComments.forEach((comment) => {
assert.isString(comment.title);
});
});
// Check pipeline on children collection links via hypernova
it("Pipeline for children should work", async () => {
// A has many B.
const Comments = A;
const Posts = B;
const Authors = C;
manyToOne(Comments, Posts, {
linkName: "post",
inversedLinkName: "comments",
});
manyToOne(Comments, Authors, {
linkName: "author",
inversedLinkName: "comments",
});
const a1 = await Authors.insertOne({ eligible: true });
const a2 = await Authors.insertOne({});
const a3 = await Authors.insertOne({});
const p1 = await Posts.insertOne({ name: "John Post" });
const comments = await Comments.insertMany([
{ title: "1", postId: p1.insertedId, authorId: a1.insertedId },
{ title: "2", postId: p1.insertedId, authorId: a2.insertedId },
{ title: "3", postId: p1.insertedId, authorId: a3.insertedId },
{ title: "4", postId: p1.insertedId, authorId: a1.insertedId },
{ title: "5", postId: p1.insertedId, authorId: a3.insertedId },
]);
const post = await query(Posts, {
comments: {
$: {
pipeline: [
lookup(Comments, "author"),
{
$match: {
"author.eligible": true,
},
},
],
},
authorId: 1,
},
}).fetchOne();
assert.isObject(post);
assert.lengthOf(post.comments, 2);
post.comments.forEach((comment) => {
assert.isTrue(idsEqual(comment.authorId, a1.insertedId));
});
});
}); | the_stack |
import {Component} from '../../component';
import {Attribute} from '../attribute';
import {provide} from '../../decorators';
import {AnyValueType, isAnyValueTypeInstance} from './any-value-type';
import {BooleanValueType, isBooleanValueTypeInstance} from './boolean-value-type';
import {NumberValueType, isNumberValueTypeInstance} from './number-value-type';
import {StringValueType, isStringValueTypeInstance} from './string-value-type';
import {ObjectValueType, isObjectValueTypeInstance} from './object-value-type';
import {DateValueType, isDateValueTypeInstance} from './date-value-type';
import {RegExpValueType, isRegExpValueTypeInstance} from './regexp-value-type';
import {ArrayValueType, isArrayValueTypeInstance} from './array-value-type';
import {ComponentValueType, isComponentValueTypeInstance} from './component-value-type';
describe('ValueType', () => {
class TestComponent extends Component {}
const attribute = new Attribute('testAttribute', TestComponent.prototype);
test('AnyValueType', async () => {
let type = new AnyValueType(attribute);
expect(isAnyValueTypeInstance(type)).toBe(true);
expect(type.toString()).toBe('any');
expect(() => type.checkValue(true, attribute)).not.toThrow();
expect(() => type.checkValue(1, attribute)).not.toThrow();
expect(() => type.checkValue('a', attribute)).not.toThrow();
expect(() => type.checkValue({}, attribute)).not.toThrow();
expect(() => type.checkValue(undefined, attribute)).not.toThrow();
// The 'isOptional' option should no effects for the 'any' type
type = new AnyValueType(attribute, {isOptional: true});
expect(type.toString()).toBe('any');
expect(() => type.checkValue(true, attribute)).not.toThrow();
expect(() => type.checkValue(1, attribute)).not.toThrow();
expect(() => type.checkValue('a', attribute)).not.toThrow();
expect(() => type.checkValue({}, attribute)).not.toThrow();
expect(() => type.checkValue(undefined, attribute)).not.toThrow();
});
test('BooleanValueType', async () => {
let type = new BooleanValueType(attribute);
expect(isBooleanValueTypeInstance(type)).toBe(true);
expect(type.toString()).toBe('boolean');
expect(() => type.checkValue(true, attribute)).not.toThrow();
expect(() => type.checkValue(false, attribute)).not.toThrow();
expect(() => type.checkValue(1, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'boolean', received type: 'number')"
);
expect(() => type.checkValue(undefined, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'boolean', received type: 'undefined')"
);
type = new BooleanValueType(attribute, {isOptional: true});
expect(type.toString()).toBe('boolean?');
expect(() => type.checkValue(true, attribute)).not.toThrow();
expect(() => type.checkValue(false, attribute)).not.toThrow();
expect(() => type.checkValue(1, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'boolean?', received type: 'number')"
);
expect(() => type.checkValue(undefined, attribute)).not.toThrow();
});
test('NumberValueType', async () => {
let type = new NumberValueType(attribute);
expect(isNumberValueTypeInstance(type)).toBe(true);
expect(type.toString()).toBe('number');
expect(() => type.checkValue(1, attribute)).not.toThrow();
expect(() => type.checkValue('a', attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'number', received type: 'string')"
);
expect(() => type.checkValue(undefined, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'number', received type: 'undefined')"
);
type = new NumberValueType(attribute, {isOptional: true});
expect(type.toString()).toBe('number?');
expect(() => type.checkValue(1, attribute)).not.toThrow();
expect(() => type.checkValue('a', attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'number?', received type: 'string')"
);
expect(() => type.checkValue(undefined, attribute)).not.toThrow();
});
test('StringValueType', async () => {
let type = new StringValueType(attribute);
expect(isStringValueTypeInstance(type)).toBe(true);
expect(type.toString()).toBe('string');
expect(() => type.checkValue('a', attribute)).not.toThrow();
expect(() => type.checkValue(1, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'string', received type: 'number')"
);
expect(() => type.checkValue(undefined, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'string', received type: 'undefined')"
);
type = new StringValueType(attribute, {isOptional: true});
expect(type.toString()).toBe('string?');
expect(() => type.checkValue('a', attribute)).not.toThrow();
expect(() => type.checkValue(1, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'string?', received type: 'number')"
);
expect(() => type.checkValue(undefined, attribute)).not.toThrow();
});
test('ObjectValueType', async () => {
let type = new ObjectValueType(attribute);
expect(isObjectValueTypeInstance(type)).toBe(true);
class Movie extends Component {}
const movie = new Movie();
expect(type.toString()).toBe('object');
expect(() => type.checkValue({}, attribute)).not.toThrow();
expect(() => type.checkValue({title: 'Inception'}, attribute)).not.toThrow();
expect(() => type.checkValue('a', attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'object', received type: 'string')"
);
expect(() => type.checkValue(movie, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'object', received type: 'Movie')"
);
expect(() => type.checkValue(undefined, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'object', received type: 'undefined')"
);
type = new ObjectValueType(attribute, {isOptional: true});
expect(type.toString()).toBe('object?');
expect(() => type.checkValue({}, attribute)).not.toThrow();
expect(() => type.checkValue({title: 'Inception'}, attribute)).not.toThrow();
expect(() => type.checkValue(movie, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'object?', received type: 'Movie')"
);
expect(() => type.checkValue('a', attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'object?', received type: 'string')"
);
expect(() => type.checkValue(undefined, attribute)).not.toThrow();
});
test('DateValueType', async () => {
let type = new DateValueType(attribute);
expect(isDateValueTypeInstance(type)).toBe(true);
expect(type.toString()).toBe('Date');
expect(() => type.checkValue(new Date(), attribute)).not.toThrow();
expect(() => type.checkValue('a', attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'Date', received type: 'string')"
);
expect(() => type.checkValue(undefined, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'Date', received type: 'undefined')"
);
type = new DateValueType(attribute, {isOptional: true});
expect(type.toString()).toBe('Date?');
expect(() => type.checkValue(new Date(), attribute)).not.toThrow();
expect(() => type.checkValue('a', attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'Date?', received type: 'string')"
);
expect(() => type.checkValue(undefined, attribute)).not.toThrow();
});
test('RegExpValueType', async () => {
let type = new RegExpValueType(attribute);
expect(isRegExpValueTypeInstance(type)).toBe(true);
expect(type.toString()).toBe('RegExp');
expect(() => type.checkValue(/abc/, attribute)).not.toThrow();
expect(() => type.checkValue('a', attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'RegExp', received type: 'string')"
);
expect(() => type.checkValue(undefined, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'RegExp', received type: 'undefined')"
);
type = new RegExpValueType(attribute, {isOptional: true});
expect(type.toString()).toBe('RegExp?');
expect(() => type.checkValue(/abc/, attribute)).not.toThrow();
expect(() => type.checkValue('a', attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'RegExp?', received type: 'string')"
);
expect(() => type.checkValue(undefined, attribute)).not.toThrow();
});
test('ArrayValueType', async () => {
let itemType = new NumberValueType(attribute);
let type = new ArrayValueType(itemType, attribute);
expect(isArrayValueTypeInstance(type)).toBe(true);
expect(type.toString()).toBe('number[]');
expect(() => type.checkValue([], attribute)).not.toThrow();
expect(() => type.checkValue([1], attribute)).not.toThrow();
// @ts-expect-error
expect(() => type.checkValue(1, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'number[]', received type: 'number')"
);
expect(() => type.checkValue(['a'], attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'number', received type: 'string')"
);
// @ts-expect-error
expect(() => type.checkValue(undefined, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'number[]', received type: 'undefined')"
);
expect(() => type.checkValue([undefined], attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'number', received type: 'undefined')"
);
expect(() => type.checkValue([1, undefined], attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'number', received type: 'undefined')"
);
expect(() => type.checkValue([undefined, 1], attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'number', received type: 'undefined')"
);
itemType = new NumberValueType(attribute, {isOptional: true});
type = new ArrayValueType(itemType, attribute, {isOptional: true});
expect(type.toString()).toBe('number?[]?');
expect(() => type.checkValue([], attribute)).not.toThrow();
expect(() => type.checkValue([1], attribute)).not.toThrow();
// @ts-expect-error
expect(() => type.checkValue(1, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'number?[]?', received type: 'number')"
);
expect(() => type.checkValue(['a'], attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'TestComponent.prototype.testAttribute', expected type: 'number?', received type: 'string')"
);
// @ts-expect-error
expect(() => type.checkValue(undefined, attribute)).not.toThrow();
expect(() => type.checkValue([undefined], attribute)).not.toThrow();
expect(() => type.checkValue([1, undefined], attribute)).not.toThrow();
expect(() => type.checkValue([undefined, 1], attribute)).not.toThrow();
});
test('ComponentValueType', async () => {
class Movie extends Component {}
class Actor extends Component {}
class App extends Component {
@provide() static Movie = Movie;
@provide() static Actor = Actor;
}
const attribute = new Attribute('testAttribute', App);
const movie = new Movie();
const actor = new Actor();
// Component class value types
let type = new ComponentValueType('typeof Movie', attribute);
expect(isComponentValueTypeInstance(type)).toBe(true);
expect(type.toString()).toBe('typeof Movie');
expect(() => type.checkValue(Movie, attribute)).not.toThrow();
expect(() => type.checkValue(Actor, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'typeof Movie', received type: 'typeof Actor')"
);
expect(() => type.checkValue(movie, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'typeof Movie', received type: 'Movie')"
);
expect(() => type.checkValue({}, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'typeof Movie', received type: 'object')"
);
expect(() => type.checkValue(undefined, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'typeof Movie', received type: 'undefined')"
);
type = new ComponentValueType('typeof Movie', attribute, {isOptional: true});
expect(type.toString()).toBe('typeof Movie?');
expect(() => type.checkValue(Movie, attribute)).not.toThrow();
expect(() => type.checkValue(Actor, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'typeof Movie?', received type: 'typeof Actor')"
);
expect(() => type.checkValue(movie, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'typeof Movie?', received type: 'Movie')"
);
expect(() => type.checkValue({}, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'typeof Movie?', received type: 'object')"
);
expect(() => type.checkValue(undefined, attribute)).not.toThrow();
// Component instance value types
type = new ComponentValueType('Movie', attribute);
expect(isComponentValueTypeInstance(type)).toBe(true);
expect(type.toString()).toBe('Movie');
expect(() => type.checkValue(movie, attribute)).not.toThrow();
expect(() => type.checkValue(actor, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'Movie', received type: 'Actor')"
);
expect(() => type.checkValue(Movie, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'Movie', received type: 'typeof Movie')"
);
expect(() => type.checkValue({}, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'Movie', received type: 'object')"
);
expect(() => type.checkValue(undefined, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'Movie', received type: 'undefined')"
);
type = new ComponentValueType('Movie', attribute, {isOptional: true});
expect(type.toString()).toBe('Movie?');
expect(() => type.checkValue(movie, attribute)).not.toThrow();
expect(() => type.checkValue(actor, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'Movie?', received type: 'Actor')"
);
expect(() => type.checkValue(Movie, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'Movie?', received type: 'typeof Movie')"
);
expect(() => type.checkValue({}, attribute)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'App.testAttribute', expected type: 'Movie?', received type: 'object')"
);
expect(() => type.checkValue(undefined, attribute)).not.toThrow();
});
}); | the_stack |
export interface ModifyDDoSPolicyCaseRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 策略场景ID
*/
SceneId: string;
/**
* 开发平台,取值[PC(PC客户端), MOBILE(移动端), TV(电视端), SERVER(主机)]
*/
PlatformTypes?: Array<string>;
/**
* 细分品类,取值[WEB(网站), GAME(游戏), APP(应用), OTHER(其他)]
*/
AppType?: string;
/**
* 应用协议,取值[tcp(TCP协议),udp(UDP协议),icmp(ICMP协议),all(其他协议)]
*/
AppProtocols?: Array<string>;
/**
* TCP业务起始端口,取值(0, 65535]
*/
TcpSportStart?: string;
/**
* TCP业务结束端口,取值(0, 65535],必须大于等于TCP业务起始端口
*/
TcpSportEnd?: string;
/**
* UDP业务起始端口,取值范围(0, 65535]
*/
UdpSportStart?: string;
/**
* UDP业务结束端口,取值范围(0, 65535),必须大于等于UDP业务起始端口
*/
UdpSportEnd?: string;
/**
* 是否有海外客户,取值[no(没有), yes(有)]
*/
HasAbroad?: string;
/**
* 是否会主动对外发起TCP请求,取值[no(不会), yes(会)]
*/
HasInitiateTcp?: string;
/**
* 是否会主动对外发起UDP业务请求,取值[no(不会), yes(会)]
*/
HasInitiateUdp?: string;
/**
* 主动发起TCP请求的端口,取值范围(0, 65535]
*/
PeerTcpPort?: string;
/**
* 主动发起UDP请求的端口,取值范围(0, 65535]
*/
PeerUdpPort?: string;
/**
* TCP载荷的固定特征码,字符串长度小于512
*/
TcpFootprint?: string;
/**
* UDP载荷的固定特征码,字符串长度小于512
*/
UdpFootprint?: string;
/**
* Web业务的API的URL
*/
WebApiUrl?: Array<string>;
/**
* TCP业务报文长度最小值,取值范围(0, 1500)
*/
MinTcpPackageLen?: string;
/**
* TCP业务报文长度最大值,取值范围(0, 1500),必须大于等于TCP业务报文长度最小值
*/
MaxTcpPackageLen?: string;
/**
* UDP业务报文长度最小值,取值范围(0, 1500)
*/
MinUdpPackageLen?: string;
/**
* UDP业务报文长度最大值,取值范围(0, 1500),必须大于等于UDP业务报文长度最小值
*/
MaxUdpPackageLen?: string;
/**
* 是否有VPN业务,取值[no(没有), yes(有)]
*/
HasVPN?: string;
/**
* TCP业务端口列表,同时支持单个端口和端口段,字符串格式,例如:80,443,700-800,53,1000-3000
*/
TcpPortList?: string;
/**
* UDP业务端口列表,同时支持单个端口和端口段,字符串格式,例如:80,443,700-800,53,1000-3000
*/
UdpPortList?: string;
}
/**
* DescribeIpUnBlockList请求参数结构体
*/
export interface DescribeIpUnBlockListRequest {
/**
* 开始时间
*/
BeginTime: string;
/**
* 结束时间
*/
EndTime: string;
/**
* IP(不为空时,进行IP过滤)
*/
Ip?: string;
/**
* 分页参数(不为空时,进行分页查询),此字段后面会弃用,请用Limit和Offset字段代替;
*/
Paging?: Paging;
/**
* 一页条数,填0表示不分页
*/
Limit?: number;
/**
* 页起始偏移,取值为(页码-1)*一页条数
*/
Offset?: number;
}
/**
* DeleteDDoSPolicyCase请求参数结构体
*/
export interface DeleteDDoSPolicyCaseRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 策略场景ID
*/
SceneId: string;
}
/**
* CreateDDoSPolicy返回参数结构体
*/
export interface CreateDDoSPolicyResponse {
/**
* 策略ID
*/
PolicyId?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteL7Rules请求参数结构体
*/
export interface DeleteL7RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则ID列表
*/
RuleIdList: Array<string>;
}
/**
* CreateBoundIP请求参数结构体
*/
export interface CreateBoundIPRequest {
/**
* 大禹子产品代号(bgp表示独享包;bgp-multip表示共享包)
*/
Business: string;
/**
* 资源实例ID
*/
Id: string;
/**
* 绑定到资源实例的IP数组,当资源实例为高防包(独享包)时,数组只允许填1个IP;当没有要绑定的IP时可以为空数组;但是BoundDevList和UnBoundDevList至少有一个不为空;
*/
BoundDevList?: Array<BoundIpInfo>;
/**
* 与资源实例解绑的IP数组,当资源实例为高防包(独享包)时,数组只允许填1个IP;当没有要解绑的IP时可以为空数组;但是BoundDevList和UnBoundDevList至少有一个不为空;
*/
UnBoundDevList?: Array<BoundIpInfo>;
/**
* 已弃用,不填
*/
CopyPolicy?: string;
}
/**
* DescribeNewL4RulesErrHealth返回参数结构体
*/
export interface DescribeNewL4RulesErrHealthResponse {
/**
* 异常规则的总数
*/
Total?: number;
/**
* 异常规则列表,返回值说明: Key值为规则ID,Value值为异常IP,多个IP用","分割
*/
ErrHealths?: Array<KeyValue>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCCEvList请求参数结构体
*/
export interface DescribeCCEvListRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版;basic表示DDoS基础防护)
*/
Business: string;
/**
* 开始时间
*/
StartTime: string;
/**
* 结束时间
*/
EndTime: string;
/**
* 资源实例ID
*/
Id?: string;
/**
* 资源实例的IP,当business不为basic时,如果IpList不为空则Id也必须不能为空;
*/
IpList?: Array<string>;
/**
* 一页条数,填0表示不分页
*/
Limit?: number;
/**
* 页起始偏移,取值为(页码-1)*一页条数
*/
Offset?: number;
}
/**
* DescribeTransmitStatis返回参数结构体
*/
export interface DescribeTransmitStatisResponse {
/**
* 当MetricName=traffic时,表示入流量带宽,单位bps;
当MetricName=pkg时,表示入包速率,单位pps;
*/
InDataList?: Array<number>;
/**
* 当MetricName=traffic时,表示出流量带宽,单位bps;
当MetricName=pkg时,表示出包速率,单位pps;
*/
OutDataList?: Array<number>;
/**
* 指标名:
traffic表示流量带宽;
pkg表示包速率;
*/
MetricName?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DDoS高级策略
*/
export interface DDosPolicy {
/**
* 策略绑定的资源
*/
Resources: Array<ResourceIp>;
/**
* 禁用协议
*/
DropOptions: DDoSPolicyDropOption;
/**
* 禁用端口
*/
PortLimits: Array<DDoSPolicyPortLimit>;
/**
* 报文过滤
*/
PacketFilters: Array<DDoSPolicyPacketFilter>;
/**
* 黑白IP名单
*/
IpBlackWhiteLists: Array<IpBlackWhite>;
/**
* 策略ID
*/
PolicyId: string;
/**
* 策略名称
*/
PolicyName: string;
/**
* 策略创建时间
*/
CreateTime: string;
/**
* 水印策略参数,最多只有一个,当没有水印策略时数组为空
*/
WaterPrint: Array<WaterPrintPolicy>;
/**
* 水印密钥,最多只有2个,当没有水印策略时数组为空
*/
WaterKey: Array<WaterPrintKey>;
/**
* 策略绑定的资源实例
注意:此字段可能返回 null,表示取不到有效值。
*/
BoundResources: Array<string>;
/**
* 策略所属的策略场景
注意:此字段可能返回 null,表示取不到有效值。
*/
SceneId: string;
}
/**
* Protocol、Port参数
*/
export interface ProtocolPort {
/**
* 协议(tcp;udp)
*/
Protocol: string;
/**
* 端口
*/
Port: number;
}
/**
* DescribeDDoSNetTrend请求参数结构体
*/
export interface DescribeDDoSNetTrendRequest {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 指标,取值[bps(攻击流量带宽,pps(攻击包速率))]
*/
MetricName: string;
/**
* 统计粒度,取值[300(5分钟),3600(小时),86400(天)]
*/
Period: number;
/**
* 统计开始时间
*/
StartTime: string;
/**
* 统计结束时间
*/
EndTime: string;
}
/**
* DescribePolicyCase请求参数结构体
*/
export interface DescribePolicyCaseRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 策略场景ID
*/
SceneId?: string;
}
/**
* DescribeUnBlockStatis请求参数结构体
*/
export declare type DescribeUnBlockStatisRequest = null;
/**
* ModifyCCUrlAllow返回参数结构体
*/
export interface ModifyCCUrlAllowResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeBasicDeviceThreshold返回参数结构体
*/
export interface DescribeBasicDeviceThresholdResponse {
/**
* 返回黑洞封堵值
*/
Threshold?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCCAlarmThreshold返回参数结构体
*/
export interface DescribeCCAlarmThresholdResponse {
/**
* CC告警阈值
*/
CCAlarmThreshold?: CCAlarmThreshold;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSNetEvList请求参数结构体
*/
export interface DescribeDDoSNetEvListRequest {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 开始时间
*/
StartTime: string;
/**
* 结束时间
*/
EndTime: string;
/**
* 一页条数,填0表示不分页
*/
Limit?: number;
/**
* 页起始偏移,取值为(页码-1)*一页条数
*/
Offset?: number;
}
/**
* DeleteNewL4Rules请求参数结构体
*/
export interface DeleteNewL4RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 删除接口结构体
*/
Rule: Array<L4DelRule>;
}
/**
* ModifyNewDomainRules请求参数结构体
*/
export interface ModifyNewDomainRulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 域名转发规则
*/
Rule: NewL7RuleEntry;
}
/**
* DDoS告警阈值
*/
export interface DDoSAlarmThreshold {
/**
* 告警阈值类型,1-入流量,2-清洗流量
*/
AlarmType: number;
/**
* 告警阈值,大于0(目前排定的值)
*/
AlarmThreshold: number;
}
/**
* DescribePolicyCase返回参数结构体
*/
export interface DescribePolicyCaseResponse {
/**
* 策略场景列表
*/
CaseList?: Array<KeyValueRecord>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeResIpList请求参数结构体
*/
export interface DescribeResIpListRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID, 如果不填,则获取用户所有资源的IP
*/
IdList?: Array<string>;
}
/**
* DescribeNewL4RulesErrHealth请求参数结构体
*/
export interface DescribeNewL4RulesErrHealthRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 规则ID列表
*/
RuleIdList?: Array<string>;
}
/**
* ModifyCCLevel请求参数结构体
*/
export interface ModifyCCLevelRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* CC防护等级,取值[default(正常), loose(宽松), strict(严格)];
*/
Level: string;
/**
* 可选字段,代表CC防护类型,取值[http(HTTP协议的CC防护),https(HTTPS协议的CC防护)];当不填时,默认为HTTP协议的CC防护;当填写https时还需要填写RuleId字段;
*/
Protocol: string;
/**
* 表示7层转发规则ID(通过获取7层转发规则接口可以获取规则ID);
*/
RuleId: string;
}
/**
* DeleteCCSelfDefinePolicy请求参数结构体
*/
export interface DeleteCCSelfDefinePolicyRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 策略ID
*/
SetId: string;
}
/**
* DescribeCCUrlAllow请求参数结构体
*/
export interface DescribeCCUrlAllowRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 黑或白名单,取值[white(白名单)],目前只支持白名单
注意:此数组只能有一个值,且只能为white
*/
Type: Array<string>;
/**
* 分页参数
*/
Limit?: number;
/**
* 分页参数
*/
Offset?: number;
/**
* 可选,代表HTTP协议或HTTPS协议的CC防护,取值[http(HTTP协议的CC防护),https(HTTPS协议的CC防护)];
*/
Protocol?: string;
}
/**
* 字段值,K-V形式
*/
export interface KeyValue {
/**
* 字段名称
*/
Key: string;
/**
* 字段取值
*/
Value: string;
}
/**
* 黑白IP
*/
export interface IpBlackWhite {
/**
* IP地址
*/
Ip: string;
/**
* 黑白类型,取值范围[black,white]
*/
Type: string;
}
/**
* ModifyDDoSAlarmThreshold请求参数结构体
*/
export interface ModifyDDoSAlarmThresholdRequest {
/**
* 大禹子产品代号(shield表示棋牌;bgpip表示高防IP;bgp表示高防包;bgp-multip表示多ip高防包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID,字符串类型
*/
RsId: string;
/**
* 告警阈值类型,0-未设置,1-入流量,2-清洗流量
*/
AlarmType: number;
/**
* 告警阈值,大于0(目前暂定的值)
*/
AlarmThreshold: number;
/**
* 资源关联的IP列表,高防包未绑定时,传空数组,高防IP专业版传多个IP的数据
*/
IpList: Array<string>;
}
/**
* DescribeNewL4Rules请求参数结构体
*/
export interface DescribeNewL4RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 指定IP查询
*/
Ip?: string;
/**
* 指定高防IP端口查询
*/
VirtualPort?: number;
/**
* 一页条数,填0表示不分页
*/
Limit?: number;
/**
* 页起始偏移,取值为(页码-1)*一页条数
*/
Offset?: number;
}
/**
* CreateDDoSPolicy请求参数结构体
*/
export interface CreateDDoSPolicyRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 协议禁用,必须填写且数组长度必须为1
*/
DropOptions: Array<DDoSPolicyDropOption>;
/**
* 策略名称
*/
Name?: string;
/**
* 端口禁用,当没有禁用端口时填空数组
*/
PortLimits?: Array<DDoSPolicyPortLimit>;
/**
* 请求源IP黑白名单,当没有IP黑白名单时填空数组
*/
IpAllowDenys?: Array<IpBlackWhite>;
/**
* 报文过滤,当没有报文过滤时填空数组
*/
PacketFilters?: Array<DDoSPolicyPacketFilter>;
/**
* 水印策略参数,当没有启用水印功能时填空数组,最多只能传一条水印策略(即数组大小不超过1)
*/
WaterPrint?: Array<WaterPrintPolicy>;
}
/**
* ModifyCCThreshold返回参数结构体
*/
export interface ModifyCCThresholdResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyNetReturnSwitch返回参数结构体
*/
export interface ModifyNetReturnSwitchResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeActionLog请求参数结构体
*/
export interface DescribeActionLogRequest {
/**
* 开始时间
*/
StartTime: string;
/**
* 结束时间
*/
EndTime: string;
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business?: string;
/**
* 搜索值,只支持资源ID或用户UIN
*/
Filter?: string;
/**
* 一页条数,填0表示不分页
*/
Limit?: number;
/**
* 页起始偏移,取值为(页码-1)*一页条数
*/
Offset?: number;
}
/**
* CreateL7RuleCert请求参数结构体
*/
export interface CreateL7RuleCertRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源实例ID,例如高防IP实例的ID,高防IP专业版实例的ID
*/
Id: string;
/**
* 规则ID
*/
RuleId: string;
/**
* 证书类型,当为协议为HTTPS协议时必须填,取值[2(腾讯云托管证书)]
*/
CertType: number;
/**
* 当证书来源为腾讯云托管证书时,此字段必须填写托管证书ID
*/
SSLId?: string;
/**
* 当证书来源为自有证书时,此字段必须填写证书内容;(因已不再支持自有证书,此字段已弃用,请不用填写此字段)
*/
Cert?: string;
/**
* 当证书来源为自有证书时,此字段必须填写证书密钥;(因已不再支持自有证书,此字段已弃用,请不用填写此字段)
*/
PrivateKey?: string;
}
/**
* DescribeBGPIPL7RuleMaxCnt返回参数结构体
*/
export interface DescribeBGPIPL7RuleMaxCntResponse {
/**
* 高防IP最多可添加的7层规则数量
*/
Count?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribePcap返回参数结构体
*/
export interface DescribePcapResponse {
/**
* pcap包的下载链接列表,无pcap包时为空数组;
*/
PcapUrlList?: Array<string>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribePackIndex返回参数结构体
*/
export interface DescribePackIndexResponse {
/**
* 字段值,如下:
TotalPackCount:资源数
AttackPackCount:清洗中的资源数
BlockPackCount:封堵中的资源数
ExpiredPackCount:过期的资源数
ExpireingPackCount:即将过期的资源数
IsolatePackCount:隔离中的资源数
*/
Data?: Array<KeyValue>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSAttackSource请求参数结构体
*/
export interface DescribeDDoSAttackSourceRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 起始时间
*/
StartTime: string;
/**
* 结束时间
*/
EndTime: string;
/**
* 一页条数,填0表示不分页
*/
Limit: number;
/**
* 页起始偏移,取值为(页码-1)*一页条数
*/
Offset: number;
/**
* 获取指定资源的特定ip的攻击源,可选
*/
IpList?: Array<string>;
}
/**
* DescribeDDoSCount请求参数结构体
*/
export interface DescribeDDoSCountRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 资源的IP
*/
Ip: string;
/**
* 统计开始时间
*/
StartTime: string;
/**
* 统计结束时间
*/
EndTime: string;
/**
* 指标,取值[traffic(攻击协议流量, 单位KB), pkg(攻击协议报文数), classnum(攻击事件次数)]
*/
MetricName: string;
}
/**
* 地域资源实例数
*/
export interface RegionInstanceCount {
/**
* 地域码
*/
Region: string;
/**
* 地域码(新规范)
*/
RegionV3: string;
/**
* 资源实例数
*/
Count: number;
}
/**
* 水印Key
*/
export interface WaterPrintKey {
/**
* 水印KeyID
*/
KeyId: string;
/**
* 水印Key值
*/
KeyContent: string;
/**
* 水印Key的版本号
*/
KeyVersion: string;
/**
* 是否开启,取值[0(没有开启),1(已开启)]
*/
OpenStatus: number;
/**
* 密钥生成时间
*/
CreateTime: string;
}
/**
* CreateNewL7Rules返回参数结构体
*/
export interface CreateNewL7RulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyNewL4Rule返回参数结构体
*/
export interface ModifyNewL4RuleResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyNewDomainRules返回参数结构体
*/
export interface ModifyNewDomainRulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateNewL4Rules返回参数结构体
*/
export interface CreateNewL4RulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSUsedStatis返回参数结构体
*/
export interface DescribeDDoSUsedStatisResponse {
/**
* 字段值,如下:
Days:高防资源使用天数
Attacks:DDoS防护次数
*/
Data?: Array<KeyValue>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeBasicCCThreshold请求参数结构体
*/
export interface DescribeBasicCCThresholdRequest {
/**
* 查询的IP地址,取值如:1.1.1.1
*/
BasicIp: string;
/**
* 查询IP所属地域,取值如:gz、bj、sh、hk等地域缩写
*/
BasicRegion: string;
/**
* 专区类型,取值如:公有云专区:public,黑石专区:bm, NAT服务器专区:nat,互联网通道:channel。
*/
BasicBizType: string;
/**
* 设备类型,取值如:服务器:cvm,公有云负载均衡:clb,黑石负载均衡:lb,NAT服务器:nat,互联网通道:channel.
*/
BasicDeviceType: string;
/**
* 可选,IPInstance Nat 网关(如果查询的设备类型是NAT服务器,需要传此参数,通过nat资源查询接口获取)
*/
BasicIpInstance?: string;
/**
* 可选,运营商线路(如果查询的设备类型是NAT服务器,需要传此参数为5)
*/
BasicIspCode?: number;
}
/**
* CreateDDoSPolicyCase返回参数结构体
*/
export interface CreateDDoSPolicyCaseResponse {
/**
* 策略场景ID
*/
SceneId?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeIPProductInfo返回参数结构体
*/
export interface DescribeIPProductInfoResponse {
/**
* 云产品信息列表,如果没有查询到则返回空数组,值说明如下:
Key为ProductName时,value表示云产品实例的名称;
Key为ProductInstanceId时,value表示云产品实例的ID;
Key为ProductType时,value表示的是云产品的类型(cvm表示云主机、clb表示负载均衡);
Key为IP时,value表示云产品实例的IP;
*/
Data?: Array<KeyValueRecord>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyDDoSSwitch返回参数结构体
*/
export interface ModifyDDoSSwitchResponse {
/**
* 当前防护状态值,取值[0(关闭),1(开启)]
*/
Status?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* IP封堵记录
*/
export interface IpBlockData {
/**
* IP
*/
Ip: string;
/**
* 状态(Blocked:被封堵;UnBlocking:解封中;UnBlockFailed:解封失败)
*/
Status: string;
/**
* 封堵时间
*/
BlockTime: string;
/**
* 解封时间(预计解封时间)
*/
UnBlockTime: string;
/**
* 解封类型(user:自助解封;auto:自动解封; update:升级解封;bind:绑定高防包解封)
*/
ActionType: string;
}
/**
* DescribeCCSelfDefinePolicy请求参数结构体
*/
export interface DescribeCCSelfDefinePolicyRequest {
/**
* 大禹子产品代号(bgp高防包;bgp-multip共享包)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 拉取的条数
*/
Limit?: number;
/**
* 偏移量
*/
Offset?: number;
}
/**
* ModifyDDoSDefendStatus请求参数结构体
*/
export interface ModifyDDoSDefendStatusRequest {
/**
* 大禹子产品代号(bgp表示独享包;bgp-multip表示共享包;bgpip表示高防IP;net表示高防IP专业版;basic表示基础防护)
*/
Business: string;
/**
* 防护状态值,取值[0(关闭),1(开启)]
*/
Status: number;
/**
* 关闭时长,单位小时,取值[0,1,2,3,4,5,6];当Status=0表示关闭时,Hour必须大于0;
*/
Hour: number;
/**
* 资源ID;当Business不是基础防护时必须填写此字段;
*/
Id?: string;
/**
* 基础防护的IP,只有当Business为基础防护时才需要填写此字段;
*/
Ip?: string;
/**
* 只有当Business为基础防护时才需要填写此字段,IP所属的产品类型,取值[public(CVM产品),bm(黑石产品),eni(弹性网卡),vpngw(VPN网关), natgw(NAT网关),waf(Web应用安全产品),fpc(金融产品),gaap(GAAP产品), other(托管IP)]
*/
BizType?: string;
/**
* 只有当Business为基础防护时才需要填写此字段,IP所属的产品子类,取值[cvm(CVM),lb(负载均衡器),eni(弹性网卡),vpngw(VPN),natgw(NAT),waf(WAF),fpc(金融),gaap(GAAP),other(托管IP),eip(黑石弹性IP)]
*/
DeviceType?: string;
/**
* 只有当Business为基础防护时才需要填写此字段,IP所属的资源实例ID,当绑定新IP时必须填写此字段;例如是弹性网卡的IP,则InstanceId填写弹性网卡的ID(eni-*);
*/
InstanceId?: string;
/**
* 只有当Business为基础防护时才需要填写此字段,表示IP所属的地域,取值:
"bj": 华北地区(北京)
"cd": 西南地区(成都)
"cq": 西南地区(重庆)
"gz": 华南地区(广州)
"gzopen": 华南地区(广州Open)
"hk": 中国香港
"kr": 东南亚地区(首尔)
"sh": 华东地区(上海)
"shjr": 华东地区(上海金融)
"szjr": 华南地区(深圳金融)
"sg": 东南亚地区(新加坡)
"th": 东南亚地区(泰国)
"de": 欧洲地区(德国)
"usw": 美国西部(硅谷)
"ca": 北美地区(多伦多)
"jp": 日本
"hzec": 杭州
"in": 印度
"use": 美东地区(弗吉尼亚)
"ru": 俄罗斯
"tpe": 中国台湾
"nj": 南京
*/
IPRegion?: string;
}
/**
* DescribeRuleSets返回参数结构体
*/
export interface DescribeRuleSetsResponse {
/**
* 规则记录数数组,取值说明:
Key值为"Id"时,Value表示资源ID
Key值为"RuleIdList"时,Value值表示资源的规则ID,多个规则ID用","分割
Key值为"RuleNameList"时,Value值表示资源的规则名,多个规则名用","分割
Key值为"RuleNum"时,Value值表示资源的规则数
*/
L4RuleSets?: Array<KeyValueRecord>;
/**
* 规则记录数数组,取值说明:
Key值为"Id"时,Value表示资源ID
Key值为"RuleIdList"时,Value值表示资源的规则ID,多个规则ID用","分割
Key值为"RuleNameList"时,Value值表示资源的规则名,多个规则名用","分割
Key值为"RuleNum"时,Value值表示资源的规则数
*/
L7RuleSets?: Array<KeyValueRecord>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeBaradData返回参数结构体
*/
export interface DescribeBaradDataResponse {
/**
* 返回指标的值
*/
DataList?: Array<BaradData>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSEvInfo请求参数结构体
*/
export interface DescribeDDoSEvInfoRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 资源的IP
*/
Ip: string;
/**
* 攻击开始时间
*/
StartTime: string;
/**
* 攻击结束时间
*/
EndTime: string;
}
/**
* DescribeDDoSAttackIPRegionMap返回参数结构体
*/
export interface DescribeDDoSAttackIPRegionMapResponse {
/**
* 全球地域分布数据
*/
NationCount?: Array<KeyValueRecord>;
/**
* 国内省份地域分布数据
*/
ProvinceCount?: Array<KeyValueRecord>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyL4KeepTime返回参数结构体
*/
export interface ModifyL4KeepTimeResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyL7Rules返回参数结构体
*/
export interface ModifyL7RulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeL7HealthConfig请求参数结构体
*/
export interface DescribeL7HealthConfigRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则ID数组,当导出所有规则的健康检查配置则不填或填空数组;
*/
RuleIdList?: Array<string>;
}
/**
* 高防包绑定IP对象
*/
export interface BoundIpInfo {
/**
* IP地址
*/
Ip: string;
/**
* 绑定的产品分类,取值[public(CVM、CLB产品),bm(黑石产品),eni(弹性网卡),vpngw(VPN网关), natgw(NAT网关),waf(Web应用安全产品),fpc(金融产品),gaap(GAAP产品), other(托管IP)]
*/
BizType?: string;
/**
* 产品分类下的子类型,取值[cvm(CVM),lb(负载均衡器),eni(弹性网卡),vpngw(VPN),natgw(NAT),waf(WAF),fpc(金融),gaap(GAAP),other(托管IP),eip(黑石弹性IP)]
*/
DeviceType?: string;
/**
* IP所属的资源实例ID,当绑定新IP时必须填写此字段;例如是弹性网卡的IP,则InstanceId填写弹性网卡的ID(eni-*); 如果绑定的是托管IP没有对应的资源实例ID,请填写"none";
*/
InstanceId?: string;
/**
* 运营商,0:电信;1:联通;2:移动;5:BGP
*/
IspCode?: number;
}
/**
* DescribePcap请求参数结构体
*/
export interface DescribePcapRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源实例ID
*/
Id: string;
/**
* 攻击事件的开始时间,格式为"2018-08-28 07:00:00"
*/
StartTime: string;
/**
* 攻击事件的结束时间,格式为"2018-08-28 07:02:00"
*/
EndTime: string;
/**
* 资源的IP,只有当Business为net时才需要填写资源实例下的IP;
*/
Ip?: string;
}
/**
* DescribeDDoSAlarmThreshold返回参数结构体
*/
export interface DescribeDDoSAlarmThresholdResponse {
/**
* DDoS告警阈值
*/
DDoSAlarmThreshold?: DDoSAlarmThreshold;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* KeyValue记录
*/
export interface KeyValueRecord {
/**
* 一条记录的Key-Value数组
*/
Record: Array<KeyValue>;
}
/**
* DescribeBasicDeviceThreshold请求参数结构体
*/
export interface DescribeBasicDeviceThresholdRequest {
/**
* 查询的IP地址,取值如:1.1.1.1
*/
BasicIp: string;
/**
* 查询IP所属地域,取值如:gz、bj、sh、hk等地域缩写
*/
BasicRegion: string;
/**
* 专区类型,取值如:公有云专区:public,黑石专区:bm, NAT服务器专区:nat,互联网通道:channel。
*/
BasicBizType: string;
/**
* 设备类型,取值如:服务器:cvm,公有云负载均衡:clb,黑石负载均衡:lb,NAT服务器:nat,互联网通道:channel.
*/
BasicDeviceType: string;
/**
* 有效性检查,取值为1
*/
BasicCheckFlag: number;
/**
* 可选,IPInstance Nat 网关(如果查询的设备类型是NAT服务器,需要传此参数,通过nat资源查询接口获取)
*/
BasicIpInstance?: string;
/**
* 可选,运营商线路(如果查询的设备类型是NAT服务器,需要传此参数为5)
*/
BasicIspCode?: number;
}
/**
* ModifyDDoSWaterKey返回参数结构体
*/
export interface ModifyDDoSWaterKeyResponse {
/**
* 水印密钥列表
*/
KeyList?: Array<WaterPrintKey>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribleNewL7Rules返回参数结构体
*/
export interface DescribleNewL7RulesResponse {
/**
* 转发规则列表
*/
Rules?: Array<NewL7RuleEntry>;
/**
* 总规则数
*/
Total?: number;
/**
* 健康检查配置列表
*/
Healths?: Array<L7RuleHealth>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyResBindDDoSPolicy返回参数结构体
*/
export interface ModifyResBindDDoSPolicyResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyDDoSWaterKey请求参数结构体
*/
export interface ModifyDDoSWaterKeyRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 策略ID
*/
PolicyId: string;
/**
* 密钥操作,取值:[add(添加),delete(删除),open(开启),close(关闭),get(获取密钥)]
*/
Method: string;
/**
* 密钥ID,当添加密钥操作时可以不填或填0,其他操作时必须填写;
*/
KeyId?: number;
}
/**
* ModifyCCLevel返回参数结构体
*/
export interface ModifyCCLevelResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeBaradData请求参数结构体
*/
export interface DescribeBaradDataRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源实例ID
*/
Id: string;
/**
* 指标名,取值:
connum表示TCP活跃连接数;
new_conn表示新建TCP连接数;
inactive_conn表示非活跃连接数;
intraffic表示入流量;
outtraffic表示出流量;
alltraffic表示出流量和入流量之和;
inpkg表示入包速率;
outpkg表示出包速率;
*/
MetricName: string;
/**
* 统计时间粒度,单位秒(300表示5分钟;3600表示小时;86400表示天)
*/
Period: number;
/**
* 统计开始时间,秒部分保持为0,分钟部分为5的倍数
*/
StartTime: string;
/**
* 统计结束时间,秒部分保持为0,分钟部分为5的倍数
*/
EndTime: string;
/**
* 统计方式,取值:
max表示最大值;
min表示最小值;
avg表示均值;
*/
Statistics: string;
/**
* 协议端口数组
*/
ProtocolPort?: Array<ProtocolPort>;
/**
* 资源实例下的IP,只有当Business=net(高防IP专业版)时才必须填写资源的一个IP(因为高防IP专业版资源实例有多个IP,才需要指定);
*/
Ip?: string;
}
/**
* DescribeDDoSDefendStatus返回参数结构体
*/
export interface DescribeDDoSDefendStatusResponse {
/**
* 防护状态,为0表示防护处于关闭状态,为1表示防护处于开启状态
注意:此字段可能返回 null,表示取不到有效值。
*/
DefendStatus?: number;
/**
* 防护临时关闭的过期时间,当防护状态为开启时此字段为空;
注意:此字段可能返回 null,表示取不到有效值。
*/
UndefendExpire?: string;
/**
* 控制台功能展示字段,为1表示控制台功能展示,为0表示控制台功能隐藏
注意:此字段可能返回 null,表示取不到有效值。
*/
ShowFlag?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeBizHttpStatus请求参数结构体
*/
export interface DescribeBizHttpStatusRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 资源Id
*/
Id: string;
/**
* 统计周期,可取值300,1800,3600, 21600,86400,单位秒
*/
Period: number;
/**
* 统计开始时间
*/
StartTime: string;
/**
* 统计结束时间
*/
EndTime: string;
/**
* 统计方式,仅支持sum
*/
Statistics: string;
/**
* 协议及端口列表,协议可取值TCP, UDP, HTTP, HTTPS,仅统计纬度为连接数时有效
*/
ProtoInfo?: Array<ProtocolPort>;
/**
* 特定域名查询
*/
Domain?: string;
}
/**
* cc自定义规则
*/
export interface CCPolicy {
/**
* 策略名称
*/
Name: string;
/**
* 匹配模式,取值[matching(匹配模式), speedlimit(限速模式)]
*/
Smode: string;
/**
* 策略id
*/
SetId?: string;
/**
* 每分钟限制的次数
*/
Frequency?: number;
/**
* 执行策略模式,拦截或者验证码,取值[alg(验证码), drop(拦截)]
*/
ExeMode?: string;
/**
* 生效开关
*/
Switch?: number;
/**
* 创建时间
*/
CreateTime?: string;
/**
* 规则列表
*/
RuleList?: Array<CCRule>;
/**
* IP列表,如果不填时,请传空数组但不能为null;
*/
IpList?: Array<string>;
/**
* cc防护类型,取值[http,https]
*/
Protocol?: string;
/**
* 可选字段,表示HTTPS的CC防护域名对应的转发规则ID;
*/
RuleId?: string;
/**
* HTTPS的CC防护域名
*/
Domain?: string;
}
/**
* ModifyDDoSAIStatus返回参数结构体
*/
export interface ModifyDDoSAIStatusResponse {
/**
* AI防护状态,取值[on,off]
*/
DDoSAI?: string;
/**
* 资源ID
*/
Id?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSNetEvInfo请求参数结构体
*/
export interface DescribeDDoSNetEvInfoRequest {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 攻击开始时间
*/
StartTime: string;
/**
* 攻击结束时间
*/
EndTime: string;
}
/**
* ModifyResourceRenewFlag请求参数结构体
*/
export interface ModifyResourceRenewFlagRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版;shield表示棋牌盾;bgp表示独享包;bgp-multip表示共享包;insurance表示保险包;staticpack表示三网套餐包)
*/
Business: string;
/**
* 资源Id
*/
Id: string;
/**
* 自动续费标记(0手动续费;1自动续费;2到期不续费)
*/
RenewFlag: number;
}
/**
* DescribeCCEvList返回参数结构体
*/
export interface DescribeCCEvListResponse {
/**
* 大禹子产品代号(shield表示棋牌盾;bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版;basic表示DDoS基础防护)
*/
Business?: string;
/**
* 资源实例ID
*/
Id?: string;
/**
* 资源实例的IP列表
注意:此字段可能返回 null,表示取不到有效值。
*/
IpList?: Array<string>;
/**
* 开始时间
*/
StartTime?: string;
/**
* 结束时间
*/
EndTime?: string;
/**
* CC攻击事件列表
*/
Data?: Array<CCEventRecord>;
/**
* 总记录数
*/
Total?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCCFrequencyRules请求参数结构体
*/
export interface DescribeCCFrequencyRulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 7层转发规则ID(通过获取7层转发规则接口可以获取规则ID);当填写时表示获取转发规则的访问频率控制规则;
*/
RuleId: string;
}
/**
* CreateL4HealthConfig请求参数结构体
*/
export interface CreateL4HealthConfigRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 四层健康检查配置数组
*/
HealthConfig: Array<L4HealthConfig>;
}
/**
* DescribeBGPIPL7RuleMaxCnt请求参数结构体
*/
export interface DescribeBGPIPL7RuleMaxCntRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 资源实例ID
*/
Id: string;
}
/**
* ModifyDDoSPolicyName返回参数结构体
*/
export interface ModifyDDoSPolicyNameResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCCAlarmThreshold请求参数结构体
*/
export interface DescribeCCAlarmThresholdRequest {
/**
* 大禹子产品代号(shield表示棋牌;bgpip表示高防IP;bgp表示高防包;bgp-multip表示多ip高防包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID,字符串类型
*/
RsId: string;
}
/**
* ModifyCCUrlAllow请求参数结构体
*/
export interface ModifyCCUrlAllowRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* =add表示添加,=delete表示删除
*/
Method: string;
/**
* 黑/白名单类型;取值[white(白名单)]
*/
Type: string;
/**
* URL数组,URL格式如下:
http://域名/cgi
https://域名/cgi
*/
UrlList: Array<string>;
/**
* 可选字段,代表CC防护类型,取值[http(HTTP协议的CC防护),https(HTTPS协议的CC防护)];当不填时,默认为HTTP协议的CC防护;当填写https时还需要填写Domain和RuleId字段;
*/
Protocol?: string;
/**
* 可选字段,表示HTTPS协议的7层转发规则域名(通过获取7层转发规则接口可以获取域名),只有当Protocol字段为https时才必须填写此字段;
*/
Domain?: string;
/**
* 可选字段,表示HTTPS协议的7层转发规则ID(通过获取7层转发规则接口可以获取规则ID),当添加并且Protocol=https时必须填写;
当Method为delete时,可以不用填写此字段;
*/
RuleId?: string;
}
/**
* ModifyDDoSAlarmThreshold返回参数结构体
*/
export interface ModifyDDoSAlarmThresholdResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyDDoSLevel返回参数结构体
*/
export interface ModifyDDoSLevelResponse {
/**
* 资源ID
*/
Id?: string;
/**
* 防护等级,取值[low,middle,high]
*/
DDoSLevel?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeIpBlockList返回参数结构体
*/
export interface DescribeIpBlockListResponse {
/**
* IP封堵列表
*/
List?: Array<IpBlockData>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCCIpAllowDeny返回参数结构体
*/
export interface DescribeCCIpAllowDenyResponse {
/**
* 该字段被RecordList字段替代了,请不要使用
*/
Data?: Array<KeyValue>;
/**
* 记录数
*/
Total?: number;
/**
* 返回黑/白名单的记录,
"Key":"ip"时,"Value":值表示ip;
"Key":"domain"时, "Value":值表示域名;
"Key":"type"时,"Value":值表示黑白名单类型(white为白名单,block为黑名单);
"Key":"protocol"时,"Value":值表示CC防护的协议(http或https);
*/
RecordList?: Array<KeyValueRecord>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSIpLog返回参数结构体
*/
export interface DescribeDDoSIpLogResponse {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business?: string;
/**
* 资源ID
*/
Id?: string;
/**
* 资源的IP
*/
Ip?: string;
/**
* 攻击开始时间
*/
StartTime?: string;
/**
* 攻击结束时间
*/
EndTime?: string;
/**
* IP攻击日志,KeyValue数组,Key-Value取值说明:
Key为"LogTime"时,Value值为IP日志时间
Key为"LogMessage"时,Value值为Ip日志内容
*/
Data?: Array<KeyValueRecord>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* cc自定义策略配置的规则
*/
export interface CCRule {
/**
* 规则的key, 可以为host、cgi、ua、referer
*/
Skey: string;
/**
* 规则的条件,可以为include、not_include、equal
*/
Operator: string;
/**
* 规则的值,长度小于31字节
*/
Value: string;
}
/**
* DescribeResIpList返回参数结构体
*/
export interface DescribeResIpListResponse {
/**
* 资源的IP列表
*/
Resource?: Array<ResourceIp>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyCCIpAllowDeny请求参数结构体
*/
export interface ModifyCCIpAllowDenyRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* add表示添加,delete表示删除
*/
Method: string;
/**
* 黑/白名单类型;取值[white(白名单),black(黑名单)]
*/
Type: string;
/**
* 黑/白名单的IP数组
*/
IpList: Array<string>;
/**
* 可选字段,代表CC防护类型,取值[http(HTTP协议的CC防护),https(HTTPS协议的CC防护)];当不填时,默认为HTTP协议的CC防护;当填写https时还需要填写Domain和RuleId字段;
*/
Protocol?: string;
/**
* 可选字段,表示HTTPS协议的7层转发规则域名(通过获取7层转发规则接口可以获取域名),只有当Protocol字段为https时才必须填写此字段;
*/
Domain?: string;
/**
* 可选字段,表示HTTPS协议的7层转发规则ID(通过获取7层转发规则接口可以获取规则ID),
当Method为delete时,不用填写此字段;
*/
RuleId?: string;
}
/**
* CreateInstanceName返回参数结构体
*/
export interface CreateInstanceNameResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSDefendStatus请求参数结构体
*/
export interface DescribeDDoSDefendStatusRequest {
/**
* 大禹子产品代号(basic表示基础防护;bgp表示独享包;bgp-multip表示共享包;bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源实例ID,只有当Business不是基础防护时才需要填写此字段;
*/
Id?: string;
/**
* 基础防护的IP,只有当Business为基础防护时才需要填写此字段;
*/
Ip?: string;
/**
* 只有当Business为基础防护时才需要填写此字段,IP所属的产品类型,取值[public(CVM产品),bm(黑石产品),eni(弹性网卡),vpngw(VPN网关), natgw(NAT网关),waf(Web应用安全产品),fpc(金融产品),gaap(GAAP产品), other(托管IP)]
*/
BizType?: string;
/**
* 只有当Business为基础防护时才需要填写此字段,IP所属的产品子类,取值[cvm(CVM),lb(负载均衡器),eni(弹性网卡),vpngw(VPN),natgw(NAT),waf(WAF),fpc(金融),gaap(GAAP),other(托管IP),eip(黑石弹性IP)]
*/
DeviceType?: string;
/**
* 只有当Business为基础防护时才需要填写此字段,IP所属的资源实例ID,当绑定新IP时必须填写此字段;例如是弹性网卡的IP,则InstanceId填写弹性网卡的ID(eni-*);
*/
InstanceId?: string;
/**
* 只有当Business为基础防护时才需要填写此字段,表示IP所属的地域,取值:
"bj": 华北地区(北京)
"cd": 西南地区(成都)
"cq": 西南地区(重庆)
"gz": 华南地区(广州)
"gzopen": 华南地区(广州Open)
"hk": 中国香港
"kr": 东南亚地区(首尔)
"sh": 华东地区(上海)
"shjr": 华东地区(上海金融)
"szjr": 华南地区(深圳金融)
"sg": 东南亚地区(新加坡)
"th": 东南亚地区(泰国)
"de": 欧洲地区(德国)
"usw": 美国西部(硅谷)
"ca": 北美地区(多伦多)
"jp": 日本
"hzec": 杭州
"in": 印度
"use": 美东地区(弗吉尼亚)
"ru": 俄罗斯
"tpe": 中国台湾
"nj": 南京
*/
IPRegion?: string;
}
/**
* 业务流量的http状态码聚合数据
*/
export interface HttpStatusMap {
/**
* http2xx状态码
*/
Http2xx: Array<number>;
/**
* http3xx状态码
*/
Http3xx: Array<number>;
/**
* http404状态码
*/
Http404: Array<number>;
/**
* http4xx状态码
*/
Http4xx: Array<number>;
/**
* http5xx状态码
*/
Http5xx: Array<number>;
/**
* http2xx回源状态码
*/
SourceHttp2xx: Array<number>;
/**
* http3xx回源状态码
*/
SourceHttp3xx: Array<number>;
/**
* http404回源状态码
*/
SourceHttp404: Array<number>;
/**
* http4xx回源状态码
*/
SourceHttp4xx: Array<number>;
/**
* http5xx回源状态码
*/
SourceHttp5xx: Array<number>;
}
/**
* ModifyL4Health请求参数结构体
*/
export interface ModifyL4HealthRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 健康检查参数数组
*/
Healths: Array<L4RuleHealth>;
}
/**
* ModifyCCHostProtection返回参数结构体
*/
export interface ModifyCCHostProtectionResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateL4Rules返回参数结构体
*/
export interface CreateL4RulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeInsurePacks请求参数结构体
*/
export interface DescribeInsurePacksRequest {
/**
* 可选字段,保险包套餐ID,当要获取指定ID(例如insure-000000xe)的保险包套餐时请填写此字段;
*/
IdList?: Array<string>;
}
/**
* DescribeDDoSNetCount请求参数结构体
*/
export interface DescribeDDoSNetCountRequest {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 统计开始时间
*/
StartTime: string;
/**
* 统计结束时间
*/
EndTime: string;
/**
* 指标,取值[traffic(攻击协议流量, 单位KB), pkg(攻击协议报文数), classnum(攻击事件次数)]
*/
MetricName: string;
}
/**
* 分页索引
*/
export interface Paging {
/**
* 起始位置
*/
Offset: number;
/**
* 数量
*/
Limit: number;
}
/**
* ModifyCCSelfDefinePolicy请求参数结构体
*/
export interface ModifyCCSelfDefinePolicyRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 策略ID
*/
SetId: string;
/**
* CC策略描述
*/
Policy: CCPolicy;
}
/**
* 四层健康检查配置
*/
export interface L4HealthConfig {
/**
* 转发协议,取值[TCP, UDP]
*/
Protocol: string;
/**
* 转发端口
*/
VirtualPort: number;
/**
* =1表示开启;=0表示关闭
*/
Enable: number;
/**
* 响应超时时间,单位秒
*/
TimeOut: number;
/**
* 检测间隔时间,单位秒
*/
Interval: number;
/**
* 不健康阈值,单位次
*/
KickNum: number;
/**
* 健康阈值,单位次
*/
AliveNum: number;
/**
* 会话保持时间,单位秒
*/
KeepTime: number;
}
/**
* CreateCCSelfDefinePolicy请求参数结构体
*/
export interface CreateCCSelfDefinePolicyRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* CC策略描述
*/
Policy: CCPolicy;
}
/**
* 操作返回码,只用于返回成功的情况
*/
export interface SuccessCode {
/**
* 成功/错误码
*/
Code: string;
/**
* 描述
*/
Message: string;
}
/**
* DescribleL4Rules请求参数结构体
*/
export interface DescribleL4RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则ID,可选参数,填写后获取指定的规则
*/
RuleIdList?: Array<string>;
/**
* 一页条数,填0表示不分页
*/
Limit?: number;
/**
* 页起始偏移,取值为(页码-1)*一页条数
*/
Offset?: number;
}
/**
* L4规则
*/
export interface L4RuleEntry {
/**
* 转发协议,取值[TCP, UDP]
*/
Protocol: string;
/**
* 转发端口
*/
VirtualPort: number;
/**
* 源站端口
*/
SourcePort: number;
/**
* 回源方式,取值[1(域名回源),2(IP回源)]
*/
SourceType: number;
/**
* 会话保持时间,单位秒
*/
KeepTime: number;
/**
* 回源列表
*/
SourceList: Array<L4RuleSource>;
/**
* 负载均衡方式,取值[1(加权轮询),2(源IP hash)]
*/
LbType: number;
/**
* 会话保持开关,取值[0(会话保持关闭),1(会话保持开启)];
*/
KeepEnable: number;
/**
* 规则ID
*/
RuleId?: string;
/**
* 规则描述
*/
RuleName?: string;
/**
* 移除水印状态,取值[0(关闭),1(开启)]
*/
RemoveSwitch?: number;
}
/**
* DescribeL4HealthConfig请求参数结构体
*/
export interface DescribeL4HealthConfigRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则ID数组,当导出所有规则的健康检查配置则不填或填空数组;
*/
RuleIdList?: Array<string>;
}
/**
* CreateL7CCRule返回参数结构体
*/
export interface CreateL7CCRuleResponse {
/**
* 7层CC自定义规则参数,当没有开启CC自定义规则时,返回空数组
*/
RuleConfig?: Array<CCRuleConfig>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyCCFrequencyRulesStatus返回参数结构体
*/
export interface ModifyCCFrequencyRulesStatusResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyNetReturnSwitch请求参数结构体
*/
export interface ModifyNetReturnSwitchRequest {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business: string;
/**
* 资源实例ID
*/
Id: string;
/**
* Status 表示回切开关,0: 关闭, 1:打开
*/
Status: number;
/**
* 回切时长,单位:小时,取值[0,1,2,3,4,5,6;]当status=1时必选填写Hour>0
*/
Hour: number;
}
/**
* CreateL7CCRule请求参数结构体
*/
export interface CreateL7CCRuleRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 操作码,取值[query(表示查询),add(表示添加),del(表示删除)]
*/
Method: string;
/**
* 7层转发规则ID,例如:rule-0000001
*/
RuleId: string;
/**
* 7层CC自定义规则参数,当操作码为query时,可以不用填写;当操作码为add或del时,必须填写,且数组长度只能为1;
*/
RuleConfig?: Array<CCRuleConfig>;
}
/**
* CreateL7Rules请求参数结构体
*/
export interface CreateL7RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则列表
*/
Rules: Array<L7RuleEntry>;
}
/**
* DescribeBizHttpStatus返回参数结构体
*/
export interface DescribeBizHttpStatusResponse {
/**
* 业务流量http状态码统计数据
*/
HttpStatusMap: HttpStatusMap;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeNewL7RulesErrHealth返回参数结构体
*/
export interface DescribeNewL7RulesErrHealthResponse {
/**
* 异常规则的总数
*/
Total?: number;
/**
* 异常规则列表,返回值说明: Key值为规则ID,Value值为异常IP及错误信息,多个IP用","分割
*/
ErrHealths?: Array<KeyValue>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSNetEvList返回参数结构体
*/
export interface DescribeDDoSNetEvListResponse {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business?: string;
/**
* 资源ID
*/
Id?: string;
/**
* 开始时间
*/
StartTime?: string;
/**
* 结束时间
*/
EndTime?: string;
/**
* DDoS攻击事件列表
*/
Data?: Array<DDoSEventRecord>;
/**
* 总记录数
*/
Total?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateL4Rules请求参数结构体
*/
export interface CreateL4RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则列表
*/
Rules: Array<L4RuleEntry>;
}
/**
* ModifyNewL4Rule请求参数结构体
*/
export interface ModifyNewL4RuleRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 转发规则
*/
Rule: L4RuleEntry;
}
/**
* DescribeL4RulesErrHealth请求参数结构体
*/
export interface DescribeL4RulesErrHealthRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
}
/**
* L4规则回源列表
*/
export interface L4RuleSource {
/**
* 回源IP或域名
*/
Source: string;
/**
* 权重值,取值[0,100]
*/
Weight: number;
}
/**
* CreateBasicDDoSAlarmThreshold返回参数结构体
*/
export interface CreateBasicDDoSAlarmThresholdResponse {
/**
* 当存在告警阈值配置时,返回告警阈值大于0,当不存在告警配置时,返回告警阈值为0;
*/
AlarmThreshold?: number;
/**
* 告警阈值类型,1-入流量,2-清洗流量;当AlarmThreshold大于0时有效;
*/
AlarmType?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateNetReturn返回参数结构体
*/
export interface CreateNetReturnResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteL4Rules请求参数结构体
*/
export interface DeleteL4RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则ID列表
*/
RuleIdList: Array<string>;
}
/**
* DescribeResourceList请求参数结构体
*/
export interface DescribeResourceListRequest {
/**
* 大禹子产品代号(bgp表示独享包;bgp-multip表示共享包;bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 地域码搜索,可选,当不指定地域时空数组,当指定地域时,填地域码。例如:["gz", "sh"]
*/
RegionList?: Array<string>;
/**
* 线路搜索,可选,只有当获取高防IP资源列表是可以选填,取值为[1(BGP线路),2(南京电信),3(南京联通),99(第三方合作线路)],当获取其他产品时请填空数组;
*/
Line?: Array<number>;
/**
* 资源ID搜索,可选,当不为空数组时表示获取指定资源的资源列表;
*/
IdList?: Array<string>;
/**
* 资源名称搜索,可选,当不为空字符串时表示按名称搜索资源;
*/
Name?: string;
/**
* IP搜索列表,可选,当不为空时表示按照IP搜索资源;
*/
IpList?: Array<string>;
/**
* 资源状态搜索列表,可选,取值为[0(运行中), 1(清洗中), 2(封堵中)],当填空数组时不进行状态搜索;
*/
Status?: Array<number>;
/**
* 即将到期搜索;可选,取值为[0(不搜索),1(搜索即将到期的资源)]
*/
Expire?: number;
/**
* 排序字段,可选
*/
OderBy?: Array<OrderBy>;
/**
* 一页条数,填0表示不分页
*/
Limit?: number;
/**
* 页起始偏移,取值为(页码-1)*一页条数
*/
Offset?: number;
/**
* 高防IP专业版资源的CNAME,可选,只对高防IP专业版资源列表有效;
*/
CName?: string;
/**
* 高防IP专业版资源的域名,可选,只对高防IP专业版资源列表有效;
*/
Domain?: string;
}
/**
* DeleteL4Rules返回参数结构体
*/
export interface DeleteL4RulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribleNewL7Rules请求参数结构体
*/
export interface DescribleNewL7RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 一页条数,填0表示不分页
*/
Limit?: number;
/**
* 页起始偏移,取值为(页码-1)*一页条数
*/
Offset?: number;
/**
* 域名搜索,选填,当需要搜索域名请填写
*/
Domain?: string;
/**
* 转发协议搜索,选填,取值[http, https, http/https]
*/
ProtocolList?: Array<string>;
/**
* 状态搜索,选填,取值[0(规则配置成功),1(规则配置生效中),2(规则配置失败),3(规则删除生效中),5(规则删除失败),6(规则等待配置),7(规则等待删除),8(规则待配置证书)]
*/
StatusList?: Array<number>;
/**
* IP搜索,选填,当需要搜索IP请填写
*/
Ip?: string;
}
/**
* DescribeIPProductInfo请求参数结构体
*/
export interface DescribeIPProductInfoRequest {
/**
* 大禹子产品代号(bgp表示独享包;bgp-multip表示共享包)
*/
Business: string;
/**
* IP列表
*/
IpList: Array<string>;
}
/**
* CreateL7HealthConfig请求参数结构体
*/
export interface CreateL7HealthConfigRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 七层健康检查配置数组
*/
HealthConfig: Array<L7HealthConfig>;
}
/**
* CreateL7RuleCert返回参数结构体
*/
export interface CreateL7RuleCertResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSAttackIPRegionMap请求参数结构体
*/
export interface DescribeDDoSAttackIPRegionMapRequest {
/**
* 大禹子产品代号(shield表示棋牌;bgpip表示高防IP;bgp表示高防包;bgp-multip表示多ip高防包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 统计开始时间
*/
StartTime: string;
/**
* 统计结束时间,最大可统计的时间范围是半年;
*/
EndTime: string;
/**
* 指定资源的特定IP的攻击源,可选
*/
IpList?: Array<string>;
}
/**
* ModifyDDoSPolicy请求参数结构体
*/
export interface ModifyDDoSPolicyRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 策略ID
*/
PolicyId: string;
/**
* 协议禁用,必须填写且数组长度必须为1
*/
DropOptions: Array<DDoSPolicyDropOption>;
/**
* 端口禁用,当没有禁用端口时填空数组
*/
PortLimits?: Array<DDoSPolicyPortLimit>;
/**
* IP黑白名单,当没有IP黑白名单时填空数组
*/
IpAllowDenys?: Array<IpBlackWhite>;
/**
* 报文过滤,当没有报文过滤时填空数组
*/
PacketFilters?: Array<DDoSPolicyPacketFilter>;
/**
* 水印策略参数,当没有启用水印功能时填空数组,最多只能传一条水印策略(即数组大小不超过1)
*/
WaterPrint?: Array<WaterPrintPolicy>;
}
/**
* DescribeSourceIpSegment请求参数结构体
*/
export interface DescribeSourceIpSegmentRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
}
/**
* DescribeSourceIpSegment返回参数结构体
*/
export interface DescribeSourceIpSegmentResponse {
/**
* 回源IP段,多个用";"分隔
*/
Data?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyResBindDDoSPolicy请求参数结构体
*/
export interface ModifyResBindDDoSPolicyRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 策略ID
*/
PolicyId: string;
/**
* 绑定或解绑,bind表示绑定策略,unbind表示解绑策略
*/
Method: string;
}
/**
* L7规则健康检查参数
*/
export interface L7RuleHealth {
/**
* 规则ID
*/
RuleId: string;
/**
* =1表示开启;=0表示关闭
*/
Enable: number;
/**
* 检测间隔时间,单位秒
*/
Interval: number;
/**
* 不健康阈值,单位次
*/
KickNum: number;
/**
* 健康阈值,单位次
*/
AliveNum: number;
/**
* HTTP请求方式,取值[HEAD,GET]
*/
Method: string;
/**
* 健康检查判定正常状态码,1xx =1, 2xx=2, 3xx=4, 4xx=8,5xx=16,多个状态码值加和
*/
StatusCode: number;
/**
* 检查目录的URL,默认为/
*/
Url: string;
/**
* 配置状态,0: 正常,1:配置中,2:配置失败
*/
Status: number;
}
/**
* CreateL7RulesUpload请求参数结构体
*/
export interface CreateL7RulesUploadRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则列表
*/
Rules: Array<L7RuleEntry>;
}
/**
* 规则健康检查参数
*/
export interface L4RuleHealth {
/**
* 规则ID
*/
RuleId: string;
/**
* =1表示开启;=0表示关闭
*/
Enable: number;
/**
* 响应超时时间,单位秒
*/
TimeOut: number;
/**
* 检测间隔时间,单位秒,必须要大于响应超时时间
*/
Interval: number;
/**
* 不健康阈值,单位次
*/
KickNum: number;
/**
* 健康阈值,单位次
*/
AliveNum: number;
}
/**
* ModifyCCFrequencyRules请求参数结构体
*/
export interface ModifyCCFrequencyRulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* CC的访问频率控制规则ID
*/
CCFrequencyRuleId: string;
/**
* 匹配规则,取值["include"(前缀匹配),"equal"(完全匹配)]
*/
Mode: string;
/**
* 统计周期,单位秒,取值[10, 30, 60]
*/
Period: number;
/**
* 访问次数,取值[1-10000]
*/
ReqNumber: number;
/**
* 执行动作,取值["alg"(人机识别), "drop"(拦截)]
*/
Act: string;
/**
* 执行时间,单位秒,取值[1-900]
*/
ExeDuration: number;
/**
* URI字符串,必须以/开头,例如/abc/a.php,长度不超过31;当URI=/时,匹配模式只能选择前缀匹配;
*/
Uri?: string;
/**
* User-Agent字符串,长度不超过80
*/
UserAgent?: string;
/**
* Cookie字符串,长度不超过40
*/
Cookie?: string;
}
/**
* ModifyCCPolicySwitch返回参数结构体
*/
export interface ModifyCCPolicySwitchResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyDDoSThreshold返回参数结构体
*/
export interface ModifyDDoSThresholdResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateDDoSPolicyCase请求参数结构体
*/
export interface CreateDDoSPolicyCaseRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 策略场景名,字符串长度小于64
*/
CaseName: string;
/**
* 开发平台,取值[PC(PC客户端), MOBILE(移动端), TV(电视端), SERVER(主机)]
*/
PlatformTypes?: Array<string>;
/**
* 细分品类,取值[WEB(网站), GAME(游戏), APP(应用), OTHER(其他)]
*/
AppType?: string;
/**
* 应用协议,取值[tcp(TCP协议),udp(UDP协议),icmp(ICMP协议),all(其他协议)]
*/
AppProtocols?: Array<string>;
/**
* TCP业务起始端口,取值(0, 65535]
*/
TcpSportStart?: string;
/**
* TCP业务结束端口,取值(0, 65535],必须大于等于TCP业务起始端口
*/
TcpSportEnd?: string;
/**
* UDP业务起始端口,取值范围(0, 65535]
*/
UdpSportStart?: string;
/**
* UDP业务结束端口,取值范围(0, 65535),必须大于等于UDP业务起始端口
*/
UdpSportEnd?: string;
/**
* 是否有海外客户,取值[no(没有), yes(有)]
*/
HasAbroad?: string;
/**
* 是否会主动对外发起TCP请求,取值[no(不会), yes(会)]
*/
HasInitiateTcp?: string;
/**
* 是否会主动对外发起UDP业务请求,取值[no(不会), yes(会)]
*/
HasInitiateUdp?: string;
/**
* 主动发起TCP请求的端口,取值范围(0, 65535]
*/
PeerTcpPort?: string;
/**
* 主动发起UDP请求的端口,取值范围(0, 65535]
*/
PeerUdpPort?: string;
/**
* TCP载荷的固定特征码,字符串长度小于512
*/
TcpFootprint?: string;
/**
* UDP载荷的固定特征码,字符串长度小于512
*/
UdpFootprint?: string;
/**
* Web业务的API的URL
*/
WebApiUrl?: Array<string>;
/**
* TCP业务报文长度最小值,取值范围(0, 1500)
*/
MinTcpPackageLen?: string;
/**
* TCP业务报文长度最大值,取值范围(0, 1500),必须大于等于TCP业务报文长度最小值
*/
MaxTcpPackageLen?: string;
/**
* UDP业务报文长度最小值,取值范围(0, 1500)
*/
MinUdpPackageLen?: string;
/**
* UDP业务报文长度最大值,取值范围(0, 1500),必须大于等于UDP业务报文长度最小值
*/
MaxUdpPackageLen?: string;
/**
* 是否有VPN业务,取值[no(没有), yes(有)]
*/
HasVPN?: string;
/**
* TCP业务端口列表,同时支持单个端口和端口段,字符串格式,例如:80,443,700-800,53,1000-3000
*/
TcpPortList?: string;
/**
* UDP业务端口列表,同时支持单个端口和端口段,字符串格式,例如:80,443,700-800,53,1000-3000
*/
UdpPortList?: string;
}
/**
* ModifyCCIpAllowDeny返回参数结构体
*/
export interface ModifyCCIpAllowDenyResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyCCAlarmThreshold请求参数结构体
*/
export interface ModifyCCAlarmThresholdRequest {
/**
* 大禹子产品代号(shield表示棋牌;bgpip表示高防IP;bgp表示高防包;bgp-multip表示多ip高防包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID,字符串类型
*/
RsId: string;
/**
* 告警阈值,大于0(目前排定的值),后台设置默认值为1000
*/
AlarmThreshold: number;
/**
* 资源关联的IP列表,高防包未绑定时,传空数组,高防IP专业版传多个IP的数据
*/
IpList: Array<string>;
}
/**
* DescribeCCFrequencyRules返回参数结构体
*/
export interface DescribeCCFrequencyRulesResponse {
/**
* 访问频率控制规则列表
*/
CCFrequencyRuleList?: Array<CCFrequencyRule>;
/**
* 访问频率控制规则开关状态,取值[on(开启),off(关闭)]
*/
CCFrequencyRuleStatus?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeBizTrend返回参数结构体
*/
export interface DescribeBizTrendResponse {
/**
* 曲线图各个时间点的值
*/
DataList?: Array<number>;
/**
* 统计纬度
*/
MetricName?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSEvList请求参数结构体
*/
export interface DescribeDDoSEvListRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版;basic表示DDoS基础防护)
*/
Business: string;
/**
* 开始时间
*/
StartTime: string;
/**
* 结束时间
*/
EndTime: string;
/**
* 资源实例ID,当Business为basic时,此字段不用填写(因为基础防护没有资源实例)
*/
Id?: string;
/**
* 资源的IP
*/
IpList?: Array<string>;
/**
* 是否超过弹性防护峰值,取值[yes(是),no(否)],填写空字符串时表示不进行过滤
*/
OverLoad?: string;
/**
* 一页条数,填0表示不分页
*/
Limit?: number;
/**
* 页起始偏移,取值为(页码-1)*一页条数
*/
Offset?: number;
}
/**
* DescribeBasicCCThreshold返回参数结构体
*/
export interface DescribeBasicCCThresholdResponse {
/**
* CC启动开关(0:关闭;1:开启)
*/
CCEnable?: number;
/**
* CC防护阈值
*/
CCThreshold?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyDDoSPolicyName请求参数结构体
*/
export interface ModifyDDoSPolicyNameRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 策略ID
*/
PolicyId: string;
/**
* 策略名称
*/
Name: string;
}
/**
* DescribeIpUnBlockList返回参数结构体
*/
export interface DescribeIpUnBlockListResponse {
/**
* 开始时间
*/
BeginTime?: string;
/**
* 结束时间
*/
EndTime?: string;
/**
* IP解封记录
*/
List?: Array<IpUnBlockData>;
/**
* 总记录数
*/
Total?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyCCPolicySwitch请求参数结构体
*/
export interface ModifyCCPolicySwitchRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 策略ID
*/
SetId: string;
/**
* 开关状态
*/
Switch: number;
}
/**
* ModifyCCFrequencyRules返回参数结构体
*/
export interface ModifyCCFrequencyRulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyL4KeepTime请求参数结构体
*/
export interface ModifyL4KeepTimeRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则ID
*/
RuleId: string;
/**
* 会话保持开关,取值[0(会话保持关闭),1(会话保持开启)]
*/
KeepEnable: number;
/**
* 会话保持时间,单位秒
*/
KeepTime: number;
}
/**
* 调度域名信息
*/
export interface SchedulingDomain {
/**
* 调度域名
*/
Domain: string;
/**
* BGP线路IP列表
*/
BGPIpList: Array<string>;
/**
* 电信线路IP列表
*/
CTCCIpList: Array<string>;
/**
* 联通线路IP列表
*/
CUCCIpList: Array<string>;
/**
* 移动线路IP列表
*/
CMCCIpList: Array<string>;
/**
* 海外线路IP列表
*/
OverseaIpList: Array<string>;
/**
* 调度方式,当前仅支持优先级, 取值为priority
*/
Method: string;
/**
* 创建时间
*/
CreateTime: string;
/**
* ttl
*/
TTL: number;
/**
* 状态
注意:此字段可能返回 null,表示取不到有效值。
*/
Status: number;
/**
* 修改时间
注意:此字段可能返回 null,表示取不到有效值。
*/
ModifyTime: string;
}
/**
* ModifyCCHostProtection请求参数结构体
*/
export interface ModifyCCHostProtectionRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则ID
*/
RuleId: string;
/**
* 开启/关闭CC域名防护,取值[open(表示开启),close(表示关闭)]
*/
Method: string;
}
/**
* DescribeIpBlockList请求参数结构体
*/
export declare type DescribeIpBlockListRequest = null;
/**
* DescribeDDoSNetCount返回参数结构体
*/
export interface DescribeDDoSNetCountResponse {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business?: string;
/**
* 资源ID
*/
Id?: string;
/**
* 统计开始时间
*/
StartTime?: string;
/**
* 统计结束时间
*/
EndTime?: string;
/**
* 指标,取值[traffic(攻击协议流量, 单位KB), pkg(攻击协议报文数), classnum(攻击事件次数)]
*/
MetricName?: string;
/**
* Key-Value值数组,Key说明如下,
当MetricName为traffic时:
key为"TcpKBSum",表示TCP报文流量,单位KB
key为"UdpKBSum",表示UDP报文流量,单位KB
key为"IcmpKBSum",表示ICMP报文流量,单位KB
key为"OtherKBSum",表示其他报文流量,单位KB
当MetricName为pkg时:
key为"TcpPacketSum",表示TCP报文个数,单位个
key为"UdpPacketSum",表示UDP报文个数,单位个
key为"IcmpPacketSum",表示ICMP报文个数,单位个
key为"OtherPacketSum",表示其他报文个数,单位个
当MetricName为classnum时:
key的值表示攻击事件类型,其中Key为"UNKNOWNFLOOD",表示未知的攻击事件
*/
Data?: Array<KeyValue>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateL7Rules返回参数结构体
*/
export interface CreateL7RulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 巴拉多返回的数据
*/
export interface BaradData {
/**
* 指标名(connum表示TCP活跃连接数;
new_conn表示新建TCP连接数;
inactive_conn表示非活跃连接数;
intraffic表示入流量;
outtraffic表示出流量;
alltraffic表示出流量和入流量之和;
inpkg表示入包速率;
outpkg表示出包速率;)
*/
MetricName: string;
/**
* 值数组
*/
Data: Array<number>;
/**
* 值数组的大小
*/
Count: number;
}
/**
* ModifyDDoSSwitch请求参数结构体
*/
export interface ModifyDDoSSwitchRequest {
/**
* 大禹子产品代号(basic表示基础防护)
*/
Business: string;
/**
* =get表示读取DDoS防护状态;=set表示修改DDoS防护状态;
*/
Method: string;
/**
* 基础防护的IP,只有当Business为基础防护时才需要填写此字段;
*/
Ip?: string;
/**
* 只有当Business为基础防护时才需要填写此字段,IP所属的产品类型,取值[public(CVM产品),bm(黑石产品),eni(弹性网卡),vpngw(VPN网关), natgw(NAT网关),waf(Web应用安全产品),fpc(金融产品),gaap(GAAP产品), other(托管IP)]
*/
BizType?: string;
/**
* 只有当Business为基础防护时才需要填写此字段,IP所属的产品子类,取值[cvm(CVM),lb(负载均衡器),eni(弹性网卡),vpngw(VPN),natgw(NAT),waf(WAF),fpc(金融),gaap(GAAP),other(托管IP),eip(黑石弹性IP)]
*/
DeviceType?: string;
/**
* 只有当Business为基础防护时才需要填写此字段,IP所属的资源实例ID,当绑定新IP时必须填写此字段;例如是弹性网卡的IP,则InstanceId填写弹性网卡的ID(eni-*);
*/
InstanceId?: string;
/**
* 只有当Business为基础防护时才需要填写此字段,表示IP所属的地域,取值:
"bj": 华北地区(北京)
"cd": 西南地区(成都)
"cq": 西南地区(重庆)
"gz": 华南地区(广州)
"gzopen": 华南地区(广州Open)
"hk": 中国香港
"kr": 东南亚地区(首尔)
"sh": 华东地区(上海)
"shjr": 华东地区(上海金融)
"szjr": 华南地区(深圳金融)
"sg": 东南亚地区(新加坡)
"th": 东南亚地区(泰国)
"de": 欧洲地区(德国)
"usw": 美国西部(硅谷)
"ca": 北美地区(多伦多)
"jp": 日本
"hzec": 杭州
"in": 印度
"use": 美东地区(弗吉尼亚)
"ru": 俄罗斯
"tpe": 中国台湾
"nj": 南京
*/
IPRegion?: string;
/**
* 可选字段,防护状态值,取值[0(关闭),1(开启)];当Method为get时可以不填写此字段;
*/
Status?: number;
}
/**
* CreateNetReturn请求参数结构体
*/
export interface CreateNetReturnRequest {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business: string;
/**
* 资源实例ID
*/
Id: string;
}
/**
* ModifyDDoSAIStatus请求参数结构体
*/
export interface ModifyDDoSAIStatusRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* =get表示读取AI防护状态;=set表示修改AI防护状态;
*/
Method: string;
/**
* AI防护状态,取值[on,off];当Method=set时必填;
*/
DDoSAI?: string;
}
/**
* DescribeDDoSAttackSource返回参数结构体
*/
export interface DescribeDDoSAttackSourceResponse {
/**
* 总攻击源条数
*/
Total?: number;
/**
* 攻击源列表
*/
AttackSourceList?: Array<DDoSAttackSourceRecord>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeResourceList返回参数结构体
*/
export interface DescribeResourceListResponse {
/**
* 总记录数
*/
Total: number;
/**
* 资源记录列表,返回Key值说明:
"Key": "CreateTime" 表示资源实例购买时间
"Key": "Region" 表示资源实例的地域
"Key": "BoundIP" 表示独享包实例绑定的IP
"Key": "Id" 表示资源实例的ID
"Key": "CCEnabled" 表示资源实例的CC防护开关状态
"Key": "DDoSThreshold" 表示资源实例的DDoS的清洗阈值
"Key": "BoundStatus" 表示独享包或共享包实例的绑定IP操作状态(绑定中或绑定完成)
"Key": "Type" 此字段弃用
"Key": "ElasticLimit" 表示资源实例的弹性防护值
"Key": "DDoSAI" 表示资源实例的DDoS AI防护开关
"Key": "OverloadCount" 表示资源实例受到超过弹性防护值的次数
"Key": "Status" 表示资源实例的状态(idle:运行中, attacking:攻击中, blocking:封堵中, isolate:隔离中)
"Key": "Lbid" 此字段弃用
"Key": "ShowFlag" 此字段弃用
"Key": "Expire" 表示资源实例的过期时间
"Key": "CCThreshold" 表示资源实例的CC防护触发阈值
"Key": "AutoRenewFlag" 表示资源实例的自动续费是否开启
"Key": "IspCode" 表示独享包或共享包的线路(0-电信, 1-联通, 2-移动, 5-BGP)
"Key": "PackType" 表示套餐包类型
"Key": "PackId" 表示套餐包ID
"Key": "Name" 表示资源实例的名称
"Key": "Locked" 此字段弃用
"Key": "IpDDoSLevel" 表示资源实例的防护等级(low-宽松, middle-正常, high-严格)
"Key": "DefendStatus" 表示资源实例的DDoS防护状态(防护开启或临时关闭)
"Key": "UndefendExpire" 表示资源实例的DDoS防护临时关闭结束时间
"Key": "Tgw" 表示资源实例是否是新资源
"Key": "Bandwidth" 表示资源实例的保底防护值,只针对高防包和高防IP
"Key": "DdosMax" 表示资源实例的保底防护值,只针对高防IP专业版
"Key": "GFBandwidth" 表示资源实例的保底业务带宽,只针对高防IP
"Key": "ServiceBandwidth" 表示资源实例的保底业务带宽,只针对高防IP专业版
*/
ServicePacks: Array<KeyValueRecord>;
/**
* 大禹子产品代号(bgp表示独享包;bgp-multip表示共享包;bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeNewL4Rules返回参数结构体
*/
export interface DescribeNewL4RulesResponse {
/**
* 转发规则列表
*/
Rules?: Array<NewL4RuleEntry>;
/**
* 总规则数
*/
Total?: number;
/**
* 四层健康检查配置列表
*/
Healths?: Array<L4RuleHealth>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyCCThreshold请求参数结构体
*/
export interface ModifyCCThresholdRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版;basic表示基础防护)
*/
Business: string;
/**
* CC防护阈值,取值(0 100 150 240 350 480 550 700 850 1000 1500 2000 3000 5000 10000 20000);
当Business为高防IP、高防IP专业版时,其CC防护最大阈值跟资源的保底防护带宽有关,对应关系如下:
保底带宽: 最大C防护阈值
10: 20000,
20: 40000,
30: 70000,
40: 100000,
50: 150000,
60: 200000,
80: 250000,
100: 300000,
*/
Threshold: number;
/**
* 资源ID
*/
Id?: string;
/**
* 可选字段,代表CC防护类型,取值[http(HTTP协议的CC防护),https(HTTPS协议的CC防护)];当不填时,默认为HTTP协议的CC防护;当填写https时还需要填写RuleId字段;
*/
Protocol?: string;
/**
* 可选字段,表示HTTPS协议的7层转发规则ID(通过获取7层转发规则接口可以获取规则ID);
当Protocol=https时必须填写;
*/
RuleId?: string;
/**
* 查询的IP地址(仅基础防护提供),取值如:1.1.1.1
*/
BasicIp?: string;
/**
* 查询IP所属地域(仅基础防护提供),取值如:gz、bj、sh、hk等地域缩写
*/
BasicRegion?: string;
/**
* 专区类型(仅基础防护提供),取值如:公有云专区:public,黑石专区:bm, NAT服务器专区:nat,互联网通道:channel。
*/
BasicBizType?: string;
/**
* 设备类型(仅基础防护提供),取值如:服务器:cvm,公有云负载均衡:clb,黑石负载均衡:lb,NAT服务器:nat,互联网通道:channel.
*/
BasicDeviceType?: string;
/**
* 仅基础防护提供。可选,IPInstance Nat 网关(如果查询的设备类型是NAT服务器,需要传此参数,通过nat资源查询接口获取)
*/
BasicIpInstance?: string;
/**
* 仅基础防护提供。可选,运营商线路(如果查询的设备类型是NAT服务器,需要传此参数为5)
*/
BasicIspCode?: number;
/**
* 可选字段,当协议取值HTTPS时,必填
*/
Domain?: string;
}
/**
* ModifyDDoSDefendStatus返回参数结构体
*/
export interface ModifyDDoSDefendStatusResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateBasicDDoSAlarmThreshold请求参数结构体
*/
export interface CreateBasicDDoSAlarmThresholdRequest {
/**
* 大禹子产品代号(basic表示DDoS基础防护)
*/
Business: string;
/**
* =get表示读取告警阈值;=set表示设置告警阈值;
*/
Method: string;
/**
* 可选,告警阈值类型,1-入流量,2-清洗流量;当Method为set时必须填写;
*/
AlarmType?: number;
/**
* 可选,告警阈值,当Method为set时必须填写;当设置阈值为0时表示清除告警阈值配置;
*/
AlarmThreshold?: number;
}
/**
* 7层CC自定义规则
*/
export interface CCRuleConfig {
/**
* 统计周期,单位秒,取值[10, 30, 60]
*/
Period: number;
/**
* 访问次数,取值[1-10000]
*/
ReqNumber: number;
/**
* 执行动作,取值["alg"(人机识别), "drop"(拦截)]
*/
Action: string;
/**
* 执行时间,单位秒,取值[1-900]
*/
ExeDuration: number;
}
/**
* DescribeDDoSEvInfo返回参数结构体
*/
export interface DescribeDDoSEvInfoResponse {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business?: string;
/**
* 资源ID
*/
Id?: string;
/**
* 资源的IP
*/
Ip?: string;
/**
* 攻击开始时间
*/
StartTime?: string;
/**
* 攻击结束时间
*/
EndTime?: string;
/**
* TCP报文攻击包数
*/
TcpPacketSum?: number;
/**
* TCP报文攻击流量,单位KB
*/
TcpKBSum?: number;
/**
* UDP报文攻击包数
*/
UdpPacketSum?: number;
/**
* UDP报文攻击流量,单位KB
*/
UdpKBSum?: number;
/**
* ICMP报文攻击包数
*/
IcmpPacketSum?: number;
/**
* ICMP报文攻击流量,单位KB
*/
IcmpKBSum?: number;
/**
* 其他报文攻击包数
*/
OtherPacketSum?: number;
/**
* 其他报文攻击流量,单位KB
*/
OtherKBSum?: number;
/**
* 累计攻击流量,单位KB
*/
TotalTraffic?: number;
/**
* 攻击流量带宽峰值
*/
Mbps?: number;
/**
* 攻击包速率峰值
*/
Pps?: number;
/**
* PCAP文件下载链接
*/
PcapUrl?: Array<string>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribleRegionCount请求参数结构体
*/
export interface DescribleRegionCountRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;)
*/
Business: string;
/**
* 根据线路统计,取值为[1(BGP线路),2(南京电信),3(南京联通),99(第三方合作线路)];只对高防IP产品有效,其他产品此字段忽略
*/
LineList?: Array<number>;
}
/**
* ModifyCCSelfDefinePolicy返回参数结构体
*/
export interface ModifyCCSelfDefinePolicyResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSIpLog请求参数结构体
*/
export interface DescribeDDoSIpLogRequest {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 资源的IP
*/
Ip: string;
/**
* 攻击开始时间
*/
StartTime: string;
/**
* 攻击结束时间
*/
EndTime: string;
}
/**
* DescribeDDoSAlarmThreshold请求参数结构体
*/
export interface DescribeDDoSAlarmThresholdRequest {
/**
* 大禹子产品代号(shield表示棋牌;bgpip表示高防IP;bgp表示高防包;bgp-multip表示多ip高防包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID,字符串类型
*/
RsId: string;
}
/**
* DeleteNewL4Rules返回参数结构体
*/
export interface DeleteNewL4RulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 水印策略参数
*/
export interface WaterPrintPolicy {
/**
* TCP端口段,例如["2000-3000","3500-4000"]
*/
TcpPortList: Array<string>;
/**
* UDP端口段,例如["2000-3000","3500-4000"]
*/
UdpPortList: Array<string>;
/**
* 水印偏移量,取值范围[0, 100)
*/
Offset: number;
/**
* 是否自动剥离,取值[0(不自动剥离),1(自动剥离)]
*/
RemoveSwitch: number;
/**
* 是否开启,取值[0(没有开启),1(已开启)]
*/
OpenStatus: number;
}
/**
* CreateNewL7RulesUpload请求参数结构体
*/
export interface CreateNewL7RulesUploadRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 资源ID列表
*/
IdList: Array<string>;
/**
* 资源IP列表
*/
VipList: Array<string>;
/**
* 规则列表
*/
Rules: Array<L7RuleEntry>;
}
/**
* DeleteNewL7Rules返回参数结构体
*/
export interface DeleteNewL7RulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteCCSelfDefinePolicy返回参数结构体
*/
export interface DeleteCCSelfDefinePolicyResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSPolicy返回参数结构体
*/
export interface DescribeDDoSPolicyResponse {
/**
* DDoS高级策略列表
*/
DDosPolicyList?: Array<DDosPolicy>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteCCFrequencyRules返回参数结构体
*/
export interface DeleteCCFrequencyRulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteDDoSPolicyCase返回参数结构体
*/
export interface DeleteDDoSPolicyCaseResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateL4HealthConfig返回参数结构体
*/
export interface CreateL4HealthConfigResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateNewL7Rules请求参数结构体
*/
export interface CreateNewL7RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 资源ID列表
*/
IdList: Array<string>;
/**
* 资源IP列表
*/
VipList: Array<string>;
/**
* 规则列表
*/
Rules: Array<L7RuleEntry>;
}
/**
* ModifyL7Rules请求参数结构体
*/
export interface ModifyL7RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则
*/
Rule: L7RuleEntry;
}
/**
* ModifyElasticLimit返回参数结构体
*/
export interface ModifyElasticLimitResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateNewL7RulesUpload返回参数结构体
*/
export interface CreateNewL7RulesUploadResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 攻击源信息
*/
export interface DDoSAttackSourceRecord {
/**
* 攻击源ip
*/
SrcIp: string;
/**
* 省份(国内有效,不包含港澳台)
*/
Province: string;
/**
* 国家
*/
Nation: string;
/**
* 累计攻击包量
*/
PacketSum: number;
/**
* 累计攻击流量
*/
PacketLen: number;
}
/**
* CreateUnblockIp返回参数结构体
*/
export interface CreateUnblockIpResponse {
/**
* IP
*/
Ip?: string;
/**
* 解封类型(user:自助解封;auto:自动解封; update:升级解封;bind:绑定高防包解封)
*/
ActionType?: string;
/**
* 解封时间(预计解封时间)
*/
UnblockTime?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribePackIndex请求参数结构体
*/
export interface DescribePackIndexRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示高防包;net表示高防IP专业版)
*/
Business: string;
}
/**
* DescribeNewL7RulesErrHealth请求参数结构体
*/
export interface DescribeNewL7RulesErrHealthRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 规则Id列表
*/
RuleIdList?: Array<string>;
}
/**
* ModifyL4Rules请求参数结构体
*/
export interface ModifyL4RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则
*/
Rule: L4RuleEntry;
}
/**
* DescribeDDoSEvList返回参数结构体
*/
export interface DescribeDDoSEvListResponse {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版;basic表示DDoS基础防护)
*/
Business?: string;
/**
* 资源ID
*/
Id?: string;
/**
* 资源的IP
注意:此字段可能返回 null,表示取不到有效值。
*/
IpList?: Array<string>;
/**
* 开始时间
*/
StartTime?: string;
/**
* 结束时间
*/
EndTime?: string;
/**
* DDoS攻击事件列表
*/
Data?: Array<DDoSEventRecord>;
/**
* 总记录数
*/
Total?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSPolicy请求参数结构体
*/
export interface DescribeDDoSPolicyRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 可选字段,资源ID,如果填写则表示该资源绑定的DDoS高级策略
*/
Id?: string;
}
/**
* 四层规则结构体
*/
export interface NewL4RuleEntry {
/**
* 转发协议,取值[TCP, UDP]
*/
Protocol: string;
/**
* 转发端口
*/
VirtualPort: number;
/**
* 源站端口
*/
SourcePort: number;
/**
* 会话保持时间,单位秒
*/
KeepTime: number;
/**
* 回源列表
*/
SourceList: Array<L4RuleSource>;
/**
* 负载均衡方式,取值[1(加权轮询),2(源IP hash)]
*/
LbType: number;
/**
* 会话保持开关,取值[0(会话保持关闭),1(会话保持开启)];
*/
KeepEnable: number;
/**
* 回源方式,取值[1(域名回源),2(IP回源)]
*/
SourceType: number;
/**
* 规则ID
*/
RuleId?: string;
/**
* 规则描述
*/
RuleName?: string;
/**
* 移除水印状态,取值[0(关闭),1(开启)]
*/
RemoveSwitch?: number;
/**
* 规则修改时间
*/
ModifyTime?: string;
/**
* 对应地区信息
*/
Region?: number;
/**
* 绑定资源IP信息
*/
Ip?: string;
/**
* 绑定资源Id信息
*/
Id?: string;
}
/**
* DescribeL7HealthConfig返回参数结构体
*/
export interface DescribeL7HealthConfigResponse {
/**
* 七层健康检查配置数组
*/
HealthConfig?: Array<L7HealthConfig>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CC的访问频率控制规则
*/
export interface CCFrequencyRule {
/**
* CC的访问频率控制规则ID
*/
CCFrequencyRuleId: string;
/**
* URI字符串,必须以/开头,例如/abc/a.php,长度不超过31;当URI=/时,匹配模式只能选择前缀匹配;
*/
Uri: string;
/**
* User-Agent字符串,长度不超过80
*/
UserAgent: string;
/**
* Cookie字符串,长度不超过40
*/
Cookie: string;
/**
* 匹配规则,取值["include"(前缀匹配),"equal"(完全匹配)]
*/
Mode: string;
/**
* 统计周期,单位秒,取值[10, 30, 60]
*/
Period: number;
/**
* 访问次数,取值[1-10000]
*/
ReqNumber: number;
/**
* 执行动作,取值["alg"(人机识别), "drop"(拦截)]
*/
Act: string;
/**
* 执行时间,单位秒,取值[1-900]
*/
ExeDuration: number;
}
/**
* CreateCCSelfDefinePolicy返回参数结构体
*/
export interface CreateCCSelfDefinePolicyResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* L7规则
*/
export interface NewL7RuleEntry {
/**
* 转发协议,取值[http, https]
*/
Protocol: string;
/**
* 转发域名
*/
Domain: string;
/**
* 回源方式,取值[1(域名回源),2(IP回源)]
*/
SourceType: number;
/**
* 会话保持时间,单位秒
*/
KeepTime: number;
/**
* 回源列表
*/
SourceList: Array<L4RuleSource>;
/**
* 负载均衡方式,取值[1(加权轮询)]
*/
LbType: number;
/**
* 会话保持开关,取值[0(会话保持关闭),1(会话保持开启)]
*/
KeepEnable: number;
/**
* 规则ID,当添加新规则时可以不用填写此字段;当修改或者删除规则时需要填写此字段;
*/
RuleId?: string;
/**
* 证书来源,当转发协议为https时必须填,取值[2(腾讯云托管证书)],当转发协议为http时也可以填0
*/
CertType?: number;
/**
* 当证书来源为腾讯云托管证书时,此字段必须填写托管证书ID
*/
SSLId?: string;
/**
* 当证书来源为自有证书时,此字段必须填写证书内容;(因已不再支持自有证书,此字段已弃用,请不用填写此字段)
*/
Cert?: string;
/**
* 当证书来源为自有证书时,此字段必须填写证书密钥;(因已不再支持自有证书,此字段已弃用,请不用填写此字段)
*/
PrivateKey?: string;
/**
* 规则描述
*/
RuleName?: string;
/**
* 规则状态,取值[0(规则配置成功),1(规则配置生效中),2(规则配置失败),3(规则删除生效中),5(规则删除失败),6(规则等待配置),7(规则等待删除),8(规则待配置证书)]
*/
Status?: number;
/**
* cc防护状态,取值[0(关闭), 1(开启)]
*/
CCStatus?: number;
/**
* HTTPS协议的CC防护状态,取值[0(关闭), 1(开启)]
*/
CCEnable?: number;
/**
* HTTPS协议的CC防护阈值
*/
CCThreshold?: number;
/**
* HTTPS协议的CC防护等级
*/
CCLevel?: string;
/**
* 区域码
*/
Region?: number;
/**
* 资源Id
*/
Id?: string;
/**
* 资源Ip
*/
Ip?: string;
/**
* 修改时间
*/
ModifyTime?: string;
/**
* 是否开启Https协议使用Http回源,取值[0(关闭), 1(开启)],不填写默认是关闭
*/
HttpsToHttpEnable?: number;
/**
* 接入端口值
注意:此字段可能返回 null,表示取不到有效值。
*/
VirtualPort?: number;
}
/**
* 删除l4规则接口
*/
export interface L4DelRule {
/**
* 资源Id
*/
Id: string;
/**
* 资源IP
*/
Ip: string;
/**
* 规则Id
*/
RuleIdList: Array<string>;
}
/**
* DescribeCCSelfDefinePolicy返回参数结构体
*/
export interface DescribeCCSelfDefinePolicyResponse {
/**
* 自定义规则总数
*/
Total?: number;
/**
* 策略列表
*/
Policys?: Array<CCPolicy>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateBoundIP返回参数结构体
*/
export interface CreateBoundIPResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSUsedStatis请求参数结构体
*/
export interface DescribeDDoSUsedStatisRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
}
/**
* DDoS高级策略的禁用协议选项
*/
export interface DDoSPolicyDropOption {
/**
* 禁用TCP协议,取值范围[0,1]
*/
DropTcp: number;
/**
* 禁用UDP协议,取值范围[0,1]
*/
DropUdp: number;
/**
* 禁用ICMP协议,取值范围[0,1]
*/
DropIcmp: number;
/**
* 禁用其他协议,取值范围[0,1]
*/
DropOther: number;
/**
* 拒绝海外流量,取值范围[0,1]
*/
DropAbroad: number;
/**
* 空连接防护,取值范围[0,1]
*/
CheckSyncConn: number;
/**
* 基于来源IP及目的IP的新建连接抑制,取值范围[0,4294967295]
*/
SdNewLimit?: number;
/**
* 基于目的IP的新建连接抑制,取值范围[0,4294967295]
*/
DstNewLimit?: number;
/**
* 基于来源IP及目的IP的并发连接抑制,取值范围[0,4294967295]
*/
SdConnLimit?: number;
/**
* 基于目的IP的并发连接抑制,取值范围[0,4294967295]
*/
DstConnLimit?: number;
/**
* 基于连接抑制触发阈值,取值范围[0,4294967295]
*/
BadConnThreshold?: number;
/**
* 异常连接检测条件,空连接防护开关,,取值范围[0,1]
*/
NullConnEnable?: number;
/**
* 异常连接检测条件,连接超时,,取值范围[0,65535]
*/
ConnTimeout?: number;
/**
* 异常连接检测条件,syn占比ack百分比,,取值范围[0,100]
*/
SynRate?: number;
/**
* 异常连接检测条件,syn阈值,取值范围[0,100]
*/
SynLimit?: number;
/**
* tcp限速,取值范围[0,4294967295]
*/
DTcpMbpsLimit?: number;
/**
* udp限速,取值范围[0,4294967295]
*/
DUdpMbpsLimit?: number;
/**
* icmp限速,取值范围[0,4294967295]
*/
DIcmpMbpsLimit?: number;
/**
* other协议限速,取值范围[0,4294967295]
*/
DOtherMbpsLimit?: number;
}
/**
* ModifyElasticLimit请求参数结构体
*/
export interface ModifyElasticLimitRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 弹性防护阈值,取值[0 10000 20000 30000 40000 50000 60000 70000 80000 90000 100000 120000 150000 200000 250000 300000 400000 600000 800000 220000 310000 110000 270000 610000]
*/
Limit: number;
}
/**
* ModifyL4Health返回参数结构体
*/
export interface ModifyL4HealthResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CC攻击事件记录
*/
export interface CCEventRecord {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版;basic表示DDoS基础防护)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 资源的IP
*/
Vip: string;
/**
* 攻击开始时间
*/
StartTime: string;
/**
* 攻击结束时间
*/
EndTime: string;
/**
* 总请求QPS峰值
*/
ReqQps: number;
/**
* 攻击QPS峰值
*/
DropQps: number;
/**
* 攻击状态,取值[0(攻击中), 1(攻击结束)]
*/
AttackStatus: number;
/**
* 资源名称
注意:此字段可能返回 null,表示取不到有效值。
*/
ResourceName: string;
/**
* 域名列表
注意:此字段可能返回 null,表示取不到有效值。
*/
DomainList: string;
/**
* uri列表
注意:此字段可能返回 null,表示取不到有效值。
*/
UriList: string;
/**
* 攻击源列表
注意:此字段可能返回 null,表示取不到有效值。
*/
AttackipList: string;
}
/**
* DescribeTransmitStatis请求参数结构体
*/
export interface DescribeTransmitStatisRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版;bgp表示独享包;bgp-multip表示共享包)
*/
Business: string;
/**
* 资源实例ID
*/
Id: string;
/**
* 指标名,取值:
traffic表示流量带宽;
pkg表示包速率;
*/
MetricName: string;
/**
* 统计时间粒度(300表示5分钟;3600表示小时;86400表示天)
*/
Period: number;
/**
* 统计开始时间,秒部分保持为0,分钟部分为5的倍数
*/
StartTime: string;
/**
* 统计结束时间,秒部分保持为0,分钟部分为5的倍数
*/
EndTime: string;
/**
* 资源的IP(当Business为bgp-multip时必填,且仅支持一个IP);当不填写时,默认统计资源实例的所有IP;资源实例有多个IP(比如高防IP专业版)时,统计方式是求和;
*/
IpList?: Array<string>;
}
/**
* DescribeInsurePacks返回参数结构体
*/
export interface DescribeInsurePacksResponse {
/**
* 保险包套餐列表
*/
InsurePacks?: Array<KeyValueRecord>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateUnblockIp请求参数结构体
*/
export interface CreateUnblockIpRequest {
/**
* IP
*/
Ip: string;
/**
* 解封类型(user:自助解封;auto:自动解封; update:升级解封;bind:绑定高防包解封)
*/
ActionType: string;
}
/**
* ModifyResourceRenewFlag返回参数结构体
*/
export interface ModifyResourceRenewFlagResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 排序字段
*/
export interface OrderBy {
/**
* 排序字段名称,取值[
bandwidth(带宽),
overloadCount(超峰值次数)
]
*/
Field: string;
/**
* 升降序,取值为[asc(升序),(升序),desc(降序), DESC(降序)]
*/
Order: string;
}
/**
* DescribeActionLog返回参数结构体
*/
export interface DescribeActionLogResponse {
/**
* 总记录数
*/
TotalCount?: number;
/**
* 记录数组
*/
Data?: Array<KeyValueRecord>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCCTrend返回参数结构体
*/
export interface DescribeCCTrendResponse {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版;basic表示DDoS基础防护)
*/
Business?: string;
/**
* 资源ID
注意:此字段可能返回 null,表示取不到有效值。
*/
Id?: string;
/**
* 资源的IP
*/
Ip?: string;
/**
* 指标,取值[inqps(总请求峰值,dropqps(攻击请求峰值))]
*/
MetricName?: string;
/**
* 统计粒度,取值[300(5分钟),3600(小时),86400(天)]
*/
Period?: number;
/**
* 统计开始时间
*/
StartTime?: string;
/**
* 统计结束时间
*/
EndTime?: string;
/**
* 值数组
*/
Data?: Array<number>;
/**
* 值个数
*/
Count?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyDDoSPolicyCase返回参数结构体
*/
export interface ModifyDDoSPolicyCaseResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCCUrlAllow返回参数结构体
*/
export interface DescribeCCUrlAllowResponse {
/**
* 该字段被RecordList字段替代了,请不要使用
*/
Data?: Array<KeyValue>;
/**
* 记录总数
*/
Total?: number;
/**
* 返回黑/白名单的记录,
"Key":"url"时,"Value":值表示URL;
"Key":"domain"时, "Value":值表示域名;
"Key":"type"时,"Value":值表示黑白名单类型(white为白名单,block为黑名单);
"Key":"protocol"时,"Value":值表示CC的防护类型(HTTP防护或HTTPS域名防护);
*/
RecordList?: Array<KeyValueRecord>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeSecIndex请求参数结构体
*/
export declare type DescribeSecIndexRequest = null;
/**
* ModifyCCFrequencyRulesStatus请求参数结构体
*/
export interface ModifyCCFrequencyRulesStatusRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 7层转发规则ID(通过获取7层转发规则接口可以获取规则ID)
*/
RuleId: string;
/**
* 开启或关闭,取值["on"(开启),"off"(关闭)]
*/
Method: string;
}
/**
* DescribeDDoSCount返回参数结构体
*/
export interface DescribeDDoSCountResponse {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business?: string;
/**
* 资源ID
*/
Id?: string;
/**
* 资源的IP
*/
Ip?: string;
/**
* 统计开始时间
*/
StartTime?: string;
/**
* 统计结束时间
*/
EndTime?: string;
/**
* 指标,取值[traffic(攻击协议流量, 单位KB), pkg(攻击协议报文数), classnum(攻击事件次数)]
*/
MetricName?: string;
/**
* Key-Value值数组,Key说明如下,
当MetricName为traffic时:
key为"TcpKBSum",表示TCP报文流量,单位KB
key为"UdpKBSum",表示UDP报文流量,单位KB
key为"IcmpKBSum",表示ICMP报文流量,单位KB
key为"OtherKBSum",表示其他报文流量,单位KB
当MetricName为pkg时:
key为"TcpPacketSum",表示TCP报文个数,单位个
key为"UdpPacketSum",表示UDP报文个数,单位个
key为"IcmpPacketSum",表示ICMP报文个数,单位个
key为"OtherPacketSum",表示其他报文个数,单位个
当MetricName为classnum时:
key的值表示攻击事件类型,其中Key为"UNKNOWNFLOOD",表示未知的攻击事件
*/
Data?: Array<KeyValue>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeL4RulesErrHealth返回参数结构体
*/
export interface DescribeL4RulesErrHealthResponse {
/**
* 异常规则的总数
*/
Total?: number;
/**
* 异常规则列表,返回值说明: Key值为规则ID,Value值为异常IP,多个IP用","分割
*/
ErrHealths?: Array<KeyValue>;
/**
* 异常规则列表(提供更多的错误相关信息),返回值说明:
Key值为RuleId时,Value值为规则ID;
Key值为Protocol时,Value值为规则的转发协议;
Key值为VirtualPort时,Value值为规则的转发端口;
Key值为ErrMessage时,Value值为健康检查异常信息;
健康检查异常信息的格式为"SourceIp:1.1.1.1|SourcePort:1234|AbnormalStatTime:1570689065|AbnormalReason:connection time out|Interval:20|CheckNum:6|FailNum:6" 多个源IP的错误信息用,分割,
SourceIp表示源站IP,SourcePort表示源站端口,AbnormalStatTime表示异常时间,AbnormalReason表示异常原因,Interval表示检查周期,CheckNum表示检查次数,FailNum表示失败次数;
*/
ExtErrHealths?: Array<KeyValueRecord>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteDDoSPolicy返回参数结构体
*/
export interface DeleteDDoSPolicyResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSTrend请求参数结构体
*/
export interface DescribeDDoSTrendRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版;basic表示DDoS基础防护)
*/
Business: string;
/**
* 资源实例的IP
*/
Ip: string;
/**
* 指标,取值[bps(攻击流量带宽,pps(攻击包速率))]
*/
MetricName: string;
/**
* 统计粒度,取值[300(5分钟),3600(小时),86400(天)]
*/
Period: number;
/**
* 统计开始时间
*/
StartTime: string;
/**
* 统计结束时间
*/
EndTime: string;
/**
* 资源实例ID,当Business为basic时,此字段不用填写(因为基础防护没有资源实例)
*/
Id?: string;
}
/**
* ModifyDDoSPolicy返回参数结构体
*/
export interface ModifyDDoSPolicyResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 资源的IP数组
*/
export interface ResourceIp {
/**
* 资源ID
*/
Id: string;
/**
* 资源的IP数组
*/
IpList?: Array<string>;
}
/**
* CC告警阈值
*/
export interface CCAlarmThreshold {
/**
* CC告警阈值
*/
AlarmThreshold: number;
}
/**
* DescribeDDoSNetIpLog请求参数结构体
*/
export interface DescribeDDoSNetIpLogRequest {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 攻击开始时间
*/
StartTime: string;
/**
* 攻击结束时间
*/
EndTime: string;
}
/**
* 七层健康检查配置
*/
export interface L7HealthConfig {
/**
* 转发协议,取值[http, https, http/https]
*/
Protocol: string;
/**
* 转发域名
*/
Domain: string;
/**
* =1表示开启;=0表示关闭
*/
Enable: number;
/**
* 检测间隔时间,单位秒
*/
Interval: number;
/**
* 异常判定次数,单位次
*/
KickNum: number;
/**
* 健康判定次数,单位次
*/
AliveNum: number;
/**
* 健康检查探测方法,可选HEAD或GET,默认为HEAD
*/
Method: string;
/**
* 健康检查判定正常状态码,1xx =1, 2xx=2, 3xx=4, 4xx=8,5xx=16,多个状态码值加和
*/
StatusCode: number;
/**
* 检查目录的URL,默认为/
*/
Url: string;
}
/**
* DescribeDDoSNetEvInfo返回参数结构体
*/
export interface DescribeDDoSNetEvInfoResponse {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business?: string;
/**
* 资源ID
*/
Id?: string;
/**
* 攻击开始时间
*/
StartTime?: string;
/**
* 攻击结束时间
*/
EndTime?: string;
/**
* TCP报文攻击包数
*/
TcpPacketSum?: number;
/**
* TCP报文攻击流量,单位KB
*/
TcpKBSum?: number;
/**
* UDP报文攻击包数
*/
UdpPacketSum?: number;
/**
* UDP报文攻击流量,单位KB
*/
UdpKBSum?: number;
/**
* ICMP报文攻击包数
*/
IcmpPacketSum?: number;
/**
* ICMP报文攻击流量,单位KB
*/
IcmpKBSum?: number;
/**
* 其他报文攻击包数
*/
OtherPacketSum?: number;
/**
* 其他报文攻击流量,单位KB
*/
OtherKBSum?: number;
/**
* 累计攻击流量,单位KB
*/
TotalTraffic?: number;
/**
* 攻击流量带宽峰值
*/
Mbps?: number;
/**
* 攻击包速率峰值
*/
Pps?: number;
/**
* PCAP文件下载链接
*/
PcapUrl?: Array<string>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyCCAlarmThreshold返回参数结构体
*/
export interface ModifyCCAlarmThresholdResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeRuleSets请求参数结构体
*/
export interface DescribeRuleSetsRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID列表
*/
IdList: Array<string>;
}
/**
* DescribeSchedulingDomainList请求参数结构体
*/
export interface DescribeSchedulingDomainListRequest {
/**
* 一页条数,填0表示不分页
*/
Limit: number;
/**
* 页起始偏移,取值为(页码-1)*一页条数
*/
Offset: number;
/**
* 可选,筛选特定的域名
*/
Domain?: string;
}
/**
* DescribleL7Rules返回参数结构体
*/
export interface DescribleL7RulesResponse {
/**
* 转发规则列表
*/
Rules?: Array<L7RuleEntry>;
/**
* 总规则数
*/
Total?: number;
/**
* 健康检查配置列表
*/
Healths?: Array<L7RuleHealth>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeBizTrend请求参数结构体
*/
export interface DescribeBizTrendRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 资源实例ID
*/
Id: string;
/**
* 统计周期,可取值300,1800,3600,21600,86400,单位秒
*/
Period: number;
/**
* 统计开始时间
*/
StartTime: string;
/**
* 统计结束时间
*/
EndTime: string;
/**
* 统计方式,可取值max, min, avg, sum, 如统计纬度是流量速率或包量速率,仅可取值max
*/
Statistics: string;
/**
* 统计纬度,可取值connum, new_conn, inactive_conn, intraffic, outtraffic, inpkg, outpkg, qps
*/
MetricName: string;
/**
* 协议及端口列表,协议可取值TCP, UDP, HTTP, HTTPS,仅统计纬度为连接数时有效
*/
ProtoInfo?: Array<ProtocolPort>;
/**
* 统计纬度为qps时,可选特定域名查询
*/
Domain?: string;
}
/**
* CreateCCFrequencyRules返回参数结构体
*/
export interface CreateCCFrequencyRulesResponse {
/**
* CC防护的访问频率控制规则ID
*/
CCFrequencyRuleId?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateNewL4Rules请求参数结构体
*/
export interface CreateNewL4RulesRequest {
/**
* 高防产品代号:bgpip
*/
Business: string;
/**
* 添加规则资源列表
*/
IdList: Array<string>;
/**
* 添加规则IP列表
*/
VipList: Array<string>;
/**
* 规则列表
*/
Rules: Array<L4RuleEntry>;
}
/**
* DDoS高级策略的禁用端口
*/
export interface DDoSPolicyPortLimit {
/**
* 协议,取值范围[tcp,udp,all]
*/
Protocol: string;
/**
* 开始目的端口,取值范围[0,65535]
*/
DPortStart: number;
/**
* 结束目的端口,取值范围[0,65535],要求大于等于开始目的端口
*/
DPortEnd: number;
/**
* 开始源端口,取值范围[0,65535]
注意:此字段可能返回 null,表示取不到有效值。
*/
SPortStart?: number;
/**
* 结束源端口,取值范围[0,65535],要求大于等于开始源端口
注意:此字段可能返回 null,表示取不到有效值。
*/
SPortEnd?: number;
/**
* 执行动作,取值[drop(丢弃) ,transmit(转发)]
注意:此字段可能返回 null,表示取不到有效值。
*/
Action?: string;
/**
* 禁用端口类型,取值[0(目的端口范围禁用), 1(源端口范围禁用), 2(目的和源端口范围同时禁用)]
注意:此字段可能返回 null,表示取不到有效值。
*/
Kind?: number;
}
/**
* DescribeSchedulingDomainList返回参数结构体
*/
export interface DescribeSchedulingDomainListResponse {
/**
* 调度域名总数
*/
Total?: number;
/**
* 调度域名列表信息
*/
DomainList?: Array<SchedulingDomain>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSNetTrend返回参数结构体
*/
export interface DescribeDDoSNetTrendResponse {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business?: string;
/**
* 资源ID
*/
Id?: string;
/**
* 指标,取值[bps(攻击流量带宽,pps(攻击包速率))]
*/
MetricName?: string;
/**
* 统计粒度,取值[300(5分钟),3600(小时),86400(天)]
*/
Period?: number;
/**
* 统计开始时间
*/
StartTime?: string;
/**
* 统计结束时间
*/
EndTime?: string;
/**
* 值数组
*/
Data?: Array<number>;
/**
* 值个数
*/
Count?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeUnBlockStatis返回参数结构体
*/
export interface DescribeUnBlockStatisResponse {
/**
* 解封总配额数
*/
Total?: number;
/**
* 已使用次数
*/
Used?: number;
/**
* 统计起始时间
*/
BeginTime?: string;
/**
* 统计结束时间
*/
EndTime?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribleL7Rules请求参数结构体
*/
export interface DescribleL7RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 规则ID,可选参数,填写后获取指定的规则
*/
RuleIdList?: Array<string>;
/**
* 一页条数,填0表示不分页
*/
Limit?: number;
/**
* 页起始偏移,取值为(页码-1)*一页条数
*/
Offset?: number;
/**
* 域名搜索,选填,当需要搜索域名请填写
*/
Domain?: string;
/**
* 转发协议搜索,选填,取值[http, https, http/https]
*/
ProtocolList?: Array<string>;
/**
* 状态搜索,选填,取值[0(规则配置成功),1(规则配置生效中),2(规则配置失败),3(规则删除生效中),5(规则删除失败),6(规则等待配置),7(规则等待删除),8(规则待配置证书)]
*/
StatusList?: Array<number>;
}
/**
* DescribeCCIpAllowDeny请求参数结构体
*/
export interface DescribeCCIpAllowDenyRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 黑或白名单,取值[white(白名单),black(黑名单)]
注意:此数组只能有一个值,不能同时获取黑名单和白名单
*/
Type: Array<string>;
/**
* 分页参数
*/
Limit?: number;
/**
* 分页参数
*/
Offset?: number;
/**
* 可选,代表HTTP协议或HTTPS协议的CC防护,取值[http(HTTP协议的CC防护),https(HTTPS协议的CC防护)];
*/
Protocol?: string;
}
/**
* DescribeSecIndex返回参数结构体
*/
export interface DescribeSecIndexResponse {
/**
* 字段值,如下:
AttackIpCount:受攻击的IP数
AttackCount:攻击次数
BlockCount:封堵次数
MaxMbps:攻击峰值Mbps
IpNum:统计的IP数据
*/
Data?: Array<KeyValue>;
/**
* 本月开始时间
*/
BeginDate?: string;
/**
* 本月结束时间
*/
EndDate?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* L7规则
*/
export interface L7RuleEntry {
/**
* 转发协议,取值[http, https]
*/
Protocol: string;
/**
* 转发域名
*/
Domain: string;
/**
* 回源方式,取值[1(域名回源),2(IP回源)]
*/
SourceType: number;
/**
* 会话保持时间,单位秒
*/
KeepTime: number;
/**
* 回源列表
*/
SourceList: Array<L4RuleSource>;
/**
* 负载均衡方式,取值[1(加权轮询)]
*/
LbType: number;
/**
* 会话保持开关,取值[0(会话保持关闭),1(会话保持开启)]
*/
KeepEnable: number;
/**
* 规则ID,当添加新规则时可以不用填写此字段;当修改或者删除规则时需要填写此字段;
*/
RuleId?: string;
/**
* 证书来源,当转发协议为https时必须填,取值[2(腾讯云托管证书)],当转发协议为http时也可以填0
*/
CertType?: number;
/**
* 当证书来源为腾讯云托管证书时,此字段必须填写托管证书ID
*/
SSLId?: string;
/**
* 当证书来源为自有证书时,此字段必须填写证书内容;(因已不再支持自有证书,此字段已弃用,请不用填写此字段)
*/
Cert?: string;
/**
* 当证书来源为自有证书时,此字段必须填写证书密钥;(因已不再支持自有证书,此字段已弃用,请不用填写此字段)
*/
PrivateKey?: string;
/**
* 规则描述
*/
RuleName?: string;
/**
* 规则状态,取值[0(规则配置成功),1(规则配置生效中),2(规则配置失败),3(规则删除生效中),5(规则删除失败),6(规则等待配置),7(规则等待删除),8(规则待配置证书)]
*/
Status?: number;
/**
* cc防护状态,取值[0(关闭), 1(开启)]
*/
CCStatus?: number;
/**
* HTTPS协议的CC防护状态,取值[0(关闭), 1(开启)]
*/
CCEnable?: number;
/**
* HTTPS协议的CC防护阈值
*/
CCThreshold?: number;
/**
* HTTPS协议的CC防护等级
*/
CCLevel?: string;
/**
* 是否开启Https协议使用Http回源,取值[0(关闭), 1(开启)],不填写默认是关闭
注意:此字段可能返回 null,表示取不到有效值。
*/
HttpsToHttpEnable?: number;
/**
* 接入端口值
注意:此字段可能返回 null,表示取不到有效值。
*/
VirtualPort?: number;
}
/**
* IP解封记录
*/
export interface IpUnBlockData {
/**
* IP
*/
Ip: string;
/**
* 封堵时间
*/
BlockTime: string;
/**
* 解封时间(实际解封时间)
*/
UnBlockTime: string;
/**
* 解封类型(user:自助解封;auto:自动解封; update:升级解封;bind:绑定高防包解封)
*/
ActionType: string;
}
/**
* DescribeL4HealthConfig返回参数结构体
*/
export interface DescribeL4HealthConfigResponse {
/**
* 四层健康检查配置数组
*/
HealthConfig?: Array<L4HealthConfig>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyDDoSLevel请求参数结构体
*/
export interface ModifyDDoSLevelRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* =get表示读取防护等级;=set表示修改防护等级
*/
Method: string;
/**
* 防护等级,取值[low,middle,high];当Method=set时必填
*/
DDoSLevel?: string;
}
/**
* DDoS高级策略的报文过滤项
*/
export interface DDoSPolicyPacketFilter {
/**
* 协议,取值范围[tcp,udp,icmp,all]
*/
Protocol: string;
/**
* 开始源端口,取值范围[0,65535]
*/
SportStart: number;
/**
* 结束源端口,取值范围[0,65535]
*/
SportEnd: number;
/**
* 开始目的端口,取值范围[0,65535]
*/
DportStart: number;
/**
* 结束目的端口,取值范围[0,65535]
*/
DportEnd: number;
/**
* 最小包长,取值范围[0,1500]
*/
PktlenMin: number;
/**
* 最大包长,取值范围[0,1500]
*/
PktlenMax: number;
/**
* 是否检测载荷,取值范围[
begin_l3(IP头)
begin_l4(TCP头)
begin_l5(载荷)
no_match(不检测)
]
*/
MatchBegin: string;
/**
* 是否是正则表达式,取值范围[sunday(表示关键字),pcre(表示正则表达式)]
*/
MatchType: string;
/**
* 关键字或正则表达式
*/
Str: string;
/**
* 检测深度,取值范围[0,1500]
*/
Depth: number;
/**
* 检测偏移量,取值范围[0,1500]
*/
Offset: number;
/**
* 是否包括,取值范围[0(表示不包含),1(表示包含)]
*/
IsNot: number;
/**
* 策略动作,取值范围[drop,drop_black,drop_rst,drop_black_rst,transmit]
*/
Action: string;
}
/**
* DeleteCCFrequencyRules请求参数结构体
*/
export interface DeleteCCFrequencyRulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* CC防护的访问频率控制规则ID
*/
CCFrequencyRuleId: string;
}
/**
* DescribeDDoSNetIpLog返回参数结构体
*/
export interface DescribeDDoSNetIpLogResponse {
/**
* 大禹子产品代号(net表示高防IP专业版)
*/
Business?: string;
/**
* 资源ID
*/
Id?: string;
/**
* 攻击开始时间
*/
StartTime?: string;
/**
* 攻击结束时间
*/
EndTime?: string;
/**
* IP攻击日志,KeyValue数组,Key-Value取值说明:
Key为"LogTime"时,Value值为IP日志时间
Key为"LogMessage"时,Value值为Ip日志内容
*/
Data?: Array<KeyValueRecord>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateCCFrequencyRules请求参数结构体
*/
export interface CreateCCFrequencyRulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 7层转发规则ID(通过获取7层转发规则接口可以获取规则ID)
*/
RuleId: string;
/**
* 匹配规则,取值["include"(前缀匹配),"equal"(完全匹配)]
*/
Mode: string;
/**
* 统计周期,单位秒,取值[10, 30, 60]
*/
Period: number;
/**
* 访问次数,取值[1-10000]
*/
ReqNumber: number;
/**
* 执行动作,取值["alg"(人机识别), "drop"(拦截)]
*/
Act: string;
/**
* 执行时间,单位秒,取值[1-900]
*/
ExeDuration: number;
/**
* URI字符串,必须以/开头,例如/abc/a.php,长度不超过31;当URI=/时,匹配模式只能选择前缀匹配;
*/
Uri?: string;
/**
* User-Agent字符串,长度不超过80
*/
UserAgent?: string;
/**
* Cookie字符串,长度不超过40
*/
Cookie?: string;
}
/**
* DeleteL7Rules返回参数结构体
*/
export interface DeleteL7RulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateL7HealthConfig返回参数结构体
*/
export interface CreateL7HealthConfigResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDDoSTrend返回参数结构体
*/
export interface DescribeDDoSTrendResponse {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版;basic表示DDoS基础防护)
*/
Business?: string;
/**
* 资源ID
注意:此字段可能返回 null,表示取不到有效值。
*/
Id?: string;
/**
* 资源的IP
*/
Ip?: string;
/**
* 指标,取值[bps(攻击流量带宽,pps(攻击包速率))]
*/
MetricName?: string;
/**
* 统计粒度,取值[300(5分钟),3600(小时),86400(天)]
*/
Period?: number;
/**
* 统计开始时间
*/
StartTime?: string;
/**
* 统计结束时间
*/
EndTime?: string;
/**
* 值数组,攻击流量带宽单位为Mbps,包速率单位为pps
*/
Data?: Array<number>;
/**
* 值个数
*/
Count?: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateL7RulesUpload返回参数结构体
*/
export interface CreateL7RulesUploadResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribleRegionCount返回参数结构体
*/
export interface DescribleRegionCountResponse {
/**
* 地域资源实例数
*/
RegionList?: Array<RegionInstanceCount>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyDDoSThreshold请求参数结构体
*/
export interface ModifyDDoSThresholdRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* DDoS清洗阈值,取值[0, 60, 80, 100, 150, 200, 250, 300, 400, 500, 700, 1000];
当设置值为0时,表示采用默认值;
*/
Threshold: number;
}
/**
* DDoS攻击事件记录
*/
export interface DDoSEventRecord {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版;basic表示DDoS基础防护)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 资源的IP
*/
Vip: string;
/**
* 攻击开始时间
*/
StartTime: string;
/**
* 攻击结束时间
*/
EndTime: string;
/**
* 攻击最大带宽
*/
Mbps: number;
/**
* 攻击最大包速率
*/
Pps: number;
/**
* 攻击类型
*/
AttackType: string;
/**
* 是否被封堵,取值[1(是),0(否),2(无效值)]
*/
BlockFlag: number;
/**
* 是否超过弹性防护峰值,取值取值[yes(是),no(否),空字符串(未知值)]
*/
OverLoad: string;
/**
* 攻击状态,取值[0(攻击中), 1(攻击结束)]
*/
AttackStatus: number;
/**
* 资源名称
注意:此字段可能返回 null,表示取不到有效值。
*/
ResourceName: string;
/**
* 攻击事件Id
注意:此字段可能返回 null,表示取不到有效值。
*/
EventId: string;
}
/**
* DescribleL4Rules返回参数结构体
*/
export interface DescribleL4RulesResponse {
/**
* 转发规则列表
*/
Rules?: Array<L4RuleEntry>;
/**
* 总规则数
*/
Total?: number;
/**
* 健康检查配置列表
*/
Healths?: Array<L4RuleHealth>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyL4Rules返回参数结构体
*/
export interface ModifyL4RulesResponse {
/**
* 成功码
*/
Success?: SuccessCode;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCCTrend请求参数结构体
*/
export interface DescribeCCTrendRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版;basic表示DDoS基础防护)
*/
Business: string;
/**
* 资源的IP
*/
Ip: string;
/**
* 指标,取值[inqps(总请求峰值,dropqps(攻击请求峰值))]
*/
MetricName: string;
/**
* 统计粒度,取值[300(5分钟),3600(小时),86400(天)]
*/
Period: number;
/**
* 统计开始时间
*/
StartTime: string;
/**
* 统计结束时间
*/
EndTime: string;
/**
* 资源实例ID,当Business为basic时,此字段不用填写(因为基础防护没有资源实例)
*/
Id?: string;
/**
* 域名,可选
*/
Domain?: string;
}
/**
* DeleteNewL7Rules请求参数结构体
*/
export interface DeleteNewL7RulesRequest {
/**
* 大禹子产品代号(bgpip表示高防IP)
*/
Business: string;
/**
* 删除规则列表
*/
Rule: Array<L4DelRule>;
}
/**
* CreateInstanceName请求参数结构体
*/
export interface CreateInstanceNameRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 资源ID
*/
Id: string;
/**
* 资源实例名称,长度不超过32个字符
*/
Name: string;
}
/**
* DeleteDDoSPolicy请求参数结构体
*/
export interface DeleteDDoSPolicyRequest {
/**
* 大禹子产品代号(bgpip表示高防IP;bgp表示独享包;bgp-multip表示共享包;net表示高防IP专业版)
*/
Business: string;
/**
* 策略ID
*/
PolicyId: string;
} | the_stack |
import type HighlightRange from '@src/model/range';
import type { SelectedNode, DomNode } from '@src/types';
import { SplitType, SelectedNodeType } from '@src/types';
import { hasClass, addClass as addElementClass, isHighlightWrapNode, removeAllClass } from '@src/util/dom';
import {
ID_DIVISION,
getDefaultOptions,
CAMEL_DATASET_IDENTIFIER,
CAMEL_DATASET_IDENTIFIER_EXTRA,
DATASET_IDENTIFIER,
DATASET_SPLIT_TYPE,
DATASET_IDENTIFIER_EXTRA,
} from '../util/const';
import { unique } from '../util/tool';
/**
* 支持的选择器类型
* - class: .title, .main-nav
* - id: #nav, #js-toggle-btn
* - tag: div, p, span
*/
const isMatchSelector = ($node: HTMLElement, selector: string): boolean => {
if (!$node) {
return false;
}
if (/^\./.test(selector)) {
const className = selector.replace(/^\./, '');
return $node && hasClass($node, className);
} else if (/^#/.test(selector)) {
const id = selector.replace(/^#/, '');
return $node && $node.id === id;
}
const tagName = selector.toUpperCase();
return $node && $node.tagName === tagName;
};
/**
* If start node and end node is the same, don't need to tranvers the dom tree.
*/
const getNodesIfSameStartEnd = (
$startNode: Text,
startOffset: number,
endOffset: number,
exceptSelectors?: string[],
) => {
let $element = $startNode as Node;
const isExcepted = ($e: HTMLElement) => exceptSelectors?.some(s => isMatchSelector($e, s));
while ($element) {
if ($element.nodeType === 1 && isExcepted($element as HTMLElement)) {
return [];
}
$element = $element.parentNode;
}
$startNode.splitText(startOffset);
const passedNode = $startNode.nextSibling as Text;
passedNode.splitText(endOffset - startOffset);
return [
{
$node: passedNode,
type: SelectedNodeType.text,
splitType: SplitType.both,
},
];
};
/**
* get all the dom nodes between the start and end node
*/
export const getSelectedNodes = (
$root: Document | HTMLElement,
start: DomNode,
end: DomNode,
exceptSelectors: string[],
): SelectedNode[] => {
const $startNode = start.$node;
const $endNode = end.$node;
const startOffset = start.offset;
const endOffset = end.offset;
// split current node when the start-node and end-node is the same
if ($startNode === $endNode && $startNode instanceof Text) {
return getNodesIfSameStartEnd($startNode, startOffset, endOffset, exceptSelectors);
}
const nodeStack: (ChildNode | Document | HTMLElement | Text)[] = [$root];
const selectedNodes: SelectedNode[] = [];
const isExcepted = ($e: HTMLElement) => exceptSelectors?.some(s => isMatchSelector($e, s));
let withinSelectedRange = false;
let curNode: Node = null;
while ((curNode = nodeStack.pop())) {
// do not traverse the excepted node
if (curNode.nodeType === 1 && isExcepted(curNode as HTMLElement)) {
continue;
}
const children = curNode.childNodes;
for (let i = children.length - 1; i >= 0; i--) {
nodeStack.push(children[i]);
}
// only collect text nodes
if (curNode === $startNode) {
if (curNode.nodeType === 3) {
(curNode as Text).splitText(startOffset);
const node = curNode.nextSibling as Text;
selectedNodes.push({
$node: node,
type: SelectedNodeType.text,
splitType: SplitType.head,
});
}
// meet the start-node (begin to traverse)
withinSelectedRange = true;
} else if (curNode === $endNode) {
if (curNode.nodeType === 3) {
const node = curNode as Text;
node.splitText(endOffset);
selectedNodes.push({
$node: node,
type: SelectedNodeType.text,
splitType: SplitType.tail,
});
}
// meet the end-node
break;
}
// handle text nodes between the range
else if (withinSelectedRange && curNode.nodeType === 3) {
selectedNodes.push({
$node: curNode as Text,
type: SelectedNodeType.text,
splitType: SplitType.none,
});
}
}
return selectedNodes;
};
const addClass = ($el: HTMLElement, className?: string[] | string): HTMLElement => {
let classNames = Array.isArray(className) ? className : [className];
classNames = classNames.length === 0 ? [getDefaultOptions().style.className] : classNames;
classNames.forEach(c => {
addElementClass($el, c);
});
return $el;
};
const isNodeEmpty = ($n: Node): boolean => !$n || !$n.textContent;
/**
* Wrap a common wrapper.
*/
const wrapNewNode = (
selected: SelectedNode,
range: HighlightRange,
className: string[] | string,
wrapTag: string,
): HTMLElement => {
const $wrap = document.createElement(wrapTag);
addClass($wrap, className);
$wrap.appendChild(selected.$node.cloneNode(false));
selected.$node.parentNode.replaceChild($wrap, selected.$node);
$wrap.setAttribute(`data-${DATASET_IDENTIFIER}`, range.id);
$wrap.setAttribute(`data-${DATASET_SPLIT_TYPE}`, selected.splitType);
$wrap.setAttribute(`data-${DATASET_IDENTIFIER_EXTRA}`, '');
return $wrap;
};
/**
* Split and wrapper each one.
*/
const wrapPartialNode = (
selected: SelectedNode,
range: HighlightRange,
className: string[] | string,
wrapTag: string,
): HTMLElement => {
const $wrap: HTMLElement = document.createElement(wrapTag);
const $parent = selected.$node.parentNode as HTMLElement;
const $prev = selected.$node.previousSibling;
const $next = selected.$node.nextSibling;
const $fr = document.createDocumentFragment();
const parentId = $parent.dataset[CAMEL_DATASET_IDENTIFIER];
const parentExtraId = $parent.dataset[CAMEL_DATASET_IDENTIFIER_EXTRA];
const extraInfo = parentExtraId ? parentId + ID_DIVISION + parentExtraId : parentId;
$wrap.setAttribute(`data-${DATASET_IDENTIFIER}`, range.id);
$wrap.setAttribute(`data-${DATASET_IDENTIFIER_EXTRA}`, extraInfo);
$wrap.appendChild(selected.$node.cloneNode(false));
let headSplit = false;
let tailSplit = false;
let splitType: SplitType;
if ($prev) {
const $span = $parent.cloneNode(false);
$span.textContent = $prev.textContent;
$fr.appendChild($span);
headSplit = true;
}
const classNameList: string[] = [];
if (Array.isArray(className)) {
classNameList.push(...className);
} else {
classNameList.push(className);
}
addClass($wrap, unique(classNameList));
$fr.appendChild($wrap);
if ($next) {
const $span = $parent.cloneNode(false);
$span.textContent = $next.textContent;
$fr.appendChild($span);
tailSplit = true;
}
if (headSplit && tailSplit) {
splitType = SplitType.both;
} else if (headSplit) {
splitType = SplitType.head;
} else if (tailSplit) {
splitType = SplitType.tail;
} else {
splitType = SplitType.none;
}
$wrap.setAttribute(`data-${DATASET_SPLIT_TYPE}`, splitType);
$parent.parentNode.replaceChild($fr, $parent);
return $wrap;
};
/**
* Just update id info (no wrapper updated).
*/
const wrapOverlapNode = (selected: SelectedNode, range: HighlightRange, className: string[] | string): HTMLElement => {
const $parent = selected.$node.parentNode as HTMLElement;
const $wrap: HTMLElement = $parent;
removeAllClass($wrap);
addClass($wrap, className);
const dataset = $parent.dataset;
const formerId = dataset[CAMEL_DATASET_IDENTIFIER];
dataset[CAMEL_DATASET_IDENTIFIER] = range.id;
dataset[CAMEL_DATASET_IDENTIFIER_EXTRA] = dataset[CAMEL_DATASET_IDENTIFIER_EXTRA]
? formerId + ID_DIVISION + dataset[CAMEL_DATASET_IDENTIFIER_EXTRA]
: formerId;
return $wrap;
};
/**
* wrap a dom node with highlight wrapper
*
* Because of supporting the highlight-overlapping,
* Highlighter can't just wrap all nodes in a simple way.
* There are three types:
* - wrapping a whole new node (without any wrapper)
* - wrapping part of the node
* - wrapping the whole wrapped node
*/
export const wrapHighlight = (
selected: SelectedNode,
range: HighlightRange,
className: string[] | string,
wrapTag: string,
): HTMLElement => {
const $parent = selected.$node.parentNode as HTMLElement;
const $prev = selected.$node.previousSibling;
const $next = selected.$node.nextSibling;
let $wrap: HTMLElement;
// text node, not in a highlight wrapper -> should be wrapped in a highlight wrapper
if (!isHighlightWrapNode($parent)) {
$wrap = wrapNewNode(selected, range, className, wrapTag);
}
// text node, in a highlight wrap -> should split the existing highlight wrapper
else if (isHighlightWrapNode($parent) && (!isNodeEmpty($prev) || !isNodeEmpty($next))) {
$wrap = wrapPartialNode(selected, range, className, wrapTag);
}
// completely overlap (with a highlight wrap) -> only add extra id info
else {
$wrap = wrapOverlapNode(selected, range, className);
}
return $wrap;
};
/**
* merge the adjacent text nodes
* .normalize() API has some bugs in IE11
*/
export const normalizeSiblingText = ($s: Node, isNext = true) => {
if (!$s || $s.nodeType !== 3) {
return;
}
const $sibling = isNext ? $s.nextSibling : $s.previousSibling;
if ($sibling.nodeType !== 3) {
return;
}
const text = $sibling.nodeValue;
$s.nodeValue = isNext ? $s.nodeValue + text : text + $s.nodeValue;
$sibling.parentNode.removeChild($sibling);
}; | the_stack |
import "jest";
import {
$util,
AppsyncContext,
ComparatorOp,
MathBinaryOp,
ResolverFunction,
ValueComparisonBinaryOp,
} from "../src";
import { reflect } from "../src/reflect";
import { appsyncTestCase, testAppsyncVelocity } from "./util";
test("empty function returning an argument", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ a: string }>) => {
return context.arguments.a;
})
);
});
test("return literal object with values", () => {
appsyncTestCase(
reflect(
(context: AppsyncContext<{ arg: string; obj: Record<string, any> }>) => {
const arg = context.arguments.arg;
const obj = context.arguments.obj;
return {
null: null,
undefined: undefined,
string: "hello",
number: 1,
["list"]: ["hello"],
obj: {
key: "value",
},
arg,
...obj,
};
}
)
);
});
test("computed property names", () => {
appsyncTestCase(
reflect(
(context: AppsyncContext<{ arg: string; obj: Record<string, any> }>) => {
const name = context.arguments.arg;
const value = name + "_test";
return {
[name]: context.arguments.arg,
[value]: context.arguments.arg,
};
}
)
);
});
test("null and undefined", () => {
appsyncTestCase(
reflect(
(_context: AppsyncContext<{ arg: string; obj: Record<string, any> }>) => {
return {
name: null,
value: undefined,
};
}
)
);
});
test("call function and return its value", () => {
appsyncTestCase(
reflect(() => {
return $util.autoId();
})
);
});
test("call function, assign to variable and return variable reference", () => {
appsyncTestCase(
reflect(() => {
const id = $util.autoId();
return id;
})
);
});
test("return in-line spread object", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ obj: { key: string } }>) => {
return {
id: $util.autoId(),
...context.arguments.obj,
};
})
);
});
test("return in-line list literal", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ a: string; b: string }>) => {
return [context.arguments.a, context.arguments.b];
})
);
});
test("return list literal variable", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ a: string; b: string }>) => {
const list = [context.arguments.a, context.arguments.b];
return list;
})
);
});
test("return list element", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ a: string; b: string }>) => {
const list = [context.arguments.a, context.arguments.b];
return list[0];
})
);
});
test("push element to array is renamed to add", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
context.arguments.list.push("hello");
return context.arguments.list;
})
);
});
// TODO https://github.com/functionless/functionless/issues/8
// test("push multiple args is expanded to multiple add calls", () => {
// const template = reflect((context: AppsyncContext<{ list: string[] }>) => {
// list.push("hello", "world");
// return list;
// });
// const vtl = new VTL();
// vtl.eval(template.body);
// const actual = vtl.toVTL();
// const expected = `$util.qr($context.arguments.list.addAll(['hello']))
// $util.qr($context.arguments.list.addAll(['world']))
// ${returnExpr("$context.arguments.list")}`;
// expect(actual).toEqual(expected);
// });
test("if statement", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
if (context.arguments.list.length > 0) {
return true;
} else {
return false;
}
})
);
});
test("return conditional expression", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return context.arguments.list.length > 0 ? true : false;
})
);
});
test("property assignment of conditional expression", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return {
prop: context.arguments.list.length > 0 ? true : false,
};
})
);
});
test("for-of loop", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
const newList = [];
for (const item of context.arguments.list) {
newList.push(item);
}
return newList;
})
);
});
test("break from for-loop", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
const newList = [];
for (const item of context.arguments.list) {
if (item === "hello") {
break;
}
newList.push(item);
}
return newList;
})
);
});
test("local variable inside for-of loop is declared as a local variable", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
const newList = [];
for (const item of context.arguments.list) {
const i = item;
newList.push(i);
}
return newList;
})
);
});
test("for-in loop and element access", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ record: Record<string, any> }>) => {
const newList = [];
for (const key in context.arguments.record) {
newList.push(context.arguments.record[key]);
}
return newList;
})
);
});
test("template expression", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ a: string }>) => {
const local = context.arguments.a;
return `head ${context.arguments.a} ${local}${context.arguments.a}`;
})
);
});
test("conditional expression in template expression", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ a: string }>) => {
return `head ${
context.arguments.a === "hello" ? "world" : context.arguments.a
}`;
})
);
});
test("map over list", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return context.arguments.list.map((item) => {
return `hello ${item}`;
});
})
);
});
test("map over list with in-line return", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return context.arguments.list.map((item) => `hello ${item}`);
})
);
});
test("chain map over list", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return context.arguments.list
.map((item) => `hello ${item}`)
.map((item) => `hello ${item}`);
})
);
});
test("chain map over list multiple array", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return context.arguments.list
.map((item, _i, _arr) => `hello ${item}`)
.map((item, _i, _arr) => `hello ${item}`);
})
);
});
test("chain map over list complex", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return context.arguments.list
.map((item, i, arr) => {
const x = i + 1;
return `hello ${item} ${x} ${arr.length}`;
})
.map((item2, ii) => `hello ${item2} ${ii}`);
})
);
});
test("forEach over list", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return context.arguments.list.forEach((item) => {
$util.error(item);
});
})
);
});
test("reduce over list with initial value", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return context.arguments.list.reduce((newList: string[], item) => {
return [...newList, item];
}, []);
})
);
});
test("reduce over list without initial value", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return context.arguments.list.reduce((str: string, item) => {
return `${str}${item}`;
});
})
);
});
test("map and reduce over list with initial value", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return context.arguments.list
.map((item) => `hello ${item}`)
.reduce((newList: string[], item) => {
return [...newList, item];
}, []);
})
);
});
test("map and reduce with array over list with initial value", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return context.arguments.list
.map((item) => `hello ${item}`)
.reduce((newList: string[], item, _i, _arr) => {
return [...newList, item];
}, []);
})
);
});
test("map and reduce and map and reduce over list with initial value", () => {
appsyncTestCase(
reflect((context: AppsyncContext<{ list: string[] }>) => {
return context.arguments.list
.map((item) => `hello ${item}`)
.reduce((newList: string[], item) => {
return [...newList, item];
}, [])
.map((item) => `hello ${item}`)
.reduce((newList: string[], item) => {
return [...newList, item];
}, []);
})
);
});
test("$util.time.nowISO8601", () => {
appsyncTestCase(
reflect(() => {
return $util.time.nowISO8601();
})
);
});
test("$util.log.info(message)", () => {
appsyncTestCase(
reflect(() => {
return $util.log.info("hello world");
})
);
});
test("$util.log.info(message, ...Object)", () => {
appsyncTestCase(
reflect(() => {
return $util.log.info("hello world", { a: 1 }, { b: 2 });
})
);
});
test("$util.log.error(message)", () => {
appsyncTestCase(
reflect(() => {
return $util.log.error("hello world");
})
);
});
test("$util.log.error(message, ...Object)", () => {
appsyncTestCase(
reflect(() => {
return $util.log.error("hello world", { a: 1 }, { b: 2 });
})
);
});
test("BinaryExpr and UnaryExpr are evaluated to temporary variables", () => {
appsyncTestCase(
reflect(() => {
return {
x: -1,
y: -(1 + 1),
z: !(true && false),
};
})
);
});
test("binary expr in", () => {
const templates = appsyncTestCase(
reflect<
ResolverFunction<{ key: string } | { key2: string }, { out: string }, any>
>(($context) => {
if ("key" in $context.arguments) {
return { out: $context.arguments.key };
}
return { out: $context.arguments.key2 };
})
);
testAppsyncVelocity(templates[1], {
arguments: { key: "hi" },
resultMatch: { out: "hi" },
});
// falsey value
testAppsyncVelocity(templates[1], {
arguments: { key: "" },
resultMatch: { out: "" },
});
testAppsyncVelocity(templates[1], {
arguments: { key2: "hello" },
resultMatch: { out: "hello" },
});
});
test("binary expr ==", () => {
const templates = appsyncTestCase(
reflect<ResolverFunction<{ key: string }, { out: boolean[] }, any>>(
($context) => {
return {
out: [
$context.arguments.key == "key",
"key" == $context.arguments.key,
],
};
}
)
);
testAppsyncVelocity(templates[1], {
arguments: { key: "key" },
resultMatch: { out: [true, true] },
});
});
test("binary expr in map", () => {
const templates = appsyncTestCase(
reflect<ResolverFunction<{}, { in: boolean; notIn: boolean }, any>>(() => {
const obj = {
key: "value",
// $null does not appear to work in amplify simulator
// keyNull: null,
keyEmpty: "",
};
return {
in: "key" in obj,
notIn: "otherKey" in obj,
// inNull: "keyNull" in obj,
inEmpty: "keyEmpty" in obj,
};
})
);
testAppsyncVelocity(templates[1], {
resultMatch: {
in: true,
notIn: false,
// inNull: true,
inEmpty: true,
},
});
});
// amplify simulator does not support .class
// https://github.com/aws-amplify/amplify-cli/issues/10575
test.skip("binary expr in array", () => {
const templates = appsyncTestCase(
reflect<ResolverFunction<{ arr: string[] }, { out: string }, any>>(
($context) => {
if (1 in $context.arguments.arr) {
return { out: $context.arguments.arr[1] };
}
return { out: $context.arguments.arr[0] };
}
)
);
testAppsyncVelocity(templates[1], {
arguments: { arr: ["1", "2"] },
resultMatch: { out: "2" },
});
testAppsyncVelocity(templates[1], {
arguments: { arr: ["1", ""] },
resultMatch: { out: "" },
});
testAppsyncVelocity(templates[1], {
arguments: { arr: ["1"] },
resultMatch: { out: "1" },
});
});
test("binary exprs value comparison", () => {
const templates = appsyncTestCase(
reflect<
ResolverFunction<
{ a: number; b: number },
Record<ValueComparisonBinaryOp, boolean>,
any
>
>(($context) => {
const a = $context.arguments.a;
const b = $context.arguments.b;
return {
"!=": a != b,
"&&": a && b,
"||": a || b,
"<": a < b,
"<=": a <= b,
"==": a == b,
">": a > b,
">=": a >= b,
};
})
);
testAppsyncVelocity(templates[1], {
arguments: { a: 1, b: 2 },
resultMatch: {
"!=": true,
"<": true,
"<=": true,
"==": false,
">": false,
">=": false,
},
});
testAppsyncVelocity(templates[1], {
arguments: { a: 2, b: 1 },
resultMatch: {
"!=": true,
"<": false,
"<=": false,
"==": false,
">": true,
">=": true,
},
});
testAppsyncVelocity(templates[1], {
arguments: { a: 1, b: 1 },
resultMatch: {
"!=": false,
"<": false,
"<=": true,
"==": true,
">": false,
">=": true,
},
});
});
test("binary exprs logical", () => {
const templates = appsyncTestCase(
reflect<
ResolverFunction<
{ a: boolean; b: boolean },
Record<ComparatorOp, boolean>,
any
>
>(($context) => {
const a = $context.arguments.a;
const b = $context.arguments.b;
return {
"&&": a && b,
"||": a || b,
};
})
);
testAppsyncVelocity(templates[1], {
arguments: { a: true, b: true },
resultMatch: {
"&&": true,
"||": true,
},
});
testAppsyncVelocity(templates[1], {
arguments: { a: true, b: false },
resultMatch: {
"&&": false,
"||": true,
},
});
testAppsyncVelocity(templates[1], {
arguments: { a: false, b: false },
resultMatch: {
"&&": false,
"||": false,
},
});
});
test("binary exprs math", () => {
const templates = appsyncTestCase(
reflect<
ResolverFunction<
{ a: number; b: number },
Record<MathBinaryOp, number>,
any
>
>(($context) => {
const a = $context.arguments.a;
const b = $context.arguments.b;
return {
"+": a + b,
"-": a - b,
"*": a * b,
"/": a / b,
};
})
);
testAppsyncVelocity(templates[1], {
arguments: { a: 6, b: 2 },
resultMatch: {
"+": 8,
"-": 4,
"*": 12,
"/": 3,
},
});
});
test("binary expr =", () => {
const templates = appsyncTestCase(
reflect<ResolverFunction<{ key: string }, { out: string }, any>>(
($context) => {
if ($context.arguments.key == "help me") {
$context.arguments.key = "hello";
}
if ($context.arguments.key == "hello") {
return { out: "ohh hi" };
}
return { out: "wot" };
}
)
);
testAppsyncVelocity(templates[1], {
arguments: { key: "hello" },
resultMatch: { out: "ohh hi" },
});
testAppsyncVelocity(templates[1], {
arguments: { key: "giddyup" },
resultMatch: { out: "wot" },
});
testAppsyncVelocity(templates[1], {
arguments: { key: "help me" },
resultMatch: { out: "ohh hi" },
});
});
// https://github.com/functionless/functionless/issues/232
test.skip("binary expr +=", () => {
const templates = appsyncTestCase(
reflect<ResolverFunction<{ key: string }, { out: number }, any>>(
($context) => {
var n = 0;
if ($context.arguments.key == "hello") {
n += 1;
}
return { out: n };
}
)
);
testAppsyncVelocity(templates[1], {
arguments: { key: "hello" },
resultMatch: { out: 1 },
});
testAppsyncVelocity(templates[1], {
arguments: { key: "giddyup" },
resultMatch: { out: 0 },
});
}); | the_stack |
import { keys, values } from "./Dict";
import { zip } from "./ZipUnzip";
export class Option<A> {
/**
* Create an Option.Some value
*/
static Some = <A = never>(value: A): Option<A> => {
const option = Object.create(protoOption) as Option<A>;
option.value = { tag: "Some", value };
return option;
};
/**
* Create an Option.None value
*/
static None = <A = never>(): Option<A> => {
return NONE as Option<A>;
};
/**
* Create an Option from a nullable value
*/
static fromNullable = <A>(nullable: A) => {
if (nullable == null) {
return Option.None<NonNullable<A>>();
} else {
return Option.Some<NonNullable<A>>(nullable as NonNullable<A>);
}
};
/**
* Create an Option from a null | value
*/
static fromNull = <A>(nullable: A) => {
if (nullable === null) {
return Option.None<Exclude<A, null>>();
} else {
return Option.Some<Exclude<A, null>>(nullable as Exclude<A, null>);
}
};
/**
* Create an Option from a undefined | value
*/
static fromUndefined = <A>(nullable: A) => {
if (nullable === undefined) {
return Option.None<Exclude<A, undefined>>();
} else {
return Option.Some<Exclude<A, undefined>>(
nullable as Exclude<A, undefined>,
);
}
};
/**
* Turns an array of options into an option of array
*/
static all = <Options extends readonly Option<any>[] | []>(
options: Options,
): Option<{
-readonly [P in keyof Options]: Options[P] extends Option<infer V>
? V
: never;
}> => {
const length = options.length;
let acc = Option.Some<Array<unknown>>([]);
let index = 0;
while (true) {
if (index >= length) {
return acc as unknown as Option<{
-readonly [P in keyof Options]: Options[P] extends Option<infer V>
? V
: never;
}>;
}
const item = options[index] as Option<unknown>;
acc = acc.flatMap((array) => {
return item.map((value) => {
array.push(value);
return array;
});
});
index++;
}
};
/**
* Turns an dict of options into a options of dict
*/
static allFromDict = <Dict extends Record<string, Option<any>>>(
dict: Dict,
): Option<{
-readonly [P in keyof Dict]: Dict[P] extends Option<infer T> ? T : never;
}> => {
const dictKeys = keys(dict);
return Option.all(values(dict)).map((values) =>
Object.fromEntries(zip(dictKeys, values)),
);
};
static equals = <A>(
a: Option<A>,
b: Option<A>,
equals: (a: A, b: A) => boolean,
) => {
if (a.isSome() && b.isSome()) {
return equals(a.value.value, b.value.value);
}
return a.value.tag === b.value.tag;
};
static pattern = {
Some: <T>(x: T) => ({ value: { tag: "Some", value: x } } as const),
None: { value: { tag: "None" } } as const,
};
value: { tag: "Some"; value: A } | { tag: "None" };
constructor() {
this.value = { tag: "None" };
}
/**
* Returns the Option containing the value from the callback
*
* (Option\<A>, A => B) => Option\<B>
*/
map<B>(f: (value: A) => B): Option<B> {
if (this.value.tag === "Some") {
return Option.Some(f(this.value.value));
} else {
return this as unknown as Option<B>;
}
}
/**
* Returns the Option containing the value from the callback
*
* (Option\<A>, A => Option\<B>) => Option\<B>
*/
flatMap<B>(f: (value: A) => Option<B>): Option<B> {
if (this.value.tag === "Some") {
return f(this.value.value);
} else {
return this as unknown as Option<B>;
}
}
/**
* Return the value if present, and the fallback otherwise
*
* (Option\<A>, A) => A
*/
getWithDefault(defaultValue: A): A {
if (this.value.tag === "Some") {
return this.value.value;
} else {
return defaultValue;
}
}
/**
* Explodes the Option given its case
*/
match<B>(config: { Some: (value: A) => B; None: () => B }): B {
if (this.value.tag === "Some") {
return config.Some(this.value.value);
} else {
return config.None();
}
}
/**
* Runs the callback and returns `this`
*/
tap(func: (option: Option<A>) => unknown): Option<A> {
func(this);
return this;
}
/**
* Converts the Option\<A> to a `A | undefined`
*/
toUndefined() {
if (this.value.tag === "None") {
return undefined;
} else {
return this.value.value;
}
}
/**
* Converts the Option\<A> to a `A | null`
*/
toNull() {
if (this.value.tag === "None") {
return null;
} else {
return this.value.value;
}
}
/**
* Takes the option and turns it into Ok(value) is Some, or Error(valueWhenNone)
*/
toResult<E>(valueWhenNone: E): Result<A, E> {
return this.match({
Some: (ok) => Result.Ok(ok),
None: () => Result.Error(valueWhenNone),
});
}
/**
* Typeguard
*/
isSome(): this is Option<A> & { value: { tag: "Some"; value: A } } {
return this.value.tag === "Some";
}
/**
* Typeguard
*/
isNone(): this is Option<A> & { value: { tag: "None" } } {
return this.value.tag === "None";
}
/**
* Returns the value. Use within `if (option.isSome()) { ... }`
*/
get(this: Option<A> & { value: { tag: "Some"; value: A } }): A {
return this.value.value;
}
}
// @ts-expect-error
Option.prototype.__boxed_type__ = "Option";
const protoOption = Object.create(
null,
Object.getOwnPropertyDescriptors(Option.prototype),
);
const NONE = (() => {
const none = Object.create(protoOption);
none.value = { tag: "None" };
return none;
})();
export class Result<A, E> {
/**
* Create an Result.Ok value
*/
static Ok = <A = never, E = never>(ok: A): Result<A, E> => {
const result = Object.create(protoResult) as Result<A, E>;
result.value = { tag: "Ok", value: ok };
return result;
};
/**
* Create an Result.Error value
*/
static Error = <A = never, E = never>(error: E): Result<A, E> => {
const result = Object.create(protoResult) as Result<A, E>;
result.value = { tag: "Error", value: error };
return result;
};
/**
* Runs the function and resolves a result of its return value, or to an error if thrown
*/
static fromExecution = <A, E = unknown>(func: () => A): Result<A, E> => {
try {
return Result.Ok(func());
} catch (err) {
return Result.Error(err) as Result<A, E>;
}
};
/**
* Takes the promise and resolves a result of its value, or to an error if rejected
*/
static async fromPromise<A, E = unknown>(
promise: Promise<A>,
): Promise<Result<A, E>> {
try {
const value = await promise;
return Result.Ok<A, E>(value);
} catch (err) {
return Result.Error<A, E>(err as E);
}
}
/**
* Takes the option and turns it into Ok(value) is Some, or Error(valueWhenNone)
*/
static fromOption<A, E>(option: Option<A>, valueWhenNone: E): Result<A, E> {
return option.toResult(valueWhenNone);
}
/**
* Turns an array of results into an result of array
*/
static all = <Results extends readonly Result<any, any>[] | []>(
results: Results,
): Result<
{
-readonly [P in keyof Results]: Results[P] extends Result<infer V, any>
? V
: never;
},
{
-readonly [P in keyof Results]: Results[P] extends Result<any, infer E>
? E
: never;
}[number]
> => {
const length = results.length;
let acc = Result.Ok<Array<unknown>, unknown>([]);
let index = 0;
while (true) {
if (index >= length) {
return acc as unknown as Result<
{
-readonly [P in keyof Results]: Results[P] extends Result<
infer V,
any
>
? V
: never;
},
{
-readonly [P in keyof Results]: Results[P] extends Result<
any,
infer E
>
? E
: never;
}[number]
>;
}
const item = results[index] as Result<unknown, unknown>;
acc = acc.flatMap((array) => {
return item.map((value) => {
array.push(value);
return array;
});
});
index++;
}
};
/**
* Turns an dict of results into a results of dict
*/
static allFromDict = <Dict extends Record<string, Result<any, any>>>(
dict: Dict,
): Result<
{
-readonly [P in keyof Dict]: Dict[P] extends Result<infer T, any>
? T
: never;
},
{
-readonly [P in keyof Dict]: Dict[P] extends Result<any, infer E>
? E
: never;
}[keyof Dict]
> => {
const dictKeys = keys(dict);
return Result.all(values(dict)).map((values) =>
Object.fromEntries(zip(dictKeys, values)),
);
};
static equals = <A, E>(
a: Result<A, E>,
b: Result<A, E>,
equals: (a: A, b: A) => boolean,
) => {
if (a.value.tag !== b.value.tag) {
return false;
}
if (a.isError() && b.isError()) {
return true;
}
return equals(a.value.value as unknown as A, b.value.value as unknown as A);
};
static pattern = {
Ok: <T>(x: T) => ({ value: { tag: "Ok", value: x } } as const),
Error: <T>(x: T) => ({ value: { tag: "Error", value: x } } as const),
};
value: { tag: "Ok"; value: A } | { tag: "Error"; value: E };
constructor() {
this.value = { tag: "Error", value: undefined as unknown as E };
}
/**
* Returns the Result containing the value from the callback
*
* (Result\<A, E>, A => B) => Result\<B>
*/
map<B>(f: (value: A) => B): Result<B, E> {
if (this.value.tag === "Ok") {
return Result.Ok(f(this.value.value));
} else {
return this as unknown as Result<B, E>;
}
}
/**
* Returns the Result containing the error returned from the callback
*
* (Result\<A, E>, E => F) => Result\<F>
*/
mapError<F>(f: (value: E) => F): Result<A, F> {
if (this.value.tag === "Ok") {
return this as unknown as Result<A, F>;
} else {
return Result.Error(f(this.value.value));
}
}
/**
* Returns the Result containing the value from the callback
*
* (Result\<A, E>, A => Result\<B, F>) => Result\<B, E | F>
*/
flatMap<B, F = E>(f: (value: A) => Result<B, F>): Result<B, F | E> {
if (this.value.tag === "Ok") {
return f(this.value.value);
} else {
return this as unknown as Result<B, F | E>;
}
}
/**
* Returns the Result containing the value from the callback
*
* (Result\<A, E>, E => Result\<A, F>) => Result\<A | B, F>
*/
flatMapError<B, F>(f: (value: E) => Result<B, F>): Result<A | B, F> {
if (this.value.tag === "Ok") {
return this as unknown as Result<A | B, F>;
} else {
return f(this.value.value);
}
}
/**
* Return the value if present, and the fallback otherwise
*
* (Result\<A, E>, A) => A
*/
getWithDefault(defaultValue: A): A {
if (this.value.tag === "Ok") {
return this.value.value;
} else {
return defaultValue;
}
}
/**
* Explodes the Result given its case
*/
match<B>(config: { Ok: (value: A) => B; Error: (error: E) => B }): B {
if (this.value.tag === "Ok") {
return config.Ok(this.value.value);
} else {
return config.Error(this.value.value);
}
}
/**
* Runs the callback and returns `this`
*/
tap(func: (result: Result<A, E>) => unknown): Result<A, E> {
func(this);
return this;
}
/**
* Runs the callback if ok and returns `this`
*/
tapOk(func: (value: A) => unknown): Result<A, E> {
if (this.isOk()) {
func(this.value.value);
}
return this;
}
/**
* Runs the callback if error and returns `this`
*/
tapError(func: (error: E) => unknown): Result<A, E> {
if (this.isError()) {
func(this.value.value);
}
return this;
}
/**
* Typeguard
*/
isOk(): this is Result<A, E> & { value: { tag: "Ok"; value: A } } {
return this.value.tag === "Ok";
}
/**
* Typeguard
*/
isError(): this is Result<A, E> & {
value: { tag: "Error"; value: E };
} {
return this.value.tag === "Error";
}
/**
* Return an option of the value
*
* (Result\<A, E>) => Option\<A>
*/
toOption(): Option<A> {
if (this.value.tag === "Ok") {
return Option.Some(this.value.value) as Option<A>;
} else {
return Option.None() as Option<A>;
}
}
/**
* Returns the ok value. Use within `if (result.isOk()) { ... }`
*/
get(this: Result<A, E> & { value: { tag: "Ok"; value: A } }): A {
return this.value.value;
}
/**
* Returns the error value. Use within `if (result.isError()) { ... }`
*/
getError(this: Result<A, E> & { value: { tag: "Error"; value: E } }): E {
return this.value.value;
}
}
// @ts-expect-error
Result.prototype.__boxed_type__ = "Result";
const protoResult = Object.create(
null,
Object.getOwnPropertyDescriptors(Result.prototype),
); | the_stack |
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { Component } from '@angular/core';
import { FOCUS_TRAP_DIRECTIVES } from '../focus-trap/mdc.focus-trap.directive';
import { DRAWER_DIRECTIVES } from './mdc.drawer.directive';
import { LIST_DIRECTIVES } from '../list/mdc.list.directive';
import { simulateKey } from '../../testutils/page.test';
const templateWithDrawer = `
<aside [mdcDrawer]="type" [(open)]="open" id=drawer
(openChange)="notify('open', $event)"
(afterOpened)="notify('afterOpened', true)"
(afterClosed)="notify('afterClosed', true)"
>
<div mdcDrawerContent>
<nav mdcList>
<a *ngFor="let item of items" mdcListItem href="javascript:void(0)">
<i mdcListItemGraphic class="material-icons">{{item.icon}}</i>
<span mdcListItemText>{{item.text}}</span>
</a>
</nav>
</div>
</aside>
<div *ngIf="type === 'modal'" mdcDrawerScrim id="scrim"></div>
<div [mdcDrawerAppContent]="type === 'dismissible'" id="appContent">app content</div>
`;
describe('MdcDrawerDirective', () => {
@Component({
template: templateWithDrawer
})
class TestComponent {
notifications = [];
open = false;
type: 'permanent' | 'dismissible' | 'modal' = 'permanent';
items = [
{icon: 'inbox', text: 'Inbox'},
{icon: 'send', text: 'Outgoing'},
{icon: 'drafts', text: 'Drafts'},
];
notify(name: string, value: boolean) {
let notification = {};
notification[name] = value;
this.notifications.push(notification);
}
}
function setup(type: 'permanent' | 'dismissible' | 'modal', open = false) {
const fixture = TestBed.configureTestingModule({
declarations: [...DRAWER_DIRECTIVES, ...FOCUS_TRAP_DIRECTIVES, ...LIST_DIRECTIVES, TestComponent]
}).createComponent(TestComponent);
const testComponent = fixture.debugElement.injector.get(TestComponent);
testComponent.type = type;
testComponent.open = open;
fixture.detectChanges();
const drawer: HTMLElement = fixture.nativeElement.querySelector('#drawer');
const appContent: HTMLElement = fixture.nativeElement.querySelector('#appContent');
if (open)
animationCycle(drawer);
//const mdcDrawer = fixture.debugElement.query(By.directive(MdcDrawerDirective)).injector.get(MdcDrawerDirective);
return { fixture, testComponent, drawer, appContent };
}
it('dismissible: structure', fakeAsync(() => {
const { fixture, testComponent, drawer, appContent } = setup('dismissible');
validateDom(drawer, {
type: 'dismissible',
open: false
});
testComponent.open = true;
fixture.detectChanges();
animationCycle(drawer);
validateDom(drawer, {
type: 'dismissible'
});
expect(appContent.classList).toContain('mdc-drawer-app-content');
}));
it('modal: structure', fakeAsync(() => {
const { fixture, testComponent, drawer, appContent } = setup('modal');
validateDom(drawer, {
type: 'modal',
open: false
});
testComponent.open = true;
fixture.detectChanges();
animationCycle(drawer);
validateDom(drawer, {
type: 'modal'
});
expect(appContent.classList).not.toContain('mdc-drawer-app-content');
}));
it('permanent: structure', fakeAsync(() => {
const { fixture, drawer, appContent } = setup('permanent');
fixture.detectChanges();
validateDom(drawer, {
type: 'permanent',
open: true
});
expect(appContent.classList).not.toContain('mdc-drawer-app-content');
}));
it('close while opening is handled correctly', fakeAsync(() => {
const { fixture, testComponent, drawer } = setup('modal', true);
testComponent.open = false;
animationCycle(drawer);
// the first animationCycle completes the opening transition:
validateDom(drawer, {
type: 'modal',
open: true
});
fixture.detectChanges();
animationCycle(drawer);
// the next animationCycle completes the closing transition:
validateDom(drawer, {
type: 'modal',
open: false
});
}));
it('modal: should trap focus to the drawer when opened', fakeAsync(() => {
const { fixture, testComponent, drawer } = setup('modal', true);
// when open: should have focus trap sentinels:
expect([...fixture.nativeElement.querySelectorAll('.mdc-dom-focus-sentinel')].length).toBe(2);
testComponent.open = false;
fixture.detectChanges();
animationCycle(drawer);
// focus trap should be cleaned up:
expect([...fixture.nativeElement.querySelectorAll('.mdc-dom-focus-sentinel')].length).toBe(0);
}));
it('modal: clicking scrim closes the modal', fakeAsync(() => {
const { fixture, drawer } = setup('modal', true);
validateDom(drawer, {type: 'modal', open: true});
const scrim = fixture.nativeElement.querySelector('#scrim');
scrim.click();
animationCycle(drawer);
validateDom(drawer, {type: 'modal', open: false});
}));
it('modal: ESCAPE closes the modal', fakeAsync(() => {
const { drawer } = setup('modal', true);
validateDom(drawer, {type: 'modal', open: true});
simulateKey(drawer, 'Escape');
animationCycle(drawer);
validateDom(drawer, {type: 'modal', open: false});
}));
it('modal: should emit the afterOpened/afterClosed/openChange events', fakeAsync(() => {
const { fixture, testComponent, drawer } = setup('modal', false);
expect(testComponent.notifications).toEqual([]);
testComponent.open = true;
fixture.detectChanges(); animationCycle(drawer);
expect(testComponent.notifications).toEqual([
{open: true},
{afterOpened: true}
]);
testComponent.notifications = [];
testComponent.open = false;
fixture.detectChanges(); animationCycle(drawer);
expect(testComponent.notifications).toEqual([
{open: false},
{afterClosed: true}
]);
}));
it('dismissible: should emit the afterOpened/afterClosed/openChange events', fakeAsync(() => {
const { fixture, testComponent, drawer } = setup('dismissible', false);
expect(testComponent.notifications).toEqual([]);
testComponent.open = true;
fixture.detectChanges(); animationCycle(drawer);
expect(testComponent.notifications).toEqual([
{open: true},
{afterOpened: true}
]);
testComponent.notifications = [];
testComponent.open = false;
fixture.detectChanges(); animationCycle(drawer);
expect(testComponent.notifications).toEqual([
{open: false},
{afterClosed: true}
]);
}));
it('change type from dismissible to modal when open', fakeAsync(() => {
const { fixture, testComponent, drawer } = setup('dismissible', true);
validateDom(drawer, {
type: 'dismissible'
});
document.body.focus(); // make sure the drawer is not focused (trapFocus must be called and focus it when changin type)
expect(document.activeElement).toBe(document.body);
testComponent.type = 'modal';
fixture.detectChanges(); animationCycle(drawer);
validateDom(drawer, {
type: 'modal'
});
}));
it('change type from permanent to modal when open is set', fakeAsync(() => {
const { fixture, testComponent, drawer } = setup('permanent', true);
validateDom(drawer, {
type: 'permanent'
});
document.body.focus(); // make sure the drawer is not focused (trapFocus must be called and focus it when changin type)
expect(document.activeElement).toBe(document.body);
testComponent.type = 'modal';
fixture.detectChanges(); animationCycle(drawer);
validateDom(drawer, {
type: 'modal',
open: true
});
}));
function validateDom(drawer, options: Partial<{
type: 'permanent' | 'dismissible' | 'modal',
open: boolean,
list: boolean
}> = {}) {
options = {...{
type: 'permanent',
open: true,
list: true
}, ...options};
expect(drawer.classList).toContain('mdc-drawer');
expect(drawer.classList).not.toContain('mdc-drawer--animate');
expect(drawer.classList).not.toContain('mdc-drawer--opening');
expect(drawer.classList).not.toContain('mdc-drawer--closing');
switch (options.type) {
case 'dismissible':
expect(drawer.classList).toContain('mdc-drawer--dismissible');
expect(drawer.classList).not.toContain('mdc-drawer--modal');
break;
case 'modal':
expect(drawer.classList).toContain('mdc-drawer--modal');
expect(drawer.classList).not.toContain('mdc-drawer--dismissible');
break;
default:
expect(drawer.classList).not.toContain('mdc-drawer--modal');
expect(drawer.classList).not.toContain('mdc-drawer--dismissible');
}
if (options.open && options.type !== 'permanent')
expect(drawer.classList).toContain('mdc-drawer--open');
else
expect(drawer.classList).not.toContain('mdc-drawer--open');
// when modal and open, there are focus-trap sentinel children:
expect(drawer.children.length).toBe(options.open && options.type === 'modal' ? 3 : 1);
const content = drawer.children[options.open && options.type === 'modal' ? 1 : 0];
expect(content.classList).toContain('mdc-drawer__content');
if (options.list) {
expect(content.children.length).toBe(1);
const list = content.children[0];
expect(list.classList).toContain('mdc-list');
}
if (options.open && options.type === 'modal') {
let drawerIsActive = false;
let active = document.activeElement;
while (active) {
if (active === drawer) {
drawerIsActive = true;
break;
}
active = active.parentElement;
}
expect(drawerIsActive).toBeTrue();
}
}
function animationCycle(drawer: HTMLElement) {
tick(20);
if (drawer.classList.contains('mdc-drawer--dismissible') || drawer.classList.contains('mdc-drawer--modal')) {
let event = new TransitionEvent('transitionend');
event.initEvent('transitionend', true, true);
drawer.dispatchEvent(event);
}
}
function newKeydownEvent(key: string) {
let event = new KeyboardEvent('keydown', {key});
event.initEvent('keydown', true, true);
return event;
}
}); | the_stack |
module CorsicaTests {
"use strict";
var glob;
function isWinRTEnabled() {
if (window && window['Windows']) {
glob = Windows.Globalization;
return true;
}
return false;
}
function process(root) {
return WinJS.UI.processAll(root);
}
// returns string with leading zero prepended for values < 10
function addLeadingZero(value) {
if (value < 10) {
return '0' + value.toString();
} else {
return value.toString();
}
}
function createPicker(options) {
var dp = document.createElement('div');
dp.setAttribute('data-win-control', 'WinJS.UI.TimePicker');
if (options !== undefined) {
dp.setAttribute('data-win-options', JSON.stringify(options));
}
// NOTE: The datetime UI is created in a deferred UI manner so
// we need to have the timeout to allow the browser to go through
// a few cycles.
return process(dp).then(function () {
return WinJS.Promise.timeout().then(
function () { return dp; });
});
}
var elementToBeRemoved;
function createPickerWithAppend(options?) {
var dp = document.createElement('div');
document.body.appendChild(dp);
elementToBeRemoved = dp;
dp.setAttribute('data-win-control', 'WinJS.UI.TimePicker');
if (options !== undefined) {
dp.setAttribute('data-win-options', JSON.stringify(options));
}
// NOTE: The datetime UI is created in a deferred UI manner so
// we need to have the timeout to allow the browser to go through
// a few cycles.
return process(dp).then(function () {
return WinJS.Promise.timeout().then(
function () { return dp; });
});
}
// return the select element containing the hour component
function hourElement(picker) {
return picker.querySelector('.win-timepicker .win-timepicker-hour');
}
// return the select element containing the minute component
function minuteElement(picker) {
return picker.querySelector('.win-timepicker .win-timepicker-minute');
}
// return the select element containing the period component
function periodElement(picker) {
return picker.querySelector('.win-timepicker .win-timepicker-period');
}
function timeToString(time) {
return "[h=" + time.hour + ", m=" + time.minute + ", period=" + time.period + "]";
}
function addChangeEvent(picker) {
picker.addEventListener("change", checkValues);
return function () { picker.removeEventListener("change", checkValues); };
}
var hourBackEnd, minuteBackEnd;
var AM = 0, PM = 1;
function setHours(picker, h, notFire = false) {
var selectHourElement = hourElement(picker);
hourBackEnd = h;
selectHourElement.value = hourBackEnd;
var selectPeriodElement = periodElement(picker);
if (selectPeriodElement && selectPeriodElement.selectedIndex === PM && hourBackEnd < 12) {
hourBackEnd += 12;
} else if (selectPeriodElement && selectPeriodElement.selectedIndex === AM && hourBackEnd === 12) {
hourBackEnd -= 12;
}
if (!notFire) {
fireOnchange(selectHourElement);
}
}
function setPeriod(picker, p, notFire = false) {
var selectPeriodElement = periodElement(picker);
if (p === PM && hourBackEnd < 12) {
hourBackEnd += 12;
}
else if (p === AM && hourBackEnd >= 12) {
hourBackEnd -= 12;
}
selectPeriodElement.selectedIndex = p;
if (!notFire) {
fireOnchange(selectPeriodElement);
}
}
function setMinutes(picker, m, notFire = false) {
var selectMinuteElement = minuteElement(picker);
minuteBackEnd = m;
selectMinuteElement.selectedIndex = minuteBackEnd;
if (!notFire) {
fireOnchange(selectMinuteElement);
}
}
function setValues() {
var today = new Date();
hourBackEnd = today.getHours();
minuteBackEnd = today.getMinutes();
}
var timePicker;
function checkValues(e) {
var d = new Date(timePicker.winControl.current);
LiveUnit.Assert.areEqual(hourBackEnd, d.getHours(), "The backend date object has a wrong hour value");
LiveUnit.Assert.areEqual(minuteBackEnd, d.getMinutes(), "The backend date object has a wrong minute value");
}
function cleanupTimePicker() {
try {
WinJS.Utilities.disposeSubTree(elementToBeRemoved);
document.body.removeChild(elementToBeRemoved);
} catch (e) {
LiveUnit.Assert.fail("cleanupTimePicker() failed: " + e);
}
}
// time object can contain values for 'hour', 'minute', 'period'. If any of these values
// is not present, function will expect querySelector to return null for that cell.
function verifyTime(picker, time) {
LiveUnit.LoggingCore.logComment("picker.winControl.current=" + picker.winControl.current + "; expected=" + timeToString(time));
var periodControl = isPeriodControl();
if ('period' in time && !periodControl && 'hour' in time) {
if (time.period.toUpperCase() === "PM") {
if (time.hour < 12) { time.hour = (parseInt(time.hour) + 12) + ''; }
}
else {
if (time.hour === 12) { time.hour = "0"; }
}
}
if ('hour' in time) {
LiveUnit.Assert.areEqual(time.hour.toString() >> 0, hourElement(picker).value >> 0);
} else {
LiveUnit.Assert.areEqual(null, hourElement(picker).value);
}
if ('minute' in time) {
LiveUnit.Assert.areEqual(time.minute.toString() >> 0, minuteElement(picker).value >> 0);
} else {
LiveUnit.Assert.areEqual(null, minuteElement(picker).value);
}
if ('period' in time && periodControl) {
LiveUnit.Assert.areEqual(time.period.toString() >> 0, periodElement(picker).value >> 0);
} else {
LiveUnit.Assert.areEqual(null, periodElement(picker));
}
}
// given an integer hour, return appropriate 'am' or 'pm' value
// TODO: make local smart
function calcPeriod(hour) {
if (hour < 12) {
return 'AM';
} else {
return 'PM';
}
}
function unhandledTestError(msg) {
try {
LiveUnit.Assert.fail("unhandled test exception: " + msg);
} catch (ex) {
// don't rethrow assertion failure exception
}
}
// returns the text from the selected option of the specified select control
function getText(selectElement) {
return selectElement.options[selectElement.selectedIndex].text;
}
function isPeriodControl() {
if (isWinRTEnabled()) {
var calendar = new Windows.Globalization.Calendar();
var computedClock = calendar.getClock();
return (computedClock !== "24HourClock");
}
return true;
}
var changeHit = 0;
var changeType = "change";
function logEventHits(e) {
LiveUnit.LoggingCore.logComment(e.type + ": changeHit=" + changeHit);
}
var changeHandler = function (e) {
changeHit++;
LiveUnit.Assert.areEqual(e.type, changeType);
logEventHits(e);
};
function attachEventListeners(picker) {
changeHit = 0;
picker.addEventListener(changeType, changeHandler, false);
return function () { changeHit = 0; picker.removeEventListener(changeType, changeHandler, false); };
}
// fire a 'change' event on the provided target element
function fireOnchange(targetElement) {
var myEvent = document.createEvent('HTMLEvents');
myEvent.initEvent('change', true, false);
targetElement.dispatchEvent(myEvent);
}
function checkPeriodControlValue(expectedValue, control, force?) {
if (force || isPeriodControl()) {
LiveUnit.Assert.areEqual(expectedValue, control.value, "period element was set incorrectly");
}
else {
LiveUnit.Assert.areEqual(null, control, "period element should not be there");
}
}
function getActualUIOrder() {
var minutePos, periodPos, hourPos;
var domElement = <HTMLElement>document.getElementsByClassName('win-timepicker')[0];
for (var i = 0; i < domElement.children.length; i++) {
var elem = (<HTMLElement>domElement.childNodes[i]).className;
if (elem.indexOf('picker-hour') !== -1) {
hourPos = i;
}
else if (elem.indexOf('picker-minute') !== -1) {
minutePos = i;
}
else {
periodPos = i;
}
}
return getOrder(hourPos, minutePos, periodPos);
}
function getOrder(hourPos, minutePos, periodPos) {
if (!periodPos && periodPos !== 0) {
if (hourPos < minutePos) {
return "HM";
}
return "MH";
}
else if (minutePos < periodPos && minutePos < hourPos) {
if (periodPos < hourPos) {
return "MPH";
}
else {
return "MHP";
}
}
else if (periodPos < minutePos && periodPos < hourPos) {
if (minutePos < hourPos) {
return "PMH";
}
else {
return "PHM";
}
}
else {
if (periodPos < minutePos) {
return "HPM";
}
else {
return "HMP";
}
}
}
function getExpectedOrder(calendar, clock) {
var dtf = Windows.Globalization.DateTimeFormatting;
var s = "hour minute";
var c = new dtf.DateTimeFormatter(s);
c = new dtf.DateTimeFormatter(s);
var formatter = new dtf.DateTimeFormatter(s, c.languages, c.geographicRegion, calendar, clock);
var pattern = formatter.patterns[0];
var hourIndex = pattern.indexOf("hour");
var minuteIndex = pattern.indexOf("minute");
var periodIndex = pattern.indexOf("period");
if (periodIndex === -1) {
periodIndex = null;
}
return getOrder(hourIndex, minuteIndex, periodIndex);
}
function getControls(picker) {
return { hourSelect: hourElement(picker), minuteSelect: minuteElement(picker), periodSelect: periodElement(picker) };
}
function getInformationJS(clock, minuteIncrement) {
var hours = ["twelve", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven"];
var minutes = {
getLength: null,
getValue: null
};
minutes.getLength = function () { return 60 / minuteIncrement; };
minutes.getValue = function (index) {
var display = index * minuteIncrement;
if (display < 10) {
return "0" + display.toString();
}
else {
return display.toString();
}
};
var order = ["period", "minute", "hour"];
if (clock === "24HourClock") {
hours = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"];
hours.push("thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenteen", "twenty-one", "twenty-two", "twenty-three");
order = ["hour", "minute"];
}
return { minutes: minutes, hours: hours, clock: clock || "12HourClock", periods: ["AM", "PM"], order: order };
};
export class TimePickerDecl {
testCorrectBackEndValue(complete) {
var cleanup;
createPickerWithAppend().then(function (picker) {
timePicker = picker;
setValues();
cleanup = addChangeEvent(picker);
setMinutes(picker, 30);
setHours(picker, 11);
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
testBackEndAtNoon(complete) {
// bug 437064
var cleanup;
createPickerWithAppend().then(function (picker) {
timePicker = picker;
setValues();
cleanup = addChangeEvent(picker);
setPeriod(picker, AM);
setMinutes(picker, 30);
setHours(picker, 12);
setPeriod(picker, PM);
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
// create default picker. Note, this test uses runtime date/time value so needs to be smart as the date
// value will change between runs and locales. before/after noon, etc..
testSimpleTime(complete) {
var today = new Date();
createPickerWithAppend().then(function (picker) {
var expectedHour = today.getHours();
var periodControl = isPeriodControl();
// workaround date object defaulting to 24h format.
if (expectedHour > 12 && periodControl) { expectedHour -= 12; }
if (expectedHour === 0) { expectedHour = 12; }
verifyTime(picker, {
hour: expectedHour,
minute: today.getMinutes(),
period: calcPeriod(today.getHours())
});
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testDefaults(complete) {
// validate timePicker defaults
createPickerWithAppend().then(function (picker) {
var c = picker.winControl;
LiveUnit.Assert.isFalse(c.disabled);
// verify all 3 elements are displayed, style display=""
LiveUnit.Assert.areEqual("", hourElement(picker).style.display);
LiveUnit.Assert.areEqual("", minuteElement(picker).style.display);
if (periodElement(picker)) {
LiveUnit.Assert.areEqual("", periodElement(picker).style.display);
}
LiveUnit.Assert.areEqual(1, c.minuteIncrement);
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testDefaultFormats(complete) {
// validate datePicker default format
createPickerWithAppend({ current: '1:23 am' }).then(function (picker) {
LiveUnit.Assert.areEqual("1", getText(hourElement(picker)));
LiveUnit.Assert.areEqual("23", getText(minuteElement(picker)));
if (isPeriodControl()) {
LiveUnit.Assert.areEqual("AM", getText(periodElement(picker)));
}
else {
LiveUnit.Assert.areEqual(null, periodElement(picker), "period control is not found in 24HourClock");
}
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testSetCurrentFromDate(complete) {
createPickerWithAppend().then(function (picker) {
var date = new Date(2011, 1, 3, 10, 11, 12);
picker.winControl.current = date;
verifyTime(picker, { hour: '10', minute: '11', period: 'AM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testDisabled1(complete) {
createPickerWithAppend({
current: '10:11 pm',
disabled: true
})
.then(function (picker) {
verifyTime(picker, { hour: '10', minute: '11', period: 'PM' });
LiveUnit.Assert.isTrue(picker.winControl.disabled);
picker.winControl.disabled = false;
LiveUnit.Assert.isFalse(picker.winControl.disabled);
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testDisabled2(complete) {
createPickerWithAppend({
current: '10:11 pm',
disabled: false
})
.then(function (picker) {
verifyTime(picker, { hour: '10', minute: '11', period: 'PM' });
LiveUnit.Assert.isFalse(picker.winControl.disabled);
picker.winControl.disabled = true;
LiveUnit.Assert.isTrue(picker.winControl.disabled);
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testMinuteIncrement1(complete) {
// verify time snaps backward to last valid increment
createPickerWithAppend({
current: '10:15 am',
minuteIncrement: 15
}).then(function (picker) {
verifyTime(picker, { hour: '10', minute: '15', period: 'AM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testMinuteIncrement2(complete) {
// verify time snaps backward to last valid increment
createPickerWithAppend({
current: '10:16 am',
minuteIncrement: 15
}).then(function (picker) {
verifyTime(picker, { hour: '10', minute: '15', period: 'AM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testMinuteIncrement3(complete) {
// verify time snaps backward to last valid increment
createPickerWithAppend({
current: '10:29 am',
minuteIncrement: 15
}).then(function (picker) {
verifyTime(picker, { hour: '10', minute: '15', period: 'AM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testMinuteIncrement4(complete) {
// verify time snaps backward to last valid increment not evenly divisible
createPickerWithAppend({
current: '10:51 am',
minuteIncrement: 50
}).then(function (picker) {
verifyTime(picker, { hour: '10', minute: '50', period: 'AM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testMinuteIncrement_boundary1(complete) {
// verify time not changed for 0 increment
createPickerWithAppend({
current: '10:11 am',
minuteIncrement: 0
}).then(function (picker) {
verifyTime(picker, { hour: '10', minute: '11', period: 'AM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testMinuteIncrement_boundary2(complete) {
// verify time not changed for increment == 60
createPickerWithAppend({
current: '10:21 am',
minuteIncrement: 60
}).then(function (picker) {
verifyTime(picker, { hour: '10', minute: '21', period: 'AM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testMinuteIncrement_boundary3(complete) {
// verify time not changed for increment > 60
createPickerWithAppend({
current: '10:31 am',
minuteIncrement: 61
}).then(function (picker) {
verifyTime(picker, { hour: '10', minute: '31', period: 'AM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testMinuteIncrement_boundary4(complete) {
// verify time not changed for increment < 0
createPickerWithAppend({
current: '10:41 am',
minuteIncrement: -15
}).then(function (picker) {
verifyTime(picker, { hour: '10', minute: '30', period: 'AM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testMinuteIncrement_boundary5(complete) {
// verify increment > 60 == increment mod 60
createPickerWithAppend({
current: '10:51 am',
minuteIncrement: 74
}).then(function (picker) {
// 74-60=14, 14*3 = 42
verifyTime(picker, { hour: '10', minute: '42', period: 'AM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testCustomTimePM(complete) {
// bug WIN8 250170: Expected '"05"' but actual was '"5"'
createPickerWithAppend({ current: '17:00:01' }).then(function (picker) {
verifyTime(picker, { hour: 5, minute: '00', period: 'PM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testCustomTimeAM(complete) {
createPickerWithAppend({ current: '0:53:15' }).then(function (picker) {
verifyTime(picker, { hour: 12, minute: 53, period: 'AM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testCustomTimeNoon(complete) {
// UNDONE: This may actually be 'AM' in certain locales.
//
createPickerWithAppend({ current: '12:00:00' }).then(function (picker) {
verifyTime(picker, { hour: 12, minute: '00', period: calcPeriod(12) });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testCustomTimeNoonPlus(complete) {
createPickerWithAppend({ current: '12:01:00' }).then(function (picker) {
verifyTime(picker, { hour: 12, minute: '01', period: 'PM' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testFireHourchangeEvent(complete) {
var cleanup;
createPickerWithAppend({
current: '11:20 pm'
}).then(function (picker) {
timePicker = picker;
cleanup = attachEventListeners(picker);
fireOnchange(hourElement(picker));
LiveUnit.Assert.areEqual(1, changeHit);
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, unhandledTestError);
}
testFireMinutechangeEvent(complete) {
var cleanup;
createPickerWithAppend({
current: '11:21 pm'
}).then(function (picker) {
timePicker = picker;
cleanup = attachEventListeners(picker);
fireOnchange(minuteElement(picker));
LiveUnit.Assert.areEqual(1, changeHit);
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
testFirePeriodchangeEvent(complete) {
var cleanup;
createPickerWithAppend({
current: '11:22 pm'
}).then(function (picker) {
if (isPeriodControl()) {
timePicker = picker;
cleanup = attachEventListeners(picker);
fireOnchange(periodElement(picker));
LiveUnit.Assert.areEqual(1, changeHit);
}
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
testFireAllEventsAndRemove(complete) {
var cleanup;
createPickerWithAppend({
current: '11:23 pm'
}).then(function (picker) {
timePicker = picker;
cleanup = attachEventListeners(picker);
verifyTime(picker, { hour: '11', minute: '23', period: 'pm' });
fireOnchange(hourElement(picker));
fireOnchange(minuteElement(picker));
if (isPeriodControl()) {
fireOnchange(periodElement(picker));
LiveUnit.Assert.areEqual(3, changeHit);
}
else {
LiveUnit.Assert.areEqual(2, changeHit);
}
// make sure time hasn't changed
verifyTime(picker, { hour: '11', minute: '23', period: 'pm' });
cleanup();
fireOnchange(hourElement(picker));
fireOnchange(minuteElement(picker));
if (isPeriodControl()) {
fireOnchange(periodElement(picker));
}
LiveUnit.Assert.areEqual(0, changeHit);
// make sure time hasn't changed
verifyTime(picker, { hour: '11', minute: '23', period: 'pm' });
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
testFireMultipleChangeEvents(complete) {
var cleanup;
createPickerWithAppend({
current: '11:24 pm'
}).then(function (picker) {
timePicker = picker;
cleanup = attachEventListeners(picker);
for (var n = 1; n <= 15; n++) {
fireOnchange(hourElement(picker));
fireOnchange(minuteElement(picker));
if (isPeriodControl()) {
fireOnchange(periodElement(picker));
LiveUnit.Assert.areEqual(n * 3, changeHit);
}
else {
LiveUnit.Assert.areEqual(n * 2, changeHit);
}
}
// make sure time hasn't changed
verifyTime(picker, { hour: '11', minute: '24', period: 'pm' });
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
testhourchangeEvent(complete) {
var cleanup;
createPickerWithAppend({
current: '11:12 am'
}).then(function (picker) {
timePicker = picker;
verifyTime(picker, { hour: '11', minute: '12', period: 'AM' });
cleanup = attachEventListeners(picker);
// change the hour
picker.winControl.current = '10:12 am';
verifyTime(picker, { hour: '10', minute: '12', period: 'AM' });
LiveUnit.Assert.areEqual(0, changeHit);
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
testminutechangeEvent(complete) {
var cleanup;
createPickerWithAppend({
current: '11:12 am'
}).then(function (picker) {
timePicker = picker;
verifyTime(picker, { hour: '11', minute: '12', period: 'AM' });
cleanup = attachEventListeners(picker);
// change the minute
picker.winControl.current = '11:10 am';
verifyTime(picker, { hour: '11', minute: '10', period: 'AM' });
LiveUnit.Assert.areEqual(0, changeHit);
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
testPeriodChangeEvent(complete) {
var cleanup;
createPickerWithAppend({
current: '11:12 pm'
}).then(function (picker) {
timePicker = picker;
verifyTime(picker, { hour: '11', minute: '12', period: 'PM' });
cleanup = attachEventListeners(picker);
// change the period
picker.winControl.current = '11:12 am';
verifyTime(picker, { hour: '11', minute: '12', period: 'AM' });
LiveUnit.Assert.areEqual(0, changeHit);
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
testChangeThreeEventsAndRemove(complete) {
var cleanup;
createPickerWithAppend({
current: '10:11 am'
}).then(function (picker) {
timePicker = picker;
cleanup = attachEventListeners(picker);
verifyTime(picker, { hour: '10', minute: '11', period: 'AM' });
// change all 3
picker.winControl.current = '11:12 pm';
verifyTime(picker, { hour: '11', minute: '12', period: 'PM' });
LiveUnit.Assert.areEqual(0, changeHit);
picker.winControl.current = '10:11 am';
verifyTime(picker, { hour: '10', minute: '11', period: 'am' });
LiveUnit.Assert.areEqual(0, changeHit);
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
test24Format(complete) {
var cleanup;
createPickerWithAppend(
{
clock: '24HourClock', current: '13:05:00'
}).then(function (picker) {
timePicker = picker;
var expectedHour = "13";
var expectedMinute = "05";
cleanup = addChangeEvent(picker);
var hour = hourElement(picker).value;
var minute = minuteElement(picker).value;
var current = picker.winControl.current;
LiveUnit.Assert.areEqual(null, periodElement(picker), "period element was generated incorrectly");
LiveUnit.Assert.areEqual(expectedHour, hour, "Wrong value for the hour");
LiveUnit.Assert.areEqual(expectedMinute, minute, "Wrong value for the minute");
LiveUnit.Assert.areEqual(parseInt(expectedHour), current.getHours(), "Wrong value for the current hour");
LiveUnit.Assert.areEqual(parseInt(expectedMinute), current.getMinutes(), "Wrong value for the current minute");
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
test12Format(complete) {
//BUGID: 729979
var cleanup;
createPickerWithAppend(
{
clock: '12HourClock', current: '08:05:00'
}).then(function (picker) {
timePicker = picker;
var expectedHour = "8";
var expectedMinute = "05";
var expectedPeriod = "AM";
cleanup = addChangeEvent(picker);
var hour = hourElement(picker).value;
var minute = minuteElement(picker).value;
var current = picker.winControl.current;
LiveUnit.Assert.areEqual(expectedPeriod, periodElement(picker).value, "period element was set incorrectly");
LiveUnit.Assert.areEqual(expectedHour, hour, "Wrong value for the hour");
LiveUnit.Assert.areEqual(expectedMinute, minute, "Wrong value for the minute");
LiveUnit.Assert.areEqual(parseInt(expectedHour), current.getHours(), "Wrong value for the current hour");
LiveUnit.Assert.areEqual(parseInt(expectedMinute), current.getMinutes(), "Wrong value for the current minute");
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
testImplicit12Format(complete) {
var cleanup;
createPickerWithAppend(
{
current: '08:05:00'
}).then(function (picker) {
timePicker = picker;
var expectedHour = "8";
var expectedMinute = "05";
var expectedPeriod = "AM";
cleanup = addChangeEvent(picker);
var hour = hourElement(picker).value;
var minute = minuteElement(picker).value;
var current = picker.winControl.current;
checkPeriodControlValue(expectedPeriod, periodElement(picker));
LiveUnit.Assert.areEqual(expectedHour, hour, "Wrong value for the hour");
LiveUnit.Assert.areEqual(expectedMinute, minute, "Wrong value for the minute");
LiveUnit.Assert.areEqual(parseInt(expectedHour), current.getHours(), "Wrong value for the current hour");
LiveUnit.Assert.areEqual(parseInt(expectedMinute), current.getMinutes(), "Wrong value for the current minute");
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
testTimePickerGlobalization = function (complete) {
var cleanup;
if (isWinRTEnabled()) {
createPickerWithAppend(
{
current: '13:05:00-05:00'
}).then(function (picker) {
timePicker = picker;
var calendar = new glob.Calendar();
// calendar.changeClock("12HourClock");
var clock = calendar.getClock();
var expectedCount = 12;
var definedPeriod = true;
if (clock === "12HourClock") {
expectedCount = 12;
}
else {
expectedCount = 24;
definedPeriod = false;
}
var selectControls = getControls(picker);
LiveUnit.Assert.areEqual(expectedCount, selectControls.hourSelect.length, "wrong number of hour elements");
LiveUnit.Assert.areEqual(definedPeriod, !!selectControls.periodSelect, "Not expected behavior of period control");
var UIOrder = getActualUIOrder();
var actualOrder = getExpectedOrder(calendar.getCalendarSystem(), clock);
LiveUnit.Assert.areEqual(actualOrder, UIOrder, "Order is not corrrect on 12HourClock");
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
else
complete();
};
testTimePicker24HourClockGlobalization = function (complete) {
if (isWinRTEnabled()) {
var cleanup;
createPickerWithAppend(
{
current: '13:05:00',
clock: "24HourClock"
}).then(function (picker) {
timePicker = picker;
var calendar = new glob.Calendar();
calendar.changeClock("24HourClock");
var clock = calendar.getClock();
var expectedCount = 12;
var definedPeriod = true;
if (clock === "12HourClock") {
expectedCount = 12;
}
else {
expectedCount = 24;
definedPeriod = false;
}
var selectControls = getControls(picker);
LiveUnit.Assert.areEqual(expectedCount, selectControls.hourSelect.length, "wrong number of hour elements");
LiveUnit.Assert.areEqual(definedPeriod, !!selectControls.periodSelect, "Not expected behavior of period control");
var UIOrder = getActualUIOrder();
var actualOrder = getExpectedOrder(calendar.getCalendarSystem(), clock);
LiveUnit.Assert.areEqual(actualOrder, UIOrder, "Order is not corrrect on 12HourClock");
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
else
complete();
};
testtimePickerExplicit12HourClockGlobalization(complete) {
//BUGID: 729979
if (isWinRTEnabled()) {
var cleanup;
createPickerWithAppend(
{
current: '13:05:00',
clock: "12HourClock"
}).then(function (picker) {
timePicker = picker;
var calendar = new glob.Calendar();
calendar.changeClock("12HourClock");
var clock = calendar.getClock();
var expectedCount = 12;
var definedPeriod = true;
if (clock === "12HourClock") {
expectedCount = 12;
}
else {
expectedCount = 24;
definedPeriod = false;
}
var selectControls = getControls(picker);
LiveUnit.Assert.areEqual(expectedCount, selectControls.hourSelect.length, "wrong number of hour elements");
LiveUnit.Assert.areEqual(definedPeriod, !!selectControls.periodSelect, "The period control visibility is not correct");
var UIOrder = getActualUIOrder();
var actualOrder = getExpectedOrder(calendar.getCalendarSystem(), clock);
LiveUnit.Assert.areEqual(actualOrder, UIOrder, "Order is not corrrect on 12HourClock");
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
else
complete();
}
testTimePickerGlobalizationWithCornerCaseCurrnet(complete) {
if (isWinRTEnabled()) {
var cleanup;
createPickerWithAppend(
{
current: '13:05:00+05:00'
}).then(function (picker) {
timePicker = picker;
var calendar = new glob.Calendar();
var clock = calendar.getClock();
var expectedCount = 12;
var definedPeriod = true;
if (clock === "12HourClock") {
expectedCount = 12;
}
else {
expectedCount = 24;
definedPeriod = false;
}
var selectControls = getControls(picker);
LiveUnit.Assert.areEqual(expectedCount, selectControls.hourSelect.length, "wrong number of hour elements");
LiveUnit.Assert.areEqual(definedPeriod, !!selectControls.periodSelect, "Not expected behavior of period control");
var UIOrder = getActualUIOrder();
var actualOrder = getExpectedOrder(calendar.getCalendarSystem(), clock);
LiveUnit.Assert.areEqual(actualOrder, UIOrder, "Order is not corrrect on 12HourClock");
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
else
complete();
}
testCorrectBackEndValueWith24HourClock(complete) {
if (isWinRTEnabled()) {
var cleanup;
createPickerWithAppend({
clock: "24HourClock"
}).
then(function (picker) {
timePicker = picker;
setValues();
cleanup = addChangeEvent(picker);
setMinutes(picker, 30);
for (var i = 1; i < 24; i++)
setHours(picker, i);
})
.then(null, unhandledTestError)
.then(cleanup)
.then(cleanupTimePicker)
.then(complete, complete);
}
else
complete();
}
testDirectPatternDeclaratively(complete) {
//BugID: 538276
if (isWinRTEnabled()) {
var cleanup;
createPickerWithAppend({
hourPattern: "{hour.integer(2)}",
minutePattern: "{minute.integer(2)}",
current: '05:10:01'
}).
then(function (picker) {
var hour = hourElement(picker).value;
var minute = minuteElement(picker).value;
var current = picker.winControl.current;
LiveUnit.Assert.areEqual('05', hour, "checking the content of hour");
LiveUnit.Assert.areEqual('10', minute, "checking the content of minute");
checkPeriodControlValue("AM", periodElement(picker));
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
else
complete();
}
testPatternWithSmallIntegersDeclaratively(complete) {
//BugID: 538276
if (isWinRTEnabled()) {
var cleanup, cleanupListeners;
createPickerWithAppend({
hourPattern: "{hour.integer(1)}",
minutePattern: "{minute.integer(1)}",
periodPattern: "{period.abbreviated(1)}",
current: '12:25:01'
}).
then(function (picker) {
var hour = hourElement(picker).value;
var minute = minuteElement(picker).value;
//var period = periodElement(picker).value;
var current = picker.winControl.current;
checkPeriodControlValue("P", periodElement(picker));
//LiveUnit.Assert.areEqual('P', period, "checking the content of period");
LiveUnit.Assert.areEqual('12', hour, "checking the content of hour");
LiveUnit.Assert.areEqual('25', minute, "checking the content of minute");
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
else
complete();
}
testPatternWithInvalidPatternDeclaratively(complete) {
//BugID: 538276
if (isWinRTEnabled()) {
createPickerWithAppend({
hourPattern: "{hour.integer(3)}",
minutePattern: "{minute.integer(3)}",
periodPattern: "{period.abbreviated(3)}",
current: '15:45:01'
}).
then(function (picker) {
var hour = hourElement(picker).value;
var minute = minuteElement(picker).value;
//var period = periodElement(picker).value;
var current = picker.winControl.current;
checkPeriodControlValue("PM", periodElement(picker));
//LiveUnit.Assert.areEqual('PM', period, "checking the content of period");
if (isPeriodControl()) {
LiveUnit.Assert.areEqual('003', hour, "checking the content of hour");
}
else {
LiveUnit.Assert.areEqual('015', hour, "checking the content of hour");
}
LiveUnit.Assert.areEqual('045', minute, "checking the content of minute");
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
else
complete();
}
testPatternWithIntegerAndAdditionPatternDeclaratively(complete) {
//BugID: 538276
if (isWinRTEnabled()) {
createPickerWithAppend({
hourPattern: "{hour.integer(2)} clock",
minutePattern: "{minute.integer(2)} minutes",
periodPattern: "{period.abbreviated(2)} period",
current: '15:45:01'
}).
then(function (picker) {
var current = picker.winControl.current;
var periodControl = periodElement(picker);
var minuteControl = minuteElement(picker);
var hourControl = hourElement(picker);
checkPeriodControlValue("PM period", periodControl);
if (isPeriodControl()) {
LiveUnit.Assert.areEqual('03 clock', hourControl.value, "checking the content of hour");
}
else {
LiveUnit.Assert.areEqual('15 clock', hourControl.value, "checking the content of hour");
}
LiveUnit.Assert.areEqual('45 minutes', minuteControl.value, "checking the content of minute");
if (isPeriodControl()) {
periodControl.selectedIndex = 0; //AM
fireOnchange(periodControl);
}
minuteControl.selectedIndex = 30; //30
fireOnchange(minuteControl);
hourControl.selectedIndex = 11;
fireOnchange(hourControl);
checkPeriodControlValue("AM period", periodControl);
LiveUnit.Assert.areEqual('11 clock', hourControl.value, "checking the content of hour");
LiveUnit.Assert.areEqual('30 minutes', minuteControl.value, "checking the content of minute");
hourControl.selectedIndex = 0;
fireOnchange(hourControl);
checkPeriodControlValue("AM period", periodControl);
if (isPeriodControl()) {
LiveUnit.Assert.areEqual('12 clock', hourControl.value, "checking the content of hour");
}
else {
LiveUnit.Assert.areEqual('00 clock', hourControl.value, "checking the content of hour");
}
LiveUnit.Assert.areEqual('30 minutes', minuteControl.value, "checking the content of minute");
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
else
complete();
}
testTwoTimePickerOneWithPatternAndOneWithout(complete) {
//BugID: 538276
if (isWinRTEnabled()) {
createPickerWithAppend({
hourPattern: "{hour.integer(2)} clock",
minutePattern: "{minute.integer(2)} minutes",
periodPattern: "{period.abbreviated(2)} period",
current: '15:45:01'
}).then(function (picker) {
var current = picker.winControl.current;
var periodControl = periodElement(picker);
var minuteControl = minuteElement(picker);
var hourControl = hourElement(picker);
checkPeriodControlValue('PM period', periodControl);
if (isPeriodControl()) {
LiveUnit.Assert.areEqual('03 clock', hourControl.value, "checking the content of hour");
}
else {
LiveUnit.Assert.areEqual('15 clock', hourControl.value, "checking the content of hour");
}
LiveUnit.Assert.areEqual('45 minutes', minuteControl.value, "checking the content of minute");
}).
then(null, unhandledTestError).
then(cleanupTimePicker).
then(function () {
createPickerWithAppend({
current: '02:30:02',
}).then(function (picker) {
var periodControl = periodElement(picker);
var minuteControl = minuteElement(picker);
var hourControl = hourElement(picker);
checkPeriodControlValue('AM', periodControl);
LiveUnit.Assert.areEqual('2', hourControl.value, "checking the content of hour");
LiveUnit.Assert.areEqual('30', minuteControl.value, "checking the content of minute");
}).
then(null, unhandledTestError).
then(cleanupTimePicker);
})
.then(complete, complete);
}
else {
complete();
}
}
testCustomInformationProvider12HourClock = function (complete) {
if (!isWinRTEnabled()) {
var old = (<any>WinJS.UI.TimePicker).getInformation;
var newComplete = function () {
(<any>WinJS.UI.TimePicker).getInformation = old;
complete();
};
(<any>WinJS.UI.TimePicker).getInformation = getInformationJS;
createPickerWithAppend({
clock: '12HourClock',
current: '13:05:00'
}).then(function (picker) {
var current = picker.winControl.current;
var periodControl = periodElement(picker);
var minuteControl = minuteElement(picker);
var hourControl = hourElement(picker);
LiveUnit.Assert.areEqual('PM', periodControl.value, "checking the content of period");
LiveUnit.Assert.areEqual('one', hourControl.value, "checking the content of hour");
LiveUnit.Assert.areEqual('05', minuteControl.value, "checking the content of minute");
LiveUnit.Assert.areEqual("PMH", getActualUIOrder(), "checking the correctness of the order");
LiveUnit.Assert.areEqual(12, hourControl.length, "checking that 24 elements are added");
LiveUnit.Assert.areEqual(60, minuteControl.length, "checking that 24 elements are added");
}).
then(null, unhandledTestError).
then(cleanupTimePicker).
then(newComplete, newComplete);
}
else {
complete();
}
};
testCustomInformationProvider24HourClock(complete) {
if (!isWinRTEnabled()) {
var old = (<any>WinJS.UI.TimePicker).getInformation;
var newComplete = function () {
(<any>WinJS.UI.TimePicker).getInformation = old;
complete();
};
(<any>WinJS.UI.TimePicker).getInformation = getInformationJS;
createPickerWithAppend({
clock: '24HourClock',
current: '00:30:00'
}).then(function (picker) {
var x = 2;
var current = picker.winControl.current;
var periodControl = periodElement(picker);
var minuteControl = minuteElement(picker);
var hourControl = hourElement(picker);
LiveUnit.Assert.isTrue(!periodControl, "checking the content of period");
LiveUnit.Assert.areEqual('zero', hourControl.value, "checking the content of hour");
LiveUnit.Assert.areEqual('30', minuteControl.value, "checking the content of minute");
LiveUnit.Assert.areEqual("HM", getActualUIOrder(), "checking the correctness of the order");
LiveUnit.Assert.areEqual(24, hourControl.length, "checking that 24 elements are added");
LiveUnit.Assert.areEqual(60, minuteControl.length, "checking that 24 elements are added");
}).
then(null, unhandledTestError).
then(cleanupTimePicker).
then(newComplete, newComplete);
} else {
complete();
}
}
testCustomInformationProvider24HourClockWithDifferentIncrements(complete) {
if (!isWinRTEnabled()) {
var old = (<any>WinJS.UI.TimePicker).getInformation;
var newComplete = function () {
(<any>WinJS.UI.TimePicker).getInformation = old;
complete();
};
(<any>WinJS.UI.TimePicker).getInformation = getInformationJS;
createPickerWithAppend({
clock: '24HourClock',
current: '23:30:00',
minuteIncrement: 15
}).then(function (picker) {
var x = 2;
var current = picker.winControl.current;
var periodControl = periodElement(picker);
var minuteControl = minuteElement(picker);
var hourControl = hourElement(picker);
LiveUnit.Assert.isTrue(!periodControl, "checking the content of period");
LiveUnit.Assert.areEqual('twenty-three', hourControl.value, "checking the content of hour");
LiveUnit.Assert.areEqual('30', minuteControl.value, "checking the content of minute");
LiveUnit.Assert.areEqual("HM", getActualUIOrder(), "checking the correctness of the order");
LiveUnit.Assert.areEqual(24, hourControl.length, "checking that 24 elements are added");
LiveUnit.Assert.areEqual(4, minuteControl.length, "checking that 24 elements are added");
}).
then(null, unhandledTestError).
then(cleanupTimePicker).
then(newComplete, newComplete);
}
else {
complete();
}
}
testChangingClockFormat(complete) {
//BUGID: 729979
var cleanup;
if (isWinRTEnabled()) {
createPickerWithAppend(
{
clock: '12HourClock',
current: '13:05:00'
}).then(function (picker) {
timePicker = picker;
var clock = "12HourClock";
var calendar = new glob.Calendar();
calendar.changeClock(clock);
clock = calendar.getClock();
var expectedCount = 12;
var definedPeriod = true;
var selectControls = getControls(picker);
LiveUnit.Assert.areEqual(expectedCount, selectControls.hourSelect.length, "wrong number of hour elements");
LiveUnit.Assert.areEqual(definedPeriod, !!selectControls.periodSelect, "Not expected behavior of period control");
var UIOrder = getActualUIOrder();
var actualOrder = getExpectedOrder(calendar.getCalendarSystem(), clock);
LiveUnit.Assert.areEqual(actualOrder, UIOrder, "Order is not corrrect on 12HourClock");
LiveUnit.Assert.areEqual("1", selectControls.hourSelect.value, "Expected Value for hourControl in 12HourClock is not correct");
LiveUnit.Assert.areEqual("05", selectControls.minuteSelect.value, "Expected Value for minuteControl in 12HourClock is not correct");
checkPeriodControlValue("PM", selectControls.periodSelect, true);
clock = "24HourClock";
calendar.changeClock(clock);
picker.winControl.clock = clock;
picker.winControl.minuteIncrement = "15";
clock = calendar.getClock();
expectedCount = 24;
definedPeriod = false;
actualOrder = getExpectedOrder(calendar.getCalendarSystem(), clock);
selectControls = getControls(picker);
LiveUnit.Assert.areEqual(expectedCount, selectControls.hourSelect.length, "wrong number of hour elements");
LiveUnit.Assert.areEqual(definedPeriod, !!selectControls.periodSelect, "Not expected behavior of period control for 24 hour clock");
UIOrder = getActualUIOrder();
LiveUnit.Assert.areEqual(actualOrder, UIOrder, "Order is not corrrect on 12HourClock");
LiveUnit.Assert.areEqual("13", selectControls.hourSelect.value, "Expected Value for hourControl in 24HourClock is not correct");
LiveUnit.Assert.areEqual("00", selectControls.minuteSelect.value, "Expected Value for minuteControl in 24HourClock is not correct");
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
else
complete();
}
testPatternWithSpecialCharacters(complete) {
if (isWinRTEnabled()) {
createPickerWithAppend({
hourPattern: " ' & < > # {hour.integer(3)}",
minutePattern: " ' & < > # {minute.integer(3)}",
periodPattern: ': ! @ $ % ^ " {period.abbreviated(3)}',
current: '15:45:01'
}).
then(function (picker) {
var hour = hourElement(picker).value;
var minute = minuteElement(picker).value;
var period = periodElement(picker);
var current = picker.winControl.current;
checkPeriodControlValue(': ! @ $ % ^ " PM', period);
if (isPeriodControl()) {
LiveUnit.Assert.areEqual(" ' & < > # 003", hour, "checking the content of hour");
}
else {
LiveUnit.Assert.areEqual(" ' & < > # 015", hour, "checking the content of hour");
}
LiveUnit.Assert.areEqual(" ' & < > # 045", minute, "checking the content of minute");
picker.winControl.current = '05:20:03';
hour = hourElement(picker).value;
minute = minuteElement(picker).value;
checkPeriodControlValue(': ! @ $ % ^ " AM', period);
LiveUnit.Assert.areEqual(" ' & < > # 005", hour, "checking the content of hour");
LiveUnit.Assert.areEqual(" ' & < > # 020", minute, "checking the content of minute");
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
else
complete();
}
testMinuteIncrement(complete) {
if (isWinRTEnabled()) {
createPickerWithAppend({
minuteIncrement: 5,
current: '3:30PM'
}).
then(function (picker) {
function setAndCheck(increment) {
picker.winControl.minuteIncrement = increment;
var minute = minuteElement(picker).value;
LiveUnit.Assert.areEqual("30", minute, "checking the content of minute");
}
setAndCheck(15);
setAndCheck(10);
setAndCheck(30);
setAndCheck(5);
})
.then(null, unhandledTestError)
.then(cleanupTimePicker)
.then(complete, complete);
}
else
complete();
}
testConstructionWithEventHandlerInOptions(complete) {
var handler = function () {
complete();
};
var dp = new WinJS.UI.TimePicker(null, { onchange: handler });
document.body.appendChild(dp.element);
var evnt = <UIEvent>document.createEvent("UIEvents");
evnt.initUIEvent("change", false, false, window, 0);
dp.element.dispatchEvent(evnt);
}
};
}
LiveUnit.registerTestClass("CorsicaTests.TimePickerDecl"); | the_stack |
import fs from 'fs';
import path from 'path';
import { BaseModel } from '../../src/BaseModel';
import { createConnection, Connection, Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, Repository } from 'typeorm';
import usersData from '../data/users.json';
async function seed(connection: Connection, Entity: any, data: any) {
await connection.createQueryBuilder()
.insert()
.into(Entity)
.values(data.map(item => ({ ...item }))) // to avoid the source data mutation
.execute();
}
async function cleanup(repository: Repository<any>) {
const { tableName } = repository.metadata;
try {
await repository.query(`DELETE FROM \`${tableName}\`;`);
await repository.query(`DELETE FROM sqlite_sequence WHERE name = "${tableName}"`);
} catch (err) {
console.error('SQLite database error:', err);
}
}
@Entity()
class User {
@PrimaryGeneratedColumn()
id?: number;
@Column()
name: string;
@Column()
age: number;
@CreateDateColumn()
createdAt?: Date;
@UpdateDateColumn()
updatedAt?: Date;
}
describe('Model integration', () => {
let connection: Connection;
let model: BaseModel<User>;
let userRepository: Repository<User>;
beforeAll(async () => {
connection = await createConnection({
type: 'sqlite',
database: path.resolve(__dirname, 'testDB.sql'),
entities: [User]
});
await connection.synchronize();
BaseModel.connection = connection;
model = new BaseModel(User);
userRepository = connection.getRepository(User);
});
afterAll(async () => {
connection.close();
fs.unlinkSync(path.resolve(__dirname, 'testDB.sql'));
});
// TODO break into find and queryBuilder sections
describe('#find', () => {
beforeAll(() => seed(connection, User, usersData));
afterAll(() => cleanup(userRepository));
describe('Paginate records using $skip and $limit query options', () => {
test('Should find with $limit option', async () => {
const results = await model.find({ $limit: 5 });
expect(results).toBeInstanceOf(Array);
expect(results.length).toBe(5);
});
test('Should find with $limit and $skip option', async () => {
const results = await model.find({ $limit: 2, $skip: 4 });
expect(results).toBeInstanceOf(Array);
expect(results.length).toBe(2);
expect(results[0].id).toBe(5);
expect(results[1].id).toBe(6);
});
});
describe('Sorting records using $sort query option', () => {
test('Should sort by string value with ASC order', async () => {
const results = await model.find({ $sort: 'age' });
expect(results).toBeInstanceOf(Array);
expect(results.length).toBe(10);
expect(results[0].age).toBe(20);
expect(results[9].age).toBe(63);
});
test('Should sort by DESC order', async () => {
const results = await model.find({ $sort: 'age' });
expect(results).toBeInstanceOf(Array);
expect(results.length).toBe(10);
expect(results[0].age).toBe(20);
expect(results[9].age).toBe(63);
});
test('Should sort by two string fields with ASC order', async () => {
const results = await model.find({ $sort: ['age', 'id'] });
expect(results).toBeInstanceOf(Array);
expect(results.length).toBe(10);
expect(results[0].age).toBe(20);
expect(results[9].age).toBe(63);
expect(results[4].id).toBe(4);
expect(results[5].id).toBe(5);
expect(results[6].id).toBe(9);
});
test.todo('Should sort by two fields with DESC order');
});
describe('Selecting fields using $select query option', () => {
test('Should select only "name" fields', async () => {
const results = await model.find({ $select: ['name'] });
const isSomeIncorrect = results.some(row => {
const fields = Object.keys(row);
return fields.length !== 1 || !fields.includes('name');
})
expect(isSomeIncorrect).toBeFalsy();
});
test('Should select only "id" and "age" fields', async () => {
const results = await model.find({ $select: ['id', 'age'] });
const isSomeIncorrect = results.some(row => {
const fields = Object.keys(row);
return fields.length !== 2 || !fields.includes('id') || !fields.includes('age');
})
expect(isSomeIncorrect).toBeFalsy();
});
});
describe('Find records using $where filtering', () => {
test('Should find rows with $not query', async () => {
const results = await model.find({ $where: { name: { $neq: 'Ervin Howell' }} });
const filteredRowIndex = results.findIndex(row => row.name === 'Ervin Howell');
expect(results).toBeInstanceOf(Array);
expect(results.length).toBe(9);
expect(filteredRowIndex).toBe(-1);
});
test.todo('Should find rows with $like query');
test('Should find rows with $in query', async () => {
const results = await model.find({ $where: { id: { $in: [3, 6, 9] }} });
expect(results).toBeInstanceOf(Array);
expect(results.length).toBe(3);
});
});
});
describe('#total', () => {
beforeAll(() => seed(connection, User, usersData));
afterAll(() => cleanup(userRepository));
test('Should return total rows count', async () => {
const results = await model.total();
expect(results).toBe(10);
});
test('Should return total rows count with search query', async () => {
const results = await model.total({ age: { $gte: 30 } });
expect(results).toBe(6);
});
});
describe('#create', () => {
afterEach(() => cleanup(userRepository));
test('Should create new single row', async () => {
const row = { name: 'Jhon Doe', age: 24 };
const results = await model.create(row);
expect(results).toMatchObject({ identifiers: [1] });
const rows = await userRepository.find();
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({ ...row, id: 1 });
});
test('Should create a few rows', async () => {
const insertRows = [
{ name: 'Jhon Doe', age: 24 },
{ name: 'Clementina DuBuque', age: 31 },
{ name: 'Nicholas Runolfsdottir V', age: 28 }
];
const results = await model.create(insertRows);
expect(results).toMatchObject({ identifiers: [1, 2, 3] });
const rows = await userRepository.find();
expect(rows).toHaveLength(3);
expect(rows[0]).toMatchObject({ ...insertRows[0], id: 1 });
expect(rows[1]).toMatchObject({ ...insertRows[1], id: 2 });
expect(rows[2]).toMatchObject({ ...insertRows[2], id: 3 });
});
});
describe('#patch', () => {
beforeEach(() => seed(connection, User, usersData));
afterEach(() => cleanup(userRepository));
test('Should patch single row', async () => {
const result = await model.patch({ id: 3 }, { age: 999 });
// Note: working only with pg or mysql, because of RETURNING supported ✅
// expect(result).toMatchObject({ affected: 1 });
expect(result).toMatchObject({ affected: undefined });
const rows = await userRepository.find();
rows.forEach(row => {
const sourceRow = usersData.find(user => user.id === row.id);
expect(row).toHaveProperty('name', sourceRow.name);
expect(row).toHaveProperty('age', row.id === 3 ? 999 : sourceRow.age);
});
});
test('Should patch multi rows', async () => {
const result = await model.patch({ age: { $in: [33, 37]} }, { name: 'PATCHED' });
// Note: working only with pg or mysql, because of RETURNING supported ✅
// expect(result).toMatchObject({ affected: 4 });
expect(result).toMatchObject({ affected: undefined });
const rows = await userRepository.find();
rows.forEach(row => {
const sourceRow = usersData.find(user => user.id === row.id);
expect(row).toHaveProperty('name', [33, 37].includes(sourceRow.age) ? 'PATCHED' : sourceRow.name);
expect(row).toHaveProperty('age', sourceRow.age);
});
});
test('Should patch all rows', async () => {
const result = await model.patch({}, { name: 'PATCHED', age: 0 });
// Note: working only with pg or mysql, because of RETURNING supported ✅
// expect(result).toMatchObject({ affected: 10 });
expect(result).toMatchObject({ affected: undefined });
const rows = await userRepository.find();
rows.forEach(row => {
expect(row).toHaveProperty('name', 'PATCHED');
expect(row).toHaveProperty('age', 0);
});
});
test.todo('Should not patch the primary id');
});
describe('#update', () => {
beforeEach(() => seed(connection, User, usersData));
afterEach(() => cleanup(userRepository));
test('Should update single row', async () => {
const [sourceRow] = await userRepository.find({ id: 6 });
const result = await model.update({ id: 6 }, { id: 666, name: 'UPDATED', age: 999 });
// Note: working only with pg or mysql, because of RETURNING supported ✅
// expect(result).toMatchObject({ affected: 1 });
expect(result).toMatchObject({ affected: undefined });
const [updatedRow] = await userRepository.find({ id: 666 });
expect(updatedRow).toBeDefined();
expect(updatedRow.name).toBe('UPDATED');
expect(updatedRow.age).toBe(999);
expect(updatedRow.createdAt.getTime()).not.toBe(sourceRow.createdAt.getTime());
expect(updatedRow.updatedAt.getTime()).not.toBe(sourceRow.updatedAt.getTime());
});
test('Should update multi rows', async () => {
// arrange
const createdAt = new Date();
const sourceRows = await userRepository.find();
// act
const result = await model.update({ id: { $in: [4, 5, 6, 7]} }, { name: 'UPDATED', age: 666, createdAt });
// assert
// Note: working only with pg or mysql, because of RETURNING supported ✅
// expect(result).toMatchObject({ affected: 4 });
expect(result).toMatchObject({ affected: undefined });
const rows = await userRepository.find();
rows.forEach(row => {
const sourceRow = sourceRows.find(user => user.id === row.id);
if ([4, 5, 6, 7].includes(row.id)) {
expect(row).toHaveProperty('name', 'UPDATED');
expect(row).toHaveProperty('age', 666);
expect(row.updatedAt.getTime()).not.toBe(sourceRow.updatedAt.getTime());
expect(row.createdAt.getTime()).toBe(createdAt.getTime());
} else {
expect(row).toHaveProperty('name', sourceRow.name);
expect(row).toHaveProperty('age', sourceRow.age);
expect(row.updatedAt.getTime()).toBe(sourceRow.updatedAt.getTime());
expect(row.createdAt.getTime()).toBe(sourceRow.createdAt.getTime());
}
});
});
test('Should update all rows', async () => {
const updatedAt = new Date();
const result = await model.update({}, { name: 'UPDATED_ALL', age: 0, updatedAt });
// Note: working only with pg or mysql, because of RETURNING supported ✅
// expect(result).toMatchObject({ affected: 10 });
expect(result).toMatchObject({ affected: undefined });
const rows = await userRepository.find();
rows.forEach(row => {
expect(row).toHaveProperty('name', 'UPDATED_ALL');
expect(row).toHaveProperty('age', 0);
expect(row.updatedAt.getTime()).toBe(updatedAt.getTime());
});
});
});
describe('#remove', () => {
beforeEach(() => seed(connection, User, usersData));
afterEach(() => cleanup(userRepository));
test('Should remove single row', async () => {
const result = await model.remove({ id: 5 });
// Note: working only with pg or mysql, because of RETURNING supported ✅
// expect(result).toMatchObject({ affected: 1 });
expect(result).toMatchObject({ affected: undefined });
const rows = await userRepository.find();
expect(rows).toHaveLength(9);
const removedRow = rows.find(row => row.id === 5);
expect(removedRow).toBeUndefined();
});
test('Should delete multi rows', async () => {
const result = await model.remove({ $or: [{ age: { $lte: 26 } }, { name: 'Chelsey Dietrich' }] });
// Note: working only with pg or mysql, because of RETURNING supported ✅
// expect(result).toMatchObject({ affected: 5 });
expect(result).toMatchObject({ affected: undefined });
const rows = await connection.getRepository(User).find();
expect(rows).toHaveLength(5);
rows.forEach(row => {
const isMatchDeleteQuery = row.age <= 26 || row.name === 'Chelsey Dietrich';
expect(isMatchDeleteQuery).toBeFalsy();
});
});
test('Should delete all rows', async () => {
const result = await model.remove({});
// TODO: check on pg and mysql, test doesn't passed because of affected is undefined
// expect(result).toMatchObject({ affected: 10 });
expect(result).toMatchObject({ affected: undefined });
const rows = await userRepository.find();
expect(rows).toHaveLength(0);
});
});
}); | the_stack |
import { spawn, StdioOptions } from 'child_process';
import * as _ from 'lodash';
import { ExpectedError } from '../errors';
export class SshPermissionDeniedError extends ExpectedError {}
export class RemoteCommandError extends ExpectedError {
cmd: string;
exitCode?: number;
exitSignal?: NodeJS.Signals;
constructor(cmd: string, exitCode?: number, exitSignal?: NodeJS.Signals) {
super(sshErrorMessage(cmd, exitSignal, exitCode));
this.cmd = cmd;
this.exitCode = exitCode;
this.exitSignal = exitSignal;
}
}
export interface SshRemoteCommandOpts {
cmd?: string;
hostname: string;
ignoreStdin?: boolean;
port?: number | 'cloud' | 'local';
proxyCommand?: string[];
username?: string;
verbose?: boolean;
}
export const stdioIgnore: {
stdin: 'ignore';
stdout: 'ignore';
stderr: 'ignore';
} = {
stdin: 'ignore',
stdout: 'ignore',
stderr: 'ignore',
};
export function sshArgsForRemoteCommand({
cmd = '',
hostname,
ignoreStdin = false,
port,
proxyCommand,
username = 'root',
verbose = false,
}: SshRemoteCommandOpts): string[] {
port = port === 'local' ? 22222 : port === 'cloud' ? 22 : port;
return [
...(verbose ? ['-vvv'] : []),
...(ignoreStdin ? ['-n'] : []),
'-t',
...(port ? ['-p', port.toString()] : []),
...['-o', 'LogLevel=ERROR'],
...['-o', 'StrictHostKeyChecking=no'],
...['-o', 'UserKnownHostsFile=/dev/null'],
...(proxyCommand && proxyCommand.length
? ['-o', `ProxyCommand=${proxyCommand.join(' ')}`]
: []),
`${username}@${hostname}`,
...(cmd ? [cmd] : []),
];
}
/**
* Execute the given command on a local balenaOS device over ssh.
* @param cmd Shell command to execute on the device
* @param hostname Device's hostname or IP address
* @param port SSH server TCP port number or 'local' (22222) or 'cloud' (22)
* @param stdin Readable stream to pipe to the remote command stdin,
* or 'ignore' or 'inherit' as documented in the child_process.spawn function.
* @param stdout Writeable stream to pipe from the remote command stdout,
* or 'ignore' or 'inherit' as documented in the child_process.spawn function.
* @param stderr Writeable stream to pipe from the remote command stdout,
* or 'ignore' or 'inherit' as documented in the child_process.spawn function.
* @param username SSH username for authorization. With balenaOS 2.44.0 or
* later, it can be a balenaCloud username.
* @param verbose Produce debugging output
*/
export async function runRemoteCommand({
cmd = '',
hostname,
port,
proxyCommand,
stdin = 'inherit',
stdout = 'inherit',
stderr = 'inherit',
username = 'root',
verbose = false,
}: SshRemoteCommandOpts & {
stdin?: 'ignore' | 'inherit' | NodeJS.ReadableStream;
stdout?: 'ignore' | 'inherit' | NodeJS.WritableStream;
stderr?: 'ignore' | 'inherit' | NodeJS.WritableStream;
}): Promise<void> {
let ignoreStdin: boolean;
if (stdin === 'ignore') {
// Set ignoreStdin=true in order for the "ssh -n" option to be used to
// prevent the ssh client from using the CLI process stdin. In addition,
// stdin must be forced to 'inherit' (if it is not a readable stream) in
// order to work around a bug in older versions of the built-in Windows
// 10 ssh client that otherwise prints the following to stderr and
// hangs: "GetConsoleMode on STD_INPUT_HANDLE failed with 6"
// They actually fixed the bug in newer versions of the ssh client:
// https://github.com/PowerShell/Win32-OpenSSH/issues/856 but users
// have to manually download and install a new client.
ignoreStdin = true;
stdin = 'inherit';
} else {
ignoreStdin = false;
}
const { which } = await import('./which');
const program = await which('ssh');
const args = sshArgsForRemoteCommand({
cmd,
hostname,
ignoreStdin,
port,
proxyCommand,
username,
verbose,
});
if (process.env.DEBUG) {
const logger = (await import('./logger')).getLogger();
logger.logDebug(`Executing [${program},${args}]`);
}
const stdio: StdioOptions = [
typeof stdin === 'string' ? stdin : 'pipe',
typeof stdout === 'string' ? stdout : 'pipe',
typeof stderr === 'string' ? stderr : 'pipe',
];
let exitCode: number | undefined;
let exitSignal: NodeJS.Signals | undefined;
try {
[exitCode, exitSignal] = await new Promise<[number, NodeJS.Signals]>(
(resolve, reject) => {
const ps = spawn(program, args, { stdio })
.on('error', reject)
.on('close', (code, signal) => resolve([code, signal]));
if (ps.stdin && stdin && typeof stdin !== 'string') {
stdin.pipe(ps.stdin);
}
if (ps.stdout && stdout && typeof stdout !== 'string') {
ps.stdout.pipe(stdout);
}
if (ps.stderr && stderr && typeof stderr !== 'string') {
ps.stderr.pipe(stderr);
}
},
);
} catch (error) {
const msg = [
`ssh failed with exit code=${exitCode} signal=${exitSignal}:`,
`[${program}, ${args.join(', ')}]`,
...(error ? [`${error}`] : []),
];
throw new ExpectedError(msg.join('\n'));
}
if (exitCode || exitSignal) {
throw new RemoteCommandError(cmd, exitCode, exitSignal);
}
}
/**
* Execute the given command on a local balenaOS device over ssh.
* Capture stdout and/or stderr to Buffers and return them.
*
* @param deviceIp IP address of the local device
* @param cmd Shell command to execute on the device
* @param opts Options
* @param opts.username SSH username for authorization. With balenaOS 2.44.0 or
* later, it may be a balenaCloud username. Otherwise, 'root'.
* @param opts.stdin Passed through to the runRemoteCommand function
* @param opts.stdout If 'capture', capture stdout to a Buffer.
* @param opts.stderr If 'capture', capture stdout to a Buffer.
*/
export async function getRemoteCommandOutput({
cmd,
hostname,
port,
proxyCommand,
stdin = 'ignore',
stdout = 'capture',
stderr = 'capture',
username = 'root',
verbose = false,
}: SshRemoteCommandOpts & {
stdin?: 'ignore' | 'inherit' | NodeJS.ReadableStream;
stdout?: 'capture' | 'ignore' | 'inherit' | NodeJS.WritableStream;
stderr?: 'capture' | 'ignore' | 'inherit' | NodeJS.WritableStream;
}): Promise<{ stdout: Buffer; stderr: Buffer }> {
const { Writable } = await import('stream');
const stdoutChunks: Buffer[] = [];
const stderrChunks: Buffer[] = [];
const stdoutStream = new Writable({
write(chunk: Buffer, _enc, callback) {
stdoutChunks.push(chunk);
callback();
},
});
const stderrStream = new Writable({
write(chunk: Buffer, _enc, callback) {
stderrChunks.push(chunk);
callback();
},
});
await runRemoteCommand({
cmd,
hostname,
port,
proxyCommand,
stdin,
stdout: stdout === 'capture' ? stdoutStream : stdout,
stderr: stderr === 'capture' ? stderrStream : stderr,
username,
verbose,
});
return {
stdout: Buffer.concat(stdoutChunks),
stderr: Buffer.concat(stderrChunks),
};
}
/** Convenience wrapper for getRemoteCommandOutput */
export async function getLocalDeviceCmdStdout(
hostname: string,
cmd: string,
stdout: 'capture' | 'ignore' | 'inherit' | NodeJS.WritableStream = 'capture',
): Promise<Buffer> {
const port = 'local';
return (
await getRemoteCommandOutput({
cmd,
hostname,
port,
stdout,
stderr: 'inherit',
username: await findBestUsernameForDevice(hostname, port),
})
).stdout;
}
/**
* Run a trivial 'exit 0' command over ssh on the target hostname (typically the
* IP address of a local device) with the 'root' username, in order to determine
* whether root authentication suceeds. It should succeed with development
* variants of balenaOS and fail with production variants, unless a ssh key was
* added to the device's 'config.json' file.
* @return True if succesful, false on any errors.
*/
export const isRootUserGood = _.memoize(async (hostname: string, port) => {
try {
await runRemoteCommand({ cmd: 'exit 0', hostname, port, ...stdioIgnore });
} catch (e) {
return false;
}
return true;
});
/**
* Determine whether the given local device (hostname or IP address) should be
* accessed as the 'root' user or as a regular cloud user (balenaCloud or
* openBalena). Where possible, the root user is preferable because:
* - It allows ssh to be used in air-gapped scenarios (no internet access).
* Logging in as a regular user requires the device to fetch public keys from
* the cloud backend.
* - Root authentication is significantly faster for local devices (a fraction
* of a second versus 5+ seconds).
* - Non-root authentication requires balenaOS v2.44.0 or later, so not (yet)
* universally possible.
*/
export const findBestUsernameForDevice = _.memoize(
async (hostname: string, port): Promise<string> => {
let username: string | undefined;
if (await isRootUserGood(hostname, port)) {
username = 'root';
} else {
const { getCachedUsername } = await import('./bootstrap');
username = (await getCachedUsername())?.username;
}
if (!username) {
const { stripIndent } = await import('./lazy');
throw new ExpectedError(stripIndent`
SSH authentication failed for 'root@${hostname}'.
Please login with 'balena login' for alternative authentication.`);
}
return username;
},
);
/**
* Return a device's balenaOS release by executing 'cat /etc/os-release'
* over ssh to the given deviceIp address. The result is cached with
* lodash's memoize.
*/
export const getDeviceOsRelease = _.memoize(async (hostname: string) =>
(await getLocalDeviceCmdStdout(hostname, 'cat /etc/os-release')).toString(),
);
function sshErrorMessage(cmd: string, exitSignal?: string, exitCode?: number) {
const msg: string[] = [];
cmd = cmd ? `Remote command "${cmd}"` : 'Process';
if (exitSignal) {
msg.push(`SSH: ${cmd} terminated with signal "${exitSignal}"`);
} else {
msg.push(`SSH: ${cmd} exited with non-zero status code "${exitCode}"`);
switch (exitCode) {
case 255:
msg.push(`
Are the SSH keys correctly configured in balenaCloud? See:
https://www.balena.io/docs/learn/manage/ssh-access/#add-an-ssh-key-to-balenacloud`);
msg.push('Are you accidentally using `sudo`?');
}
}
return msg.join('\n');
} | the_stack |
import Dimensions = Utils.Measurements.Dimensions;
import DisplayObject = etch.drawing.DisplayObject;
import IEventArgs = nullstone.IEventArgs;
import Point = etch.primitives.Point;
import Stage = etch.drawing.Stage;
import {AnimationsLayer} from './UI/AnimationsLayer';
import {CreateNew} from './UI/CreateNew';
import {Commands} from './Commands';
import {CompositionLoadedEventArgs} from './CompositionLoadedEventArgs';
import {ConnectionLines} from './UI/ConnectionLines';
import {Controller} from './Blocks/Interaction/Controller';
import {Header} from './UI/Header';
import {IApp} from './IApp';
import {IBlock} from './Blocks/IBlock';
import {IEffect} from './Blocks/IEffect';
import {IOperation} from './Core/Operations/IOperation';
import {ISource} from './Blocks/ISource';
import {LaserBeams} from './LaserBeams';
import {MessagePanel} from './UI/MessagePanel';
import {OptionsPanel} from './UI/OptionsPanel';
import {ParticleLayer} from './ParticleLayer';
import {PowerEffect} from './Blocks/Power/PowerEffect';
import {PowerSource} from './Blocks/Power/PowerSource';
import {RecorderPanel} from './UI/RecorderPanel';
import {SettingsPanel} from './UI/SettingsPanel';
import {SharePanel} from './UI/SharePanel';
import {SoundcloudPanel} from './UI/SoundcloudPanel';
import {StageDragger as MainSceneDragger} from './UI/StageDragger';
import {ToolTip} from './UI/ToolTip';
import {TrashCan} from './UI/TrashCan';
import {Tutorial} from './UI/Tutorial';
import {TutorialHotspots} from './UI/TutorialHotspots';
import {ZoomButtons} from './UI/ZoomButtons';
declare var App: IApp;
declare var OptionTimeout: boolean; //TODO: better way than using global? Needs to stay in scope within a setTimeout though.
export class MainScene extends DisplayObject{
public Header: Header;
private _IsPointerDown: boolean = false;
private _PointerPoint: Point;
private _RecorderPanel: RecorderPanel;
private _SelectedBlock: IBlock;
private _SelectedBlockPosition: Point;
private _ToolTip: ToolTip;
private _ToolTipTimeout;
private _TrashCan: TrashCan;
public AnimationsLayer: AnimationsLayer;
public BlocksContainer: DisplayObject;
public ConnectionLines: ConnectionLines;
public CreateNew: CreateNew;
public IsDraggingABlock: boolean = false;
public LaserBeams: LaserBeams;
public MainSceneDragger: MainSceneDragger;
public MessagePanel: MessagePanel;
public OptionsPanel: OptionsPanel;
public Particles: ParticleLayer;
public SettingsPanel: SettingsPanel;
public SharePanel: SharePanel;
public SoundcloudPanel: SoundcloudPanel;
public Tutorial: Tutorial;
public TutorialHotspots: TutorialHotspots;
public ZoomButtons: ZoomButtons;
//-------------------------------------------------------------------------------------------
// SETUP
//-------------------------------------------------------------------------------------------
constructor() {
super();
}
Setup(){
super.Setup();
App.PointerInputManager.MouseDown.on((s: any, e: MouseEvent) => {
this.MouseDown(e);
}, this);
App.PointerInputManager.MouseUp.on((s: any, e: MouseEvent) => {
this.MouseUp(e);
}, this);
App.PointerInputManager.MouseMove.on((s: any, e: MouseEvent) => {
this.MouseMove(e);
}, this);
App.PointerInputManager.MouseWheel.on((s: any, e: MouseWheelEvent) => {
this.MouseWheel(e);
}, this);
App.PointerInputManager.TouchStart.on((s: any, e: TouchEvent) => {
this.TouchStart(e);
}, this);
App.PointerInputManager.TouchEnd.on((s: any, e: TouchEvent) => {
this.TouchEnd(e);
}, this);
App.PointerInputManager.TouchMove.on((s: any, e: TouchEvent) => {
this.TouchMove(e);
}, this);
App.OperationManager.OperationComplete.on((operation: IOperation) => {
this._Invalidate();
}, this);
// COMPOSITION LOADED //
App.CompositionLoaded.on((s: any, e: CompositionLoadedEventArgs) => {
this.CompositionLoaded(e);
}, this);
// FILE DRAGGING //
//App.DragFileInputManager.Dropped.on((s: any, e: any) => {
// e.stopPropagation();
// e.preventDefault();
// const b: Sampler = this.CreateBlockFromType(Sampler);
//
// var files = e.dataTransfer.files; // FileList object.
//
// App.Audio.AudioFileManager.DecodeFileData(files, (file: any, buffer: AudioBuffer) => {
// if (buffer) {
// //TODO: set the buffer of this newly created Sampler
// console.log(file.name + ' dropped');
// }
// });
//
//}, this);
//
//App.DragFileInputManager.DragEnter.on((s: any, e: any) => {
// console.log('file drag entered area');
//}, this);
//
//App.DragFileInputManager.DragMove.on((s: any, e: any) => {
// e.stopPropagation();
// e.preventDefault();
// console.log('file drag over');
//}, this);
//
//App.DragFileInputManager.DragLeave.on((s: any, e: any) => {
// console.log('file left drag area');
//}, this);
OptionTimeout = false; // todo: remove
// METRICS //
this._PointerPoint = new Point();
this._SelectedBlockPosition = new Point();
// Display Objects //
this.ConnectionLines = new ConnectionLines();
this.DisplayList.Add(this.ConnectionLines);
this.ConnectionLines.Init(this);
this.BlocksContainer = new DisplayObject();
this.DisplayList.Add(this.BlocksContainer);
this.BlocksContainer.Init(this);
this.LaserBeams = new LaserBeams();
this.DisplayList.Add(this.LaserBeams);
this.LaserBeams.Init(this);
this.Particles = new ParticleLayer();
this.DisplayList.Add(this.Particles);
this.Particles.Init(this);
this._ToolTip = new ToolTip();
this.DisplayList.Add(this._ToolTip);
this._ToolTip.Init(this);
this.AnimationsLayer = new AnimationsLayer();
this.DisplayList.Add(this.AnimationsLayer);
this.AnimationsLayer.Init(this);
this._RecorderPanel = new RecorderPanel();
this.DisplayList.Add(this._RecorderPanel);
this._RecorderPanel.Init(this);
this.ZoomButtons = new ZoomButtons();
this.DisplayList.Add(this.ZoomButtons);
this.ZoomButtons.Init(this);
this.MainSceneDragger = new MainSceneDragger();
this.DisplayList.Add(this.MainSceneDragger);
this.MainSceneDragger.Init(this);
this._TrashCan = new TrashCan();
this.DisplayList.Add(this._TrashCan);
this._TrashCan.Init(this);
this.Tutorial = new Tutorial();
this.DisplayList.Add(this.Tutorial);
this.Tutorial.Init(this);
this.OptionsPanel = new OptionsPanel();
this.DisplayList.Add(this.OptionsPanel);
this.OptionsPanel.Init(this);
this.Header = new Header();
this.DisplayList.Add(this.Header);
this.Header.Init(this);
this.CreateNew = new CreateNew();
this.DisplayList.Add(this.CreateNew);
this.CreateNew.Init(this);
this.TutorialHotspots = new TutorialHotspots();
this.DisplayList.Add(this.TutorialHotspots);
this.TutorialHotspots.Init(this);
this.SharePanel = new SharePanel();
this.DisplayList.Add(this.SharePanel);
this.SharePanel.Init(this);
this.SettingsPanel = new SettingsPanel();
this.DisplayList.Add(this.SettingsPanel);
this.SettingsPanel.Init(this);
this.SoundcloudPanel = new SoundcloudPanel();
this.DisplayList.Add(this.SoundcloudPanel);
this.SoundcloudPanel.Init(this);
this.MessagePanel = new MessagePanel();
this.DisplayList.Add(this.MessagePanel);
this.MessagePanel.Init(this);
this._Invalidate();
//console.log(App.Stage);
if(!App.CompositionId) {
this.Tutorial.CheckLaunch();
}
}
//-------------------------------------------------------------------------------------------
// UPDATE
//-------------------------------------------------------------------------------------------
Update() {
if (this.IsPaused) return;
super.Update();
}
//-------------------------------------------------------------------------------------------
// DRAW
//-------------------------------------------------------------------------------------------
Draw(): void {
super.Draw();
// BG //
App.FillColor(this.Ctx,App.Palette[0]);
this.Ctx.globalAlpha = 1;
this.Ctx.fillRect(0, 0, this.Width, this.Height);
}
//-------------------------------------------------------------------------------------------
// INTERACTION
//-------------------------------------------------------------------------------------------
// FIRST TOUCHES //
MouseDown(e: MouseEvent): void {
var position: Point = new Point(e.clientX, e.clientY + window.pageYOffset);
this._PointerDown(position);
}
MouseUp(e: MouseEvent): void {
var position: Point = new Point(e.clientX, e.clientY + window.pageYOffset);
this._PointerUp(position);
this._CheckHover(position);
}
MouseMove(e: MouseEvent): void {
var position: Point = new Point(e.clientX, e.clientY + window.pageYOffset);
this._PointerMove(position);
}
MouseWheel(e: MouseWheelEvent): void {
this._MouseWheel(e);
}
TouchStart(e: any){
var touch = e.touches[0]; // e.args.Device.GetTouchPoint(null);
var point = new Point(touch.clientX, touch.clientY + window.pageYOffset);
this._PointerDown(point);
}
TouchEnd(e: any){
var touch = e.changedTouches[0]; // e.args.Device.GetTouchPoint(null);
var point = new Point(touch.clientX, touch.clientY + window.pageYOffset);
this._PointerUp(point,true);
}
TouchMove(e: any){
var touch = e.touches[0]; // e.args.Device.GetTouchPoint(null);
var point = new Point(touch.clientX, touch.clientY + window.pageYOffset);
this._PointerMove(point);
}
// AGNOSTIC EVENTS //
private _PointerDown(point: Point) {
App.Metrics.ConvertToPixelRatioPoint(point);
if (!App.Stage.Splash.IsAnimationFinished) {
return;
}
this._IsPointerDown = true;
this._PointerPoint = point;
var UIInteraction: Boolean;
var collision: Boolean;
var tooltip = this._ToolTip;
var zoom = this.ZoomButtons;
var header = this.Header;
var soundcloud = this.SoundcloudPanel;
var share = this.SharePanel;
var settings = this.SettingsPanel;
var recorder = this._RecorderPanel;
var options = this.OptionsPanel;
var message = this.MessagePanel;
var create = this.CreateNew;
var tutorial = this.Tutorial;
// UI //
//UIInteraction = this._UIInteraction();
if (tooltip.Open) {
this.ToolTipClose();
}
if (message.Open && message.Hover) {
message.MouseDown(point);
return;
}
if (share.Open) {
share.MouseDown(point);
return;
}
if (settings.Open) {
settings.MouseDown(point);
return;
}
if (soundcloud.Open) {
soundcloud.MouseDown(point);
return;
}
if (!share.Open && !settings.Open && !soundcloud.Open) {
if (tutorial.SplashOpen) {
tutorial.SplashMouseDown(point);
if (tutorial.Hover) {
return;
}
}
create.MouseDown(point);
if (create.Hover) {
return;
}
header.MouseDown(point);
if (header.MenuOver) {
return;
}
zoom.MouseDown(point);
if (zoom.InRoll || zoom.OutRoll) {
return;
}
if (options.Scale === 1) {
options.MouseDown(point.x,point.y); // to do : unsplit point
if (options.Hover) {
return;
}
}
if (tutorial.Open) {
tutorial.MouseDown(point);
if (tutorial.Hover) {
return;
}
}
recorder.MouseDown(point);
if (recorder.Hover) {
return;
}
}
// BLOCK CLICK //
//if (!UIInteraction) {
collision = this._CheckCollision(point);
//}
if (collision) {
this.IsDraggingABlock = true; // for trashcan to know
this._SelectedBlockPosition = this.SelectedBlock.Position; // memory of start position
}
// MainScene DRAGGING //
if (!collision){
//if (!collision && !UIInteraction){
this.MainSceneDragger.MouseDown(point);
}
//this.ConnectionLines.UpdateList();
}
private _PointerUp(point: Point, isTouch?: boolean) {
App.Metrics.ConvertToPixelRatioPoint(point);
this._IsPointerDown = false;
if (this.IsDraggingABlock) {
var blockDelete = this._TrashCan.MouseUp();
}
this.IsDraggingABlock = false;
if (!blockDelete) {
// BLOCK //
if (this.SelectedBlock){
if (this.SelectedBlock.IsPressed){
this.SelectedBlock.MouseUp();
// if the block has moved, create an undoable operation.
if (!Point.isEqual(this.SelectedBlock.Position, this.SelectedBlock.LastPosition)){
App.CommandManager.ExecuteCommand(Commands.MOVE_BLOCK, this.SelectedBlock);
}
}
}
// OPEN PANEL //
if (OptionTimeout) {
this.OptionsPanel.Open(this.SelectedBlock);
}
}
// UI //
if (this.SharePanel.Open) {
this.SharePanel.MouseUp(point,isTouch);
}
else if (this.SettingsPanel.Open) {
this.SettingsPanel.MouseUp(point);
} else {
this.Header.MouseUp();
if (this.OptionsPanel.Scale === 1) {
this.OptionsPanel.MouseUp();
}
this.MainSceneDragger.MouseUp();
}
//this.ConnectionLines.UpdateList();
}
private _PointerMove(point: Point){
App.Metrics.ConvertToPixelRatioPoint(point);
App.Canvas.Style.cursor = "default";
this._CheckHover(point);
// BLOCK //
if (this.SelectedBlock){
this.SelectedBlock.MouseMove(point);
this._CheckProximity();
if (this.IsDraggingABlock && (Math.round(this.SelectedBlock.Position.x) !== Math.round(this._SelectedBlockPosition.x) || Math.round(this.SelectedBlock.Position.y) !== Math.round(this._SelectedBlockPosition.y) ) ) {
this._SelectedBlockPosition = this.SelectedBlock.Position; // new grid position
this._ABlockHasBeenMoved();
if (this.OptionsPanel.Scale === 1) {
this.OptionsPanel.Close();
}
}
}
// UI //
if (this.OptionsPanel.Scale === 1) {
this.OptionsPanel.MouseMove(point.x,point.y);
}
if (this.SharePanel.Open) {
this.SharePanel.MouseMove(point);
}
if (this.SettingsPanel.Open) {
this.SettingsPanel.MouseMove(point);
}
if (this.SoundcloudPanel.Open) {
this.SoundcloudPanel.MouseMove(point);
}
if (this.MessagePanel.Open) {
this.MessagePanel.MouseMove(point);
}
this.Header.MouseMove(point);
this._RecorderPanel.MouseMove(point);
this.CreateNew.MouseMove(point);
if (this.Tutorial.Open || this.Tutorial.SplashOpen) {
this.Tutorial.MouseMove(point);
}
this.ZoomButtons.MouseMove(point);
this._TrashCan.MouseMove(point);
this.MainSceneDragger.MouseMove(point);
}
private _MouseWheel(e: MouseWheelEvent): void {
this.ZoomButtons.MouseWheel(e);
}
// PROXIMITY CHECK //
private _CheckProximity(){
// loop through all Source blocks checking proximity to Effect blocks.
// if within CatchmentArea, add Effect to Source.Effects and add Source to Effect.Sources
for (var j = 0; j < App.Sources.length; j++) {
var source: ISource = App.Sources[j];
for (var i = 0; i < App.Effects.length; i++) {
var effect: IEffect = App.Effects[i];
// if a source is close enough to the effect, add the effect
// to its internal list.
var catchmentArea = App.Metrics.ConvertGridUnitsToAbsolute(new Point(effect.CatchmentArea, effect.CatchmentArea));
var distanceFromEffect = source.DistanceFrom(App.Metrics.ConvertGridUnitsToAbsolute(effect.Position));
if (distanceFromEffect <= catchmentArea.x) {
// if the effect isn't already in the sources connections list
if (!source.Connections.Contains(effect)){
if ( !(source instanceof PowerSource && effect instanceof Controller) && ((source instanceof PowerSource && effect instanceof PowerEffect) || !(source instanceof PowerSource)) ) {
//Add sources to effect
effect.AddSource(source);
// Add effect to source
source.AddEffect(effect);
this._Invalidate();
App.Audio.ConnectionManager.Update();
}
}
} else {
// if the source already has the effect on its internal list
// remove it as it's now too far away.
if (source.Connections.Contains(effect)){
// Remove source from effect
effect.RemoveSource(source);
// Remove effect from source
source.RemoveEffect(effect);
this._Invalidate();
App.Audio.ConnectionManager.Update();
}
}
}
}
}
// COLLISION CHECK ON BLOCK //
private _CheckCollision(point: Point): Boolean {
// LOOP BLOCKS //
for (var i = App.Blocks.length - 1; i >= 0; i--) {
var block:IBlock = App.Blocks[i];
if (block.HitTest(point)) {
block.MouseDown();
this.SelectedBlock = block;
// TIMER TO CHECK BETWEEN SINGLE CLICK OR DRAG //
OptionTimeout = true;
setTimeout(function() {
OptionTimeout = false;
}, App.Config.SingleClickTime);
return true;
}
}
// CLOSE OPTIONS IF NO BLOCK CLICKED //
this.OptionsPanel.Close();
return false;
}
// CHECK FOR HOVERING OVER BLOCK (TOOLTIP) //
private _CheckHover(point: Point) {
var panelCheck = false;
var blockHover = false;
var panel = this._ToolTip;
// CHECK BLOCKS FOR HOVER //
if (this.OptionsPanel.Scale === 1) {
panelCheck = Dimensions.hitRect(this.OptionsPanel.Position.x,this.OptionsPanel.Position.y - (this.OptionsPanel.Size.height*0.5), this.OptionsPanel.Size.width,this.OptionsPanel.Size.height,point.x,point.y);
}
if (!panelCheck && !this._IsPointerDown) {
for (var i = App.Blocks.length - 1; i >= 0; i--) {
var block:IBlock = App.Blocks[i];
if (block.HitTest(point)) {
// GET BLOCK NAME //
//if (block.OptionsForm) {
panel.Name = block.BlockName;
var blockPos = App.Metrics.PointOnGrid(block.Position);
panel.Position.x = blockPos.x;
panel.Position.y = blockPos.y;
blockHover = true;
//}
break;
}
}
}
// OPEN TOOLTIP IF NOT ALREADY OPEN //
if (blockHover && !panel.Open && !this.OptionsPanel.Opening) {
panel.Open = true;
if (panel.Alpha>0) {
panel.AlphaTo(panel, 100, 600);
} else {
this._ToolTipTimeout = setTimeout(function() {
if (panel.Alpha === 0) {
panel.AlphaTo(panel, 100, 600);
}
},550);
}
}
// CLOSE IF NO LONGER HOVERING //
if (!blockHover && panel.Open) {
this.ToolTipClose();
}
}
public ToolTipClose() {
var panel = this._ToolTip;
clearTimeout(this._ToolTipTimeout);
panel.StopTween();
panel.AlphaTo(panel, 0, 200);
panel.Open = false;
}
private _ABlockHasBeenMoved() {
this.LaserBeams.UpdateAllLasers = true;
this.ConnectionLines.UpdateList();
}
// IS ANYTHING ON THE UI LEVEL BEING CLICKED //
private _UIInteraction() {
var zoom = this.ZoomButtons;
var header = this.Header;
var share = this.SharePanel;
var settings = this.SettingsPanel;
var soundcloud = this.SoundcloudPanel;
var recorder = this._RecorderPanel;
var options = this.OptionsPanel;
var message = this.MessagePanel;
var create = this.CreateNew;
var tutorial = this.Tutorial;
if (zoom.InRoll || zoom.OutRoll || header.MenuOver || share.Open || settings.Open || soundcloud.Open || recorder.Hover || (message.Open && message.Hover) || create.Hover || ((tutorial.Open || tutorial.SplashOpen) && tutorial.Hover) || (options.Scale===1 && options.Hover)) {
return true;
}
return false;
}
//-------------------------------------------------------------------------------------------
// BLOCKS
//-------------------------------------------------------------------------------------------
get SelectedBlock(): IBlock {
return this._SelectedBlock;
}
set SelectedBlock(block: IBlock) {
// if setting the selected block to null (or falsey)
// if there's already a selected block, set its
// IsSelected to false.
if (!block && this._SelectedBlock){
this._SelectedBlock.IsSelected = false;
this._SelectedBlock = null;
}
else {
if (this._SelectedBlock){
this._SelectedBlock.IsSelected = false;
}
if (block) {
block.IsSelected = true;
this._SelectedBlock = block;
this.BlockToFront(block);
}
}
}
BlockToFront(block: IBlock){
this.BlocksContainer.DisplayList.ToFront(block);
}
private _Invalidate(){
this._ValidateBlocks();
this._CheckProximity();
this.CreateNew.CheckState();
this.Tutorial.CheckTask();
}
_ValidateBlocks() {
for (var i = 0; i < App.Sources.length; i++){
var src: ISource = App.Sources[i];
src.ValidateEffects();
}
for (var i = 0; i < App.Effects.length; i++){
var effect: IEffect = App.Effects[i];
effect.ValidateSources();
}
}
DuplicateParams(params: any): any {
var paramsCopy = {};
for (var key in params) {
paramsCopy[""+key] = params[""+key];
}
return paramsCopy;
}
CreateBlockFromType<T extends IBlock>(t: {new(): T; }, params?: any): T {
var block: T = new t();
block.Id = App.GetBlockId();
block.Position = App.Metrics.CursorToGrid(this._PointerPoint);
if (params) block.Params = this.DuplicateParams(params);
//TODO:
//if (block instanceof Recorder) {
// (<any>block).Duplicate((<any>block).BufferSource.buffer);
//}
block.Init(this);
block.Type = t;
App.CommandManager.ExecuteCommand(Commands.CREATE_BLOCK, block);
block.MouseDown();
this.SelectedBlock = block;
this.BlockToFront(block);
this.IsDraggingABlock = true;
return block;
}
// GETS CALLED WHEN LOADING FROM SHARE URL //
CompositionLoaded(e: CompositionLoadedEventArgs): void {
// add blocks to display list
this.BlocksContainer.DisplayList.AddRange(App.Blocks);
// initialise blocks (give them a ctx to draw to)
for (var i = 0; i < this.BlocksContainer.DisplayList.Count; i++){
var block: IBlock = <IBlock>this.BlocksContainer.DisplayList.GetValueAt(i);
block.Init(this);
}
if (this.MainSceneDragger) {
this.MainSceneDragger.Destination = new Point(e.SaveFile.DragOffset.x, e.SaveFile.DragOffset.y);
}
this.ZoomButtons.UpdateSlot(e.SaveFile.ZoomLevel);
this.SharePanel.Reset();
App.Metrics.UpdateGridScale();
// validate blocks and give us a little time to stabilise / bring in volume etc
this._Invalidate();
// Dont start yet if splash paused //
if (App.Stage.Splash.IOSPause) {
return;
}
this.Begin();
}
Begin() {
// Fade In Audio //
setTimeout(() => {
this.Play();
this.ConnectionLines.UpdateList();
// App.Audio.Master.volume.linearRampToValue(App.Audio.MasterVolume,5); //This breaks audio volume slider
}, 2400);
//TODO: THIS IS SHIT - For some reason fading in the volume using the above method breaks the volume slider
// Come back to this once useful functions have been abstracted from Tone into a simplified version
var volume = -30;
var volumeFade = setInterval(() => {
if (volume < App.Audio.MasterVolume) {
App.Audio.Master.volume.value = volume;
volume += 2;
} else {
clearInterval(volumeFade);
}
}, 70);
}
//-------------------------------------------------------------------------------------------
// OPERATIONS
//-------------------------------------------------------------------------------------------
DeleteSelectedBlock(){
if (!this.SelectedBlock) return;
if (this.SelectedBlock.IsPressed) {
this.SelectedBlock.MouseUp();
}
this.OptionsPanel.Close();
App.CommandManager.ExecuteCommand(Commands.DELETE_BLOCK, this.SelectedBlock);
//this.DeleteBlock(this.SelectedBlock);
this.SelectedBlock = null;
// Update drawing of connection lines //
setTimeout(() => {
this.ConnectionLines.UpdateList();
}, 1);
}
DeleteBlock(block) {
this.BlocksContainer.DisplayList.Remove(block);
App.Blocks.remove(block);
//this.SelectedBlock.Stop(); //LP commented this out because if you have a keyboard and a source connected and call reset you get errors
block.Dispose();
block = null;
}
DeleteAllBlocks() {
var blockList = [];
for (var i=0; i<App.Blocks.length; i++) {
blockList.push(App.Blocks[i]);
}
for (i=0; i<blockList.length; i++) {
this.DeleteBlock(blockList[i]);
}
}
// CLEAR SCENE OF ALL BLOCKS, RESET SESSION //
ResetScene() {
if (this.Tutorial.Open) {
this.Tutorial.ClosePanel();
}
// delete all blocks //
this.DeleteAllBlocks();
this.Tutorial.WatchedBlocks = [];
this.ConnectionLines.UpdateList();
this.SelectedBlock = null;
// reset zoom & drag //
App.DragOffset.x = 0;
App.DragOffset.y = 0;
this.ZoomButtons.CurrentSlot = 2;
this.MainSceneDragger.Destination = new Point(App.DragOffset.x,App.DragOffset.y);
App.ZoomLevel = 1;
App.Particles = [];
App.Metrics.UpdateGridScale();
this.OptionsPanel.Close();
// reset session //
App.AddressBarManager.StripURL();
App.CompositionId = null;
App.SessionId = null;
this.SharePanel.Reset();
// invalidate //
this._Invalidate();
}
Resize(): void {
this.OptionsPanel.Close();
this.Header.Populate(this.Header.MenuJson);
this.SettingsPanel.Populate(this.SettingsPanel.MenuJson);
}
} | the_stack |
import { Component, OnInit } from '@angular/core';
import { Validators } from '@angular/forms';
import { takeUntil } from 'rxjs/operators';
// App imports
import { APIClient } from '../../../../swagger/api-client.service';
import { AppEdition } from 'src/app/shared/constants/branding.constants';
import AppServices from '../../../../shared/service/appServices';
import { AwsField, VpcType } from "../aws-wizard.constants";
import { AwsFieldDisplayOrder, AwsNodeSettingStepMapping } from './node-setting-step.fieldmapping';
import { AWSNodeAz } from '../../../../swagger/models/aws-node-az.model';
import { AWSSubnet } from '../../../../swagger/models/aws-subnet.model';
import { AzRelatedFieldsArray } from '../aws-wizard.component';
import { NodeSettingField } from '../../wizard/shared/components/steps/node-setting-step/node-setting-step.fieldmapping';
import { NodeSettingStepDirective } from '../../wizard/shared/components/steps/node-setting-step/node-setting-step.component';
import { StepMapping } from '../../wizard/shared/field-mapping/FieldMapping';
import { TanzuEventType } from '../../../../shared/service/Messenger';
import { ValidationService } from '../../wizard/shared/validation/validation.service';
export interface AzNodeTypes {
awsNodeAz1: Array<string>,
awsNodeAz2: Array<string>,
awsNodeAz3: Array<string>
}
export interface FilteredAzs {
awsNodeAz1: {
publicSubnets: Array<AWSSubnet>;
privateSubnets: Array<AWSSubnet>;
},
awsNodeAz2: {
publicSubnets: Array<AWSSubnet>;
privateSubnets: Array<AWSSubnet>;
},
awsNodeAz3: {
publicSubnets: Array<AWSSubnet>;
privateSubnets: Array<AWSSubnet>;
}
}
const AZS = [
AwsField.NODESETTING_AZ_1,
AwsField.NODESETTING_AZ_2,
AwsField.NODESETTING_AZ_3,
];
const WORKER_NODE_INSTANCE_TYPES = [
NodeSettingField.WORKER_NODE_INSTANCE_TYPE,
AwsField.NODESETTING_WORKERTYPE_2,
AwsField.NODESETTING_WORKERTYPE_3
];
const PUBLIC_SUBNETS = [
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_1,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_2,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_3
];
const PRIVATE_SUBNET = [
AwsField.NODESETTING_VPC_PRIVATE_SUBNET_1,
AwsField.NODESETTING_VPC_PRIVATE_SUBNET_2,
AwsField.NODESETTING_VPC_PRIVATE_SUBNET_3,
];
const VPC_SUBNETS = [...PUBLIC_SUBNETS, ...PRIVATE_SUBNET];
enum vpcType {
EXISTING = 'existing'
}
@Component({
selector: 'app-node-setting-step',
templateUrl: './node-setting-step.component.html',
styleUrls: ['./node-setting-step.component.scss']
})
export class NodeSettingStepComponent extends NodeSettingStepDirective<string> implements OnInit {
APP_EDITION: any = AppEdition;
vpcType: string;
nodeAzs: Array<AWSNodeAz> = [];
azNodeTypes: AzNodeTypes = {
awsNodeAz1: [],
awsNodeAz2: [],
awsNodeAz3: []
};
publicSubnets: Array<AWSSubnet> = new Array<AWSSubnet>();
privateSubnets: Array<AWSSubnet> = new Array<AWSSubnet>();
filteredAzs: FilteredAzs = {
awsNodeAz1: {
publicSubnets: [],
privateSubnets: []
},
awsNodeAz2: {
publicSubnets: [],
privateSubnets: []
},
awsNodeAz3: {
publicSubnets: [],
privateSubnets: []
}
};
config = {
displayKey: 'description',
search: true,
height: 'auto',
placeholder: 'Select',
customComparator: () => { },
moreText: 'more',
noResultsFound: 'No results found!',
searchPlaceholder: 'Search',
searchOnKey: 'name',
clearOnSelection: false,
inputDirection: 'ltr'
};
airgappedVPC = false;
constructor(protected validationService: ValidationService,
private apiClient: APIClient) {
super(validationService);
}
protected createStepMapping(): StepMapping {
// AWS has a bunch of extra fields (related to AZs) over and above the default base class field mapping
const result = { fieldMappings: [ ...super.createStepMapping().fieldMappings, ...AwsNodeSettingStepMapping.fieldMappings]};
// The worker node instance in the base class is used as workerNodeInstance1 for AWS; it needs diff label and requiresBackendData
const workerNodeInstanceType = AppServices.fieldMapUtilities.getFieldMapping(NodeSettingField.WORKER_NODE_INSTANCE_TYPE, result);
workerNodeInstanceType.label = 'AZ1 WORKER NODE INSTANCE TYPE';
workerNodeInstanceType.requiresBackendData = true;
return result;
}
protected onProdInstanceTypeChange(prodNodeType: string) {
// AWS sets the worker instance in response to the AZ selection, not the prod instance type selection
}
protected onDevInstanceTypeChange(devNodeType: string) {
// AWS sets the worker instance in response to the AZ selection, not the dev instance type selection
}
protected listenToEvents() {
super.listenToEvents();
AppServices.messenger.subscribe<boolean>(TanzuEventType.AWS_AIRGAPPED_VPC_CHANGE, event => {
this.airgappedVPC = event.payload;
if (this.airgappedVPC) { // public subnet IDs shouldn't be provided
PUBLIC_SUBNETS.forEach(f => {
const control = this.getControl(f);
control.setValue('');
control.disable();
})
} else { // public subnet IDs are required
PUBLIC_SUBNETS.forEach(f => {
this.getControl(f).enable();
})
}
});
AppServices.messenger.subscribe(TanzuEventType.AWS_REGION_CHANGED, () => {
if (this.formGroup.get(AwsField.NODESETTING_AZ_1)) {
this.publicSubnets = [];
this.privateSubnets = [];
this.clearSubnetData();
this.clearAzs();
this.clearSubnets();
}
}, this.unsubscribe);
AppServices.messenger.subscribe<{ vpcType: string }>(TanzuEventType.AWS_VPC_TYPE_CHANGED, event => {
this.vpcType = event.payload.vpcType;
if (this.vpcType !== vpcType.EXISTING) {
this.clearSubnets();
}
this.updateVpcSubnets();
// clear az selection
this.clearAzs();
[...AZS, ...WORKER_NODE_INSTANCE_TYPES, ...VPC_SUBNETS].forEach(
field => this.getControl(field).updateValueAndValidity()
);
});
AppServices.messenger.subscribe(TanzuEventType.AWS_VPC_CHANGED, () => {
this.clearAzs();
this.clearSubnets();
});
AzRelatedFieldsArray.forEach(azRelatedFields => {
this.registerOnValueChange(azRelatedFields.az, (newlySelectedAz) => {
this.filterSubnetsByAZ(azRelatedFields.az, newlySelectedAz);
this.setSubnetFieldsWithOnlyOneOption(azRelatedFields.az);
this.updateWorkerNodeInstanceTypes(azRelatedFields.az, newlySelectedAz, azRelatedFields.workerNodeInstanceType);
});
});
}
protected subscribeToServices() {
AppServices.dataServiceRegistrar.stepSubscribe<AWSSubnet>(this, TanzuEventType.AWS_GET_SUBNETS, this.onFetchedSubnets.bind(this));
AppServices.dataServiceRegistrar.stepSubscribe<string>(this, TanzuEventType.AWS_GET_NODE_TYPES, this.onFetchedNodeTypes.bind(this));
AppServices.dataServiceRegistrar.stepSubscribe<AWSNodeAz>(this, TanzuEventType.AWS_GET_AVAILABILITY_ZONES,
this.onFetchedAzs.bind(this));
}
private onFetchedAzs(availabilityZones: Array<AWSNodeAz>) {
this.nodeAzs = availabilityZones;
}
private onFetchedSubnets(subnets: Array<AWSSubnet>) {
this.publicSubnets = subnets.filter(obj => { return obj.isPublic });
this.privateSubnets = subnets.filter(obj => { return !obj.isPublic });
AZS.forEach(az => { this.filterSubnetsByAZ(az, this.getFieldValue(az)); });
this.setSubnetFieldsFromSavedValues();
}
private onFetchedNodeTypes(nodeTypes: Array<string>) {
this.nodeTypes = nodeTypes.sort();
// The validation is based on the value of this.nodeTypes. Whenever we update this.nodeTypes,
// the corresponding validation should be updated as well. e.g. the users came to the node-settings
// step before the api responses. Then an empty array will be passed to the validation isValidNameInList.
// It will cause the selected option to be invalid all the time.
if (this.isClusterPlanDev) {
const devInstanceType = this.nodeTypes.length === 1 ? this.nodeTypes[0] :
this.formGroup.get(NodeSettingField.INSTANCE_TYPE_DEV).value;
this.resurrectField(NodeSettingField.INSTANCE_TYPE_DEV,
[Validators.required, this.validationService.isValidNameInList(this.nodeTypes)],
devInstanceType);
} else {
const prodInstanceType = this.nodeTypes.length === 1 ? this.nodeTypes[0] :
this.formGroup.get(NodeSettingField.INSTANCE_TYPE_PROD).value;
this.resurrectField(NodeSettingField.INSTANCE_TYPE_PROD,
[Validators.required, this.validationService.isValidNameInList(this.nodeTypes)],
prodInstanceType);
}
}
protected setControlPlaneToProd() {
super.setControlPlaneToProd();
this.updateVpcSubnets();
for (let i = 0; i < AZS.length; i++) {
const thisAZ = AZS[i];
const otherAZs = this.otherAZs(thisAZ);
const thisAZcontrol = this.getControl(thisAZ);
thisAZcontrol.setValidators([
Validators.required,
this.validationService.isUniqueAz([
this.getControl(otherAZs[0]),
this.getControl(otherAZs[1]) ])
]);
this.setFieldWithStoredValue(thisAZ, this.supplyStepMapping());
}
if (!this.modeClusterStandalone) {
WORKER_NODE_INSTANCE_TYPES.forEach((field, index) => {
// only populated the worker node instance type if the associated AZ has a value
if (this.getFieldValue(AZS[index])) {
this.resurrectFieldWithStoredValue(field.toString(), this.supplyStepMapping(), [Validators.required]);
} else {
this.resurrectField(field.toString(), [Validators.required]);
}
});
}
}
protected setControlPlaneToDev() {
super.setControlPlaneToDev();
this.updateVpcSubnets();
const prodFields = [
AwsField.NODESETTING_AZ_2,
AwsField.NODESETTING_AZ_3,
AwsField.NODESETTING_WORKERTYPE_2,
AwsField.NODESETTING_WORKERTYPE_3,
NodeSettingField.INSTANCE_TYPE_PROD
];
prodFields.forEach(attr => this.disarmField(attr.toString(), true));
if (this.nodeAzs && this.nodeAzs.length === 1) {
this.setControlValueSafely(AwsField.NODESETTING_AZ_1, this.nodeAzs[0].name);
} else {
this.setFieldWithStoredValue(AwsField.NODESETTING_AZ_1, this.supplyStepMapping());
}
}
// returns an array of the other two AZs (used to populate a validator that ensures unique AZs are selected)
private otherAZs(targetAz: AwsField): AwsField[] {
return AZS.filter((field, index, arr) => { return field !== targetAz });
}
get workerNodeInstanceType1Value() {
return this.getFieldValue(NodeSettingField.WORKER_NODE_INSTANCE_TYPE);
}
get workerNodeInstanceType2Value() {
return this.getFieldValue(AwsField.NODESETTING_WORKERTYPE_2);
}
get workerNodeInstanceType3Value() {
return this.getFieldValue(AwsField.NODESETTING_WORKERTYPE_3);
}
// public for testing
clearAzs() {
AZS.forEach(az => this.clearControlValue(az));
}
// public for testing
clearSubnets() {
VPC_SUBNETS.forEach(vpcSubnet => this.clearControlValue(vpcSubnet));
}
// public for testing
clearSubnetData() {
AZS.forEach(az => {
this.filteredAzs[az.toString()].publicSubnets = [];
this.filteredAzs[az.toString()].privateSubnets = [];
});
}
filterSubnetsByAZ(azControlName, az): void {
if (this.vpcType === vpcType.EXISTING && azControlName !== '' && az !== '') {
this.filteredAzs[azControlName].publicSubnets = this.filterSubnetArrayByAZ(az, this.publicSubnets);
this.filteredAzs[azControlName].privateSubnets = this.filterSubnetArrayByAZ(az, this.privateSubnets);
}
}
private filterSubnetArrayByAZ(az: string, subnets: AWSSubnet[]): AWSSubnet[] {
return (!subnets) ? [] : subnets.filter(subnet => { return subnet.availabilityZoneName === az; });
}
private setSubnetFieldsWithOnlyOneOption(azControlName) {
if (this.vpcType === vpcType.EXISTING && azControlName !== '') {
const filteredPublicSubnets = this.filteredAzs[azControlName].publicSubnets;
if (filteredPublicSubnets.length === 1 && !this.airgappedVPC) {
this.setControlValueSafely(this.getPublicSubnetFromAz(azControlName), filteredPublicSubnets[0].id);
}
const filteredPrivateSubnets = this.filteredAzs[azControlName].privateSubnets;
if (filteredPrivateSubnets.length === 1) {
this.setControlValueSafely(this.getPrivateSubnetFromAz(azControlName), filteredPrivateSubnets[0].id);
}
}
}
private getPublicSubnetFromAz(azControlName: AwsField): AwsField {
const indexAZ = AZS.indexOf(azControlName);
if (indexAZ < 0) {
console.log('WARNING: getPrivateSubnetFieldNameFromAzName() received unrecognized azControlName of ' + azControlName);
return null;
}
return PUBLIC_SUBNETS[indexAZ];
}
private getPrivateSubnetFromAz(azControlName: AwsField): AwsField {
const indexAZ = AZS.indexOf(azControlName);
if (indexAZ < 0) {
console.log('WARNING: getPrivateSubnetFieldNameFromAzName() received unrecognized azControlName of ' + azControlName);
return null;
}
return PRIVATE_SUBNET[indexAZ];
}
// updateWorkerNodeInstanceTypes() is called when the user has selected a new value (newlySelectedAz) for an azField.
// We need to get the worker node types available on that AZ and use them to populate our data structure that holds them.
// If there is only one worker node type, then we want to set the value of the workerNodeField to that type (rather than
// make the user "select it" from a list of only one element
private updateWorkerNodeInstanceTypes(azField: string, newlySelectedAz: string, workerNodeField: string) {
if (newlySelectedAz) {
this.apiClient.getAWSNodeTypes({
az: newlySelectedAz
})
.pipe(takeUntil(this.unsubscribe))
.subscribe(
((nodeTypes) => {
this.azNodeTypes[azField] = nodeTypes?.sort();
if (nodeTypes.length === 1) {
this.setControlValueSafely(workerNodeField, nodeTypes[0]);
} else {
// we default to the same instance type as the management cluster
const mgmtClusterInstanceType = this.isClusterPlanProd ? this.prodInstanceTypeValue : this.devInstanceTypeValue;
// ...but the stored value has precedence
const instanceType = this.getStoredValue(workerNodeField, this.supplyStepMapping(), mgmtClusterInstanceType);
this.setControlValueSafely(workerNodeField, instanceType);
}
}),
((err) => {
const error = err.error.message || err.message || JSON.stringify(err);
this.errorNotification = `Unable to retrieve worker node instance types. ${error}`;
})
);
} else {
this.azNodeTypes[newlySelectedAz] = [];
}
}
setSubnetFieldsFromSavedValues(): void {
// NOTE: in air-gapped VPC we do not use public subnets, so don't restore a value
if (!this.airgappedVPC) {
PUBLIC_SUBNETS.forEach(vpcSubnet => {
const subnet = this.findSubnetFromSavedValue(vpcSubnet, this['publicSubnets']);
this.setControlValueSafely(vpcSubnet, subnet ? subnet.id : '');
});
}
PRIVATE_SUBNET.forEach(vpcSubnet => {
const subnet = this.findSubnetFromSavedValue(vpcSubnet, this['privateSubnets']);
this.setControlValueSafely(vpcSubnet, subnet ? subnet.id : '');
});
}
// Given an array of subnet objects, find the one corresponding to the saved value of the given field
private findSubnetFromSavedValue(subnetField: AwsField, subnets: AWSSubnet[]) {
const savedValue = this.getStoredValue(subnetField, this.supplyStepMapping());
// note that the saved value could either be the CIDR or the ID, so we find a match for either
return subnets.find(x => { return x.cidr === savedValue || x.id === savedValue; });
}
updateVpcSubnets() {
if (this.vpcType !== vpcType.EXISTING) { // validations should be disabled for all public/private subnets
[
AwsField.NODESETTING_VPC_PRIVATE_SUBNET_1,
AwsField.NODESETTING_VPC_PRIVATE_SUBNET_2,
AwsField.NODESETTING_VPC_PRIVATE_SUBNET_3,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_1,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_2,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_3
].forEach(field => {
this.disarmField(field.toString(), false);
});
return;
}
if (this.isClusterPlanProd) {
// in PROD deployments, all three subnets are used
[
AwsField.NODESETTING_VPC_PRIVATE_SUBNET_1,
AwsField.NODESETTING_VPC_PRIVATE_SUBNET_2,
AwsField.NODESETTING_VPC_PRIVATE_SUBNET_3,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_1,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_2,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_3
].forEach(field => {
this.resurrectFieldWithStoredValue(field.toString(), this.supplyStepMapping(), [Validators.required]);
});
} else if (this.isClusterPlanDev) {
// in DEV deployments, only one subnet is used
[
AwsField.NODESETTING_VPC_PRIVATE_SUBNET_1,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_1,
].forEach(field => {
this.resurrectFieldWithStoredValue(field.toString(), this.supplyStepMapping(), [Validators.required]);
});
[
AwsField.NODESETTING_VPC_PRIVATE_SUBNET_2,
AwsField.NODESETTING_VPC_PRIVATE_SUBNET_3,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_2,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_3
].forEach(field => {
this.disarmField(field.toString(), false);
});
}
if (this.airgappedVPC) {
[
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_1,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_2,
AwsField.NODESETTING_VPC_PUBLIC_SUBNET_3
].forEach(field => {
this.disarmField(field.toString(), false);
});
}
}
get isVpcTypeExisting(): boolean {
return this.vpcType === VpcType.EXISTING;
}
protected getKeyFromNodeInstance(nodeInstance: string): string {
return nodeInstance;
}
protected getDisplayFromNodeInstance(nodeInstance: string): string {
return nodeInstance;
}
// We override the default behavior of displaying the fields in the order they occur in the StepMapping.
// This is because we inherit some fields from the shared NodeSettingStep, and just appending AWS added fields results
// in a jumbled order.
protected getFieldDisplayOrder(): string[] {
return AppServices.userDataService.fieldsWithStoredData(this.wizardName, this.formName, AwsFieldDisplayOrder);
}
} | the_stack |
import {defaults, take, normalizeAngle} from '../utils/utils';
import {selectOrAppend, classes} from '../utils/utils-dom';
import {cutText, wrapText, avoidTickTextCollision} from '../utils/d3-decorators';
import {CSS_PREFIX} from '../const';
import * as utilsDraw from '../utils/utils-draw';
import {Selection} from 'd3-selection';
import {Transition} from 'd3-transition';
import {AxisLabelGuide, ScaleFunction, ScaleGuide} from '../definitions';
type AxisOrient = 'top' | 'right' | 'bottom' | 'left';
type GridOrient = 'horizontal' | 'vertical';
interface AxisConfig {
scale: ScaleFunction;
scaleGuide: ScaleGuide;
ticksCount?: number;
tickFormat?: (x) => string;
tickSize?: number;
tickPadding?: number;
gridOnly?: boolean;
position: [number, number];
}
interface GridConfig {
scale: ScaleFunction;
scaleGuide: ScaleGuide;
ticksCount: number;
tickSize: number;
position: [number, number];
}
type d3Selection = Selection<any, any, any, any>;
type d3Transition = Transition<any, any, any, any>;
function identity<T>(x: T) {
return x;
}
const epsilon = 1e-6;
function translateX(x: number) {
return `translate(${x + 0.5},0)`;
}
function translateY(y: number) {
return `translate(0,${y + 0.5})`;
}
function center(scale: ScaleFunction) {
var offset = Math.max(0, scale.bandwidth() - 1) / 2; // Adjust for 0.5px offset.
if (scale.round()) {
offset = Math.round(offset);
}
return function (d) {
return (scale(d) + offset);
};
}
function getContainer(selection: d3Selection) {
let svg: SVGElement = selection.node();
while (svg && svg.tagName !== 'svg') {
svg = svg.parentNode as SVGElement;
}
return svg;
}
const Orient = {
'top': 1,
'right': 2,
'bottom': 3,
'left': 4
};
function createAxis(config: AxisConfig) {
const orient = Orient[config.scaleGuide.scaleOrient];
const scale = config.scale;
const scaleGuide = config.scaleGuide;
const labelGuide = scaleGuide.label;
const {
ticksCount,
tickFormat,
tickSize,
tickPadding,
gridOnly
} = defaults(config, {
tickSize: 6,
tickPadding: 3,
gridOnly: false
});
const isLinearScale = (scale.scaleType === 'linear');
const isOrdinalScale = (scale.scaleType === 'ordinal' || scale.scaleType === 'period');
const isHorizontal = (orient === Orient.top || orient === Orient.bottom);
const ko = (orient === Orient.top || orient === Orient.left ? -1 : 1);
const x = (isHorizontal ? 'x' : 'y');
const y = (isHorizontal ? 'y' : 'x');
const transform = (isHorizontal ? translateX : translateY);
const kh = (isHorizontal ? 1 : -1);
return ((context: d3Selection | d3Transition) => {
var values: any[];
if (scale.ticks) {
values = scale.ticks(ticksCount);
// Prevent generating too much ticks
let count = Math.floor(ticksCount * 1.25);
while ((values.length > count) && (count > 2) && (values.length > 2)) {
values = scale.ticks(--count);
}
} else {
values = scale.domain();
}
if (scaleGuide.hideTicks) {
values = gridOnly ? values.filter((d => d == 0)) : [];
}
const format = (tickFormat == null ? (scale.tickFormat ? scale.tickFormat(ticksCount) : identity) : tickFormat);
const spacing = (Math.max(tickSize, 0) + tickPadding);
const range = scale.range();
const range0 = (range[0] + 0.5);
const range1 = (range[range.length - 1] + 0.5);
let position = (scale.bandwidth ? center : identity)(scale);
if (scaleGuide.facetAxis) {
let oldPos = position;
position = (d) => oldPos(d) - scale.stepSize(d) / 2;
}
// Todo: Determine if scale copy is necessary. Fails on ordinal scales with ratio.
// const position = (scale.bandwidth ? center : identity)(scale.copy());
const transition = ((context as d3Transition).selection ? (context as d3Transition) : null);
const selection = (transition ? transition.selection() : context as d3Selection);
const containerSize = getContainer(selection).getBoundingClientRect();
// Set default style
selection
.attr('fill', 'none')
.attr('font-size', 10)
.attr('font-family', 'sans-serif')
.attr('text-anchor', orient === Orient.right ? 'start' : orient === Orient.left ? 'end' : 'middle');
interface TickDataBinding {
tickExit: d3Selection;
tickEnter: d3Selection;
tick: d3Selection;
}
function drawDomain() {
const domainLineData = scaleGuide.hideTicks || scaleGuide.hide ? [] : [null];
take(selection.selectAll('.domain').data(domainLineData))
.then((path) => {
if (transition) {
path.exit()
.transition(transition)
.attr('opacity', 0)
.remove();
}
return path.merge(
path.enter().insert('path', '.tick')
.attr('class', 'domain')
.attr('opacity', 1)
.attr('stroke', '#000'));
})
.then((path) => {
return (transition ?
path.transition(transition) :
path);
})
.then((path) => {
path.attr('d', orient === Orient.left || orient == Orient.right ?
`M${ko * tickSize},${range0}H0.5V${range1}H${ko * tickSize}` :
`M${range0},${ko * tickSize}V0.5H${range1}V${ko * tickSize}`);
});
}
function createTicks(): TickDataBinding {
return take((selection
.selectAll('.tick') as d3Selection)
.data(values, (x) => String(scale(x)))
.order())
.then((tick) => {
const tickExit = tick.exit<any>();
const tickEnter = tick.enter().append('g').attr('class', 'tick');
return {
tickExit,
tickEnter,
tick: tick.merge(tickEnter)
};
})
.then((result) => {
if (isLinearScale) {
const ticks = scale.ticks();
const domain = scale.domain();
const last = (values.length - 1);
const shouldHighlightZero = (
(ticks.length > 1) &&
(domain[0] * domain[1] < 0) &&
(-domain[0] > (ticks[1] - ticks[0]) / 2) &&
(domain[1] > (ticks[last] - ticks[last - 1]) / 2)
);
result.tick
.classed('zero-tick', (d) => {
return (
(d == 0) &&
shouldHighlightZero
);
});
}
return result;
})
.result();
}
function updateTicks(ticks: TickDataBinding) {
take(ticks)
.then(({tickEnter, tickExit, tick}) => {
if (!transition) {
return {tick, tickExit};
}
tickEnter
.attr('opacity', epsilon)
.attr('transform', function (d) {
const p: number = position(d);
return transform(p);
});
return {
tick: tick.transition(transition),
tickExit: tickExit.transition(transition)
.attr('opacity', epsilon)
.attr('transform', function (d) {
const p = position(d);
if (isFinite(p)) {
return transform(p);
}
return (this as SVGElement).getAttribute('transform');
})
};
})
.then(({tick, tickExit}) => {
tickExit.remove();
tick
.attr('opacity', 1)
.attr('transform', (d) => transform(position(d)));
});
}
function drawLines(ticks: TickDataBinding) {
const ly = (ko * tickSize);
const lx = (isOrdinalScale ? ((d) => (kh * scale.stepSize(d) / 2)) : null);
take(ticks)
.then(({tick, tickEnter}) => {
const line = tick.select('line');
const lineEnter = tickEnter.append('line')
.attr('stroke', '#000')
.attr(`${y}2`, ly);
if (isOrdinalScale) {
lineEnter
.attr(`${x}1`, lx)
.attr(`${x}2`, lx);
}
return line.merge(lineEnter);
})
.then((line) => {
if (transition) {
return line.transition(transition);
}
return line;
})
.then((line) => {
line
.attr(`${y}2`, ly);
if (isOrdinalScale) {
line
.attr(`${x}1`, lx)
.attr(`${x}2`, lx);
}
});
}
function drawExtraOrdinalLine() {
if (!isOrdinalScale || !values || !values.length) {
return;
}
take(selection.selectAll('.extra-tick-line').data([null]))
.then((extra) => {
return extra.merge(
extra.enter().insert('line', '.tick')
.attr('class', 'extra-tick-line')
.attr('stroke', '#000'));
})
.then((extra) => {
return (transition ?
extra.transition(transition) :
extra);
})
.then((extra) => {
extra
.attr(`${x}1`, range0)
.attr(`${x}2`, range0)
.attr(`${y}1`, 0)
.attr(`${y}2`, ko * tickSize);
});
}
function drawText(ticks: TickDataBinding) {
const textAnchor = scaleGuide.textAnchor;
const ty = (ko * spacing);
const tdy = (orient === Orient.top ? '0em' : orient === Orient.bottom ? '0.71em' : '0.32em');
function fixTextPosForVerticalFacets(selection) {
if (scaleGuide.facetAxis) {
return selection
.attr('dx', -config.position[0] + 18)
.attr('dy', 16);
}
}
take(ticks)
.then(({tick, tickEnter}) => {
const text = tick.select('text');
const textEnter = tickEnter.append('text')
.attr('fill', '#000')
.attr(y, ty)
.attr('dy', tdy);
rotateText(textEnter);
fixTextPosForVerticalFacets(textEnter);
return text.merge(textEnter);
})
.then((text) => {
text
.text(format)
.attr('text-anchor', textAnchor);
if (isHorizontal === false && scaleGuide.facetAxis === true) {
const facetShift = utilsDraw
.parseTransformTranslate(selection.node().parentNode.getAttribute('transform'));
fixLongText(text, containerSize.width - Math.abs(facetShift.x));
} else {
fixLongText(text);
}
if (isHorizontal && (scale.scaleType === 'time')) {
fixHorizontalTextOverflow(text);
}
if (isHorizontal && (scale.scaleType === 'time' || scale.scaleType === 'linear')) {
fixOuterTicksOverflow(text);
}
return text;
})
.then((text) => {
if (transition) {
return text.transition(transition);
}
return text;
})
.then((text) => {
text
.attr(y, ty);
rotateText(text);
fixTextPosForVerticalFacets(text);
if (isOrdinalScale && scaleGuide.avoidCollisions && !scaleGuide.facetAxis) {
if (transition) {
transition.on('end.fixTickTextCollision', () => {
return fixTickTextCollision(ticks.tick);
});
} else {
fixTickTextCollision(ticks.tick);
}
}
});
}
function rotateText(text: d3Selection | d3Transition) {
const angle = normalizeAngle(scaleGuide.rotate);
// Todo: Rotate around rotation point (text anchor?)
text
.attr('transform', utilsDraw.rotate(angle));
// Todo: Unpredictable behavior, need review
if ((Math.abs(angle / 90) % 2) > 0) {
let kRot = (angle < 180 ? 1 : -1);
let k = isHorizontal ? 0.5 : -2;
let sign = (orient === Orient.top || orient === Orient.left ? -1 : 1);
let dy = (k * (orient === Orient.top || orient === Orient.bottom ?
(sign < 0 ? 0 : 0.71) :
0.32));
text
.attr('x', 9 * kRot)
.attr('y', 0)
.attr('dx', isHorizontal ? null : `${dy}em`)
.attr('dy', `${dy}em`);
}
}
function fixLongText(text: d3Selection, containerWidth = 0) {
const stepSize = (d) => Math.max(scale.stepSize(d), scaleGuide.tickFormatWordWrapLimit, containerWidth);
if (scaleGuide.tickFormatWordWrap) {
wrapText(
text,
stepSize,
scaleGuide.tickFormatWordWrapLines,
scaleGuide.tickFontHeight,
!isHorizontal
);
} else {
cutText(
text,
stepSize
);
}
}
function fixHorizontalTextOverflow(text: d3Selection) {
if (values.length < 2) {
return;
}
var maxTextLn = 0;
var iMaxTexts = -1;
const nodes: Element[] = text.nodes();
nodes.forEach((textNode, i) => {
const textContent = (textNode.textContent || '');
var textLength = textContent.length;
if (textLength > maxTextLn) {
maxTextLn = textLength;
iMaxTexts = i;
}
});
const tickStep = (position(values[1]) - position(values[0]));
var hasOverflow = false;
if (iMaxTexts >= 0) {
var rect = nodes[iMaxTexts].getBoundingClientRect();
hasOverflow = (tickStep - rect.width) < 8; // 2px from each side
}
selection.classed(`${CSS_PREFIX}time-axis-overflow`, hasOverflow);
}
function fixOuterTicksOverflow(text: d3Selection) {
if (values.length === 0) {
return;
}
const value0 = values[0];
const value1 = values[values.length - 1];
const tempLeft = selection
.append('line')
.attr('x1', position(value0))
.attr('x2', position(value0))
.attr('y1', 0)
.attr('y2', 1) as d3Selection;
const tempRight = selection
.append('line')
.attr('x1', position(value1))
.attr('x2', position(value1))
.attr('y1', 0)
.attr('y2', 1) as d3Selection;
const available = {
left: (tempLeft.node().getBoundingClientRect().left - containerSize.left),
right: (containerSize.right - tempRight.node().getBoundingClientRect().right)
};
tempLeft.remove();
tempRight.remove();
const fixText = (node: SVGElement, dir: -1 | 1, value) => {
const rect = node.getBoundingClientRect();
const side = (dir > 0 ? 'right' : 'left');
const tx = position(value);
const limit = available[side];
const diff = Math.ceil(rect.width / 2 - limit + 1); // 1px rounding fix
node.setAttribute('dx', String(diff > 0 ? -dir * diff : 0));
};
const tick0 = text.filter((d) => d === value0).node();
const tick1 = text.filter((d) => d === value1).node();
text.attr('dx', null);
fixText(tick0, -1, value0);
fixText(tick1, 1, value1);
}
function fixTickTextCollision(tick: d3Selection) {
avoidTickTextCollision(tick, isHorizontal);
}
function drawAxisLabel() {
const guide = labelGuide;
const labelTextNode = selectOrAppend(selection, `text.label`)
.attr('class', classes('label', guide.cssClass))
.attr('transform', utilsDraw.rotate(guide.rotate))
.attr('text-anchor', guide.textAnchor);
take(labelTextNode)
.then((label) => {
if (transition) {
return label.transition(transition);
}
return label;
})
.then((label) => {
const ly = (kh * guide.padding);
const size = Math.abs(range1 - range0);
const lx = isHorizontal ? size : 0;
label
.attr('x', lx)
.attr('y', ly);
});
const delimiter = ' \u2192 ';
const textParts = guide.text.split(delimiter);
for (var i = textParts.length - 1; i > 0; i--) {
textParts.splice(i, 0, delimiter);
}
let tspans = labelTextNode.selectAll('tspan')
.data(textParts)
.enter()
.append('tspan')
.attr('opacity', epsilon)
.attr('class', (d, i) => i % 2 ?
(`label-token-delimiter label-token-delimiter-${i}`) :
(`label-token label-token-${i}`))
.text((d) => d);
let tspansExit = tspans
.exit();
if (transition) {
tspans = tspans
.transition(transition);
tspansExit = tspansExit
.transition(transition)
.attr('opacity', epsilon);
}
tspans.attr('opacity', 1);
tspansExit
.remove();
}
if (!gridOnly) {
drawDomain();
}
const ticks = createTicks();
updateTicks(ticks);
if (!scaleGuide.facetAxis) {
drawLines(ticks);
}
if (isOrdinalScale && gridOnly) { // Todo: Explicitly determine if grid
drawExtraOrdinalLine();
}
if (!gridOnly) {
drawText(ticks);
if (!labelGuide.hide) {
drawAxisLabel();
}
}
});
}
export function cartesianAxis(config: AxisConfig) {
return createAxis(config);
}
export function cartesianGrid(config: GridConfig) {
return createAxis({
scale: config.scale,
scaleGuide: config.scaleGuide,
ticksCount: config.ticksCount,
tickSize: config.tickSize,
gridOnly: true,
position: config.position,
});
} | the_stack |
import { StreamID } from '@ceramicnetwork/streamid'
import { TileDocument } from '@ceramicnetwork/stream-tile'
import { CIP11_DEFINITION_SCHEMA_URL, CIP11_INDEX_SCHEMA_URL } from '@glazed/constants'
import { DataModel } from '@glazed/datamodel'
import { DIDDataStore } from '../src'
jest.mock('@ceramicnetwork/stream-tile')
// eslint-disable-next-line @typescript-eslint/unbound-method
const createTile = TileDocument.create as jest.Mock<Promise<TileDocument>>
// eslint-disable-next-line @typescript-eslint/unbound-method
const loadTile = TileDocument.load as jest.Mock<Promise<TileDocument>>
describe('DIDDataStore', () => {
const model = {
schemas: {},
definitions: {},
tiles: {},
}
const testDocID = StreamID.fromString(
'kjzl6cwe1jw147dvq16zluojmraqvwdmbh61dx9e0c59i344lcrsgqfohexp60s'
)
describe('properties', () => {
test('`authenticated` property', () => {
const ds1 = new DIDDataStore({ ceramic: {}, model } as any)
expect(ds1.authenticated).toBe(false)
const ds2 = new DIDDataStore({ ceramic: { did: {} }, model } as any)
expect(ds2.authenticated).toBe(true)
})
test('`ceramic` property', () => {
const ceramic = {}
const ds = new DIDDataStore({ ceramic, model } as any)
expect(ds.ceramic).toBe(ceramic)
})
test('`id` property', () => {
const ds1 = new DIDDataStore({ ceramic: {}, model } as any)
expect(() => ds1.id).toThrow('Ceramic instance is not authenticated')
const ds2 = new DIDDataStore({ ceramic: { did: { id: 'did:test' } }, model } as any)
expect(ds2.id).toBe('did:test')
})
test('`model` property', () => {
const ds = new DIDDataStore({ ceramic: {}, model } as any)
expect(ds.model).toBeInstanceOf(DataModel)
})
})
describe('Main methods', () => {
// TODO: check aliases resolution
describe('has', () => {
test('returns true', async () => {
const getRecordID = jest.fn(() => Promise.resolve('streamId'))
const ds = new DIDDataStore({ model } as any)
ds.getRecordID = getRecordID
await expect(ds.has('test', 'did')).resolves.toBe(true)
expect(getRecordID).toBeCalledWith('test', 'did')
})
test('returns false', async () => {
const getRecordID = jest.fn(() => Promise.resolve(null))
const ds = new DIDDataStore({ model } as any)
ds.getRecordID = getRecordID
await expect(ds.has('test', 'did')).resolves.toBe(false)
expect(getRecordID).toBeCalledWith('test', 'did')
})
})
test('get', async () => {
const content = {}
const getRecordDocument = jest.fn(() => ({ content }))
const ds = new DIDDataStore({ model } as any)
ds.getRecordDocument = getRecordDocument as any
await expect(ds.get('streamId', 'did')).resolves.toBe(content)
expect(getRecordDocument).toBeCalledWith('streamId', 'did')
})
describe('set', () => {
test('does not set the index key if it already exists', async () => {
const ds = new DIDDataStore({ model } as any)
const setRecord = jest.fn(() => Promise.resolve([false, 'streamId']))
ds._setRecordOnly = setRecord as any
const setReference = jest.fn()
ds._setReference = setReference
const content = { test: true }
await ds.setRecord('defId', content)
expect(setRecord).toBeCalledWith('defId', content, undefined)
expect(setReference).not.toBeCalled()
})
test('adds the new index key', async () => {
const ds = new DIDDataStore({ model } as any)
const setRecord = jest.fn(() => Promise.resolve([true, 'streamId']))
ds._setRecordOnly = setRecord as any
const setReference = jest.fn()
ds._setReference = setReference
const content = { test: true }
await ds.setRecord('defId', content)
expect(setRecord).toBeCalledWith('defId', content, undefined)
expect(setReference).toBeCalledWith('defId', 'streamId')
})
})
describe('merge', () => {
test('with existing contents', async () => {
const content = { hello: 'test', foo: 'bar' }
const getRecord = jest.fn(() => content)
const setRecord = jest.fn(() => 'contentId')
const ds = new DIDDataStore({ ceramic: { did: { id: 'did:test:123' } }, model } as any)
ds.getRecord = getRecord as any
ds.setRecord = setRecord as any
await expect(ds.merge('streamId', { hello: 'world', added: 'value' })).resolves.toBe(
'contentId'
)
expect(setRecord).toBeCalledWith(
'streamId',
{ hello: 'world', foo: 'bar', added: 'value' },
undefined
)
})
test('without existing contents', async () => {
const content = { hello: 'test', foo: 'bar' }
const getRecord = jest.fn(() => null)
const setRecord = jest.fn(() => 'contentId')
const ds = new DIDDataStore({ ceramic: { did: { id: 'did:test:123' } }, model } as any)
ds.getRecord = getRecord as any
ds.setRecord = setRecord as any
await expect(ds.merge('streamId', content)).resolves.toBe('contentId')
expect(setRecord).toBeCalledWith('streamId', content, undefined)
})
})
test('setAll', async () => {
const ref1 = 'kjzl6cwe1jw147dvq16zluojmraqvwdmbh61dx9e0c59i344lcrsgqfohexpaaa'
const ref2 = 'kjzl6cwe1jw147dvq16zluojmraqvwdmbh61dx9e0c59i344lcrsgqfohexpbbb'
const setRecordOnly = jest.fn((key) => {
return key === 'first'
? [true, StreamID.fromString(ref1)]
: [false, StreamID.fromString(ref2)]
})
const setReferences = jest.fn()
const ds = new DIDDataStore({ ceramic: { did: { id: 'did:test' } }, model } as any)
ds._setRecordOnly = setRecordOnly as any
ds._setReferences = setReferences as any
const refs = { first: `ceramic://${ref1}` }
await expect(ds.setAll({ first: { foo: 'foo' }, second: { bar: 'bar' } })).resolves.toEqual(
refs
)
expect(setRecordOnly).toBeCalledTimes(2)
expect(setReferences).toBeCalledWith(refs)
})
test('setDefaults', async () => {
const newID = StreamID.fromString(
'kjzl6cwe1jw147dvq16zluojmraqvwdmbh61dx9e0c59i344lcrsgqfohexpaaa'
)
const definition = {}
const getDefinition = jest.fn(() => definition)
const getIndex = jest.fn(() => ({ def1: 'ref1', def2: 'ref2' }))
const createRecord = jest.fn(() => newID)
const setReferences = jest.fn()
const ds = new DIDDataStore({ ceramic: { did: { id: 'did:test' } }, model } as any)
ds.getDefinition = getDefinition as any
ds.getIndex = getIndex as any
ds._createRecord = createRecord as any
ds._setReferences = setReferences as any
const refs = { def3: newID.toUrl() }
await expect(
ds.setDefaults({ def1: { hello: 'world' }, def3: { added: 'value' } })
).resolves.toEqual(refs)
expect(getDefinition).toBeCalledWith('def3')
expect(createRecord).toBeCalledWith(definition, { added: 'value' }, undefined)
expect(setReferences).toBeCalledWith(refs)
})
test('remove', async () => {
const remove = jest.fn(() => Promise.resolve())
const ds = new DIDDataStore({ model } as any)
ds.remove = remove
await expect(ds.remove('streamId')).resolves.toBeUndefined()
expect(remove).toBeCalledWith('streamId')
})
})
describe('Index methods', () => {
test('getIndex with provided DID', async () => {
const get = jest.fn()
const ds = new DIDDataStore({ ceramic: { did: {} }, model } as any)
ds._getIDXDoc = get
await ds.getIndex('did:test')
expect(get).toBeCalledWith('did:test')
})
test('getIndex with own DID', async () => {
const get = jest.fn()
const ds = new DIDDataStore({ ceramic: { did: { id: 'did:test' } }, model } as any)
ds._indexProxy = { get } as any
await ds.getIndex()
expect(get).toBeCalled()
})
test('iterator', async () => {
const index = {
'ceramic://definition1': 'ceramic://doc1',
'ceramic://definition2': 'ceramic://doc2',
'ceramic://definition3': 'ceramic://doc3',
}
const loadDocument = jest.fn(() => Promise.resolve({ content: 'doc content' }))
const getIndex = jest.fn(() => Promise.resolve(index))
const ds = new DIDDataStore({ ceramic: { did: { id: 'did:own' } }, model } as any)
ds._loadDocument = loadDocument as any
ds.getIndex = getIndex
const results = []
for await (const entry of ds.iterator()) {
results.push(entry)
}
expect(results).toEqual([
{
key: 'ceramic://definition1',
id: 'ceramic://doc1',
record: 'doc content',
},
{
key: 'ceramic://definition2',
id: 'ceramic://doc2',
record: 'doc content',
},
{
key: 'ceramic://definition3',
id: 'ceramic://doc3',
record: 'doc content',
},
])
expect(loadDocument).toBeCalledTimes(3)
expect(loadDocument).toHaveBeenNthCalledWith(1, 'ceramic://doc1')
expect(loadDocument).toHaveBeenNthCalledWith(2, 'ceramic://doc2')
expect(loadDocument).toHaveBeenNthCalledWith(3, 'ceramic://doc3')
})
test('_createIDXDoc', async () => {
const ceramic = {}
const doc = { id: 'streamId' }
createTile.mockImplementationOnce(jest.fn(() => Promise.resolve(doc)) as any)
const ds = new DIDDataStore({ ceramic, model } as any)
await expect(ds._createIDXDoc('did:test:123')).resolves.toBe(doc)
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(createTile).toHaveBeenCalledTimes(1)
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(createTile).toHaveBeenCalledWith(
ceramic,
null,
{ deterministic: true, controllers: ['did:test:123'], family: 'IDX' },
{ anchor: false, publish: false }
)
})
describe('_getIDXDoc', () => {
test('calls _createIDXDoc and check the contents and schema are set', async () => {
const doc = { content: {}, metadata: { schema: CIP11_INDEX_SCHEMA_URL } } as any
const createDoc = jest.fn((_did) => Promise.resolve(doc))
const ds = new DIDDataStore({ model } as any)
ds._createIDXDoc = createDoc
await expect(ds._getIDXDoc('did:test:123')).resolves.toBe(doc)
expect(createDoc).toHaveBeenCalledWith('did:test:123')
})
test('returns null if the contents are not set', async () => {
const doc = { content: null, metadata: { schema: CIP11_INDEX_SCHEMA_URL } } as any
const createDoc = jest.fn((_did) => Promise.resolve(doc))
const ds = new DIDDataStore({ model } as any)
ds._createIDXDoc = createDoc
await expect(ds._getIDXDoc('did:test:123')).resolves.toBeNull()
expect(createDoc).toHaveBeenCalledWith('did:test:123')
})
test('returns null if the schema is not set', async () => {
const doc = { content: {}, metadata: {} } as any
const createDoc = jest.fn((_did) => Promise.resolve(doc))
const ds = new DIDDataStore({ model } as any)
ds._createIDXDoc = createDoc
await expect(ds._getIDXDoc('did:test:123')).resolves.toBeNull()
expect(createDoc).toHaveBeenCalledWith('did:test:123')
})
test('throws if the schema is invalid', async () => {
const doc = { content: {}, metadata: { schema: 'OtherSchemaURL' } } as any
const createDoc = jest.fn((_did) => Promise.resolve(doc))
const ds = new DIDDataStore({ model } as any)
ds._createIDXDoc = createDoc
await expect(ds._getIDXDoc('did:test:123')).rejects.toThrow(
'Invalid document: schema is not IdentityIndex'
)
expect(createDoc).toHaveBeenCalledWith('did:test:123')
})
})
describe('_getOwnIDXDoc', () => {
test('creates and sets schema in update', async () => {
const id = 'did:test:123'
const metadata = { controllers: [id], family: 'IDX' }
const update = jest.fn()
const add = jest.fn()
const doc = { id: 'streamId', update, metadata } as any
const createDoc = jest.fn((_did) => Promise.resolve(doc))
const ds = new DIDDataStore({ ceramic: { did: { id }, pin: { add } }, model } as any)
ds._createIDXDoc = createDoc
await expect(ds._getOwnIDXDoc()).resolves.toBe(doc)
expect(createDoc).toHaveBeenCalledWith(id)
expect(update).toHaveBeenCalledWith({}, { schema: CIP11_INDEX_SCHEMA_URL })
expect(add).toBeCalledWith('streamId')
})
test('returns the doc if valid', async () => {
const id = 'did:test:123'
const metadata = { controllers: [id], family: 'IDX', schema: CIP11_INDEX_SCHEMA_URL }
const update = jest.fn()
const doc = { update, metadata, content: {} } as any
const createDoc = jest.fn((_did) => Promise.resolve(doc))
const ds = new DIDDataStore({ ceramic: { did: { id } }, model } as any)
ds._createIDXDoc = createDoc
await expect(ds._getOwnIDXDoc()).resolves.toBe(doc)
expect(createDoc).toHaveBeenCalledWith(id)
expect(update).not.toHaveBeenCalled()
})
test('throws if the schema is invalid', async () => {
const id = 'did:test:123'
const metadata = { controllers: [id], family: 'IDX', schema: 'OtherSchemaURL' }
const update = jest.fn()
const doc = { update, metadata, content: {} } as any
const createDoc = jest.fn((_did) => Promise.resolve(doc))
const ds = new DIDDataStore({ ceramic: { did: { id } }, model } as any)
ds._createIDXDoc = createDoc
await expect(ds._getOwnIDXDoc()).rejects.toThrow(
'Invalid document: schema is not IdentityIndex'
)
expect(createDoc).toHaveBeenCalledWith(id)
expect(update).not.toHaveBeenCalled()
})
})
})
describe('Metadata methods', () => {
describe('getDefinitionID', () => {
test('with alias in model', () => {
const ds = new DIDDataStore({
ceramic: {},
model: { ...model, definitions: { foo: 'bar' } },
} as any)
expect(ds.getDefinitionID('foo')).toBe('bar')
})
test('without alias in model', () => {
const ds = new DIDDataStore({ ceramic: {}, model } as any)
expect(ds.getDefinitionID('foo')).toBe('foo')
})
})
describe('getDefinition', () => {
test('returns valid definition', async () => {
const ceramic = {}
const load = jest.fn(() => {
return Promise.resolve({
content: { name: 'definition' },
metadata: { schema: CIP11_DEFINITION_SCHEMA_URL },
} as TileDocument)
})
loadTile.mockImplementationOnce(load)
const ds = new DIDDataStore({ ceramic, model } as any)
await expect(ds.getDefinition('ceramic://test')).resolves.toEqual({
name: 'definition',
})
expect(load).toBeCalledWith(ceramic, 'ceramic://test')
})
test('throws on invalid definition schema', async () => {
const ceramic = {}
const load = jest.fn(() => {
return Promise.resolve({
content: { name: 'definition' },
metadata: { schema: 'OtherSchemaURL' },
} as TileDocument)
})
loadTile.mockImplementationOnce(load)
const ds = new DIDDataStore({ ceramic, model } as any)
await expect(ds.getDefinition('ceramic://test')).rejects.toThrow(
'Invalid document: schema is not Definition'
)
expect(load).toBeCalledWith(ceramic, 'ceramic://test')
})
})
})
describe('Records methods', () => {
test('_loadDocument', async () => {
const load = jest.fn()
loadTile.mockImplementation(load)
const ds = new DIDDataStore({ model } as any)
await Promise.all([ds._loadDocument('one'), ds._loadDocument('one'), ds._loadDocument('two')])
expect(load).toBeCalledTimes(3)
})
test('getRecordID', async () => {
const ds = new DIDDataStore({ model } as any)
ds.getIndex = () => Promise.resolve(null)
await expect(ds.getRecordID('test', 'did')).resolves.toBeNull()
const get = jest.fn(() => Promise.resolve({ exists: 'ceramic://test' }))
ds.getIndex = get as any
await expect(ds.getRecordID('exists', 'did')).resolves.toBe('ceramic://test')
expect(get).toHaveBeenCalledWith('did')
})
test('getRecordDocument', async () => {
const ds = new DIDDataStore({ model } as any)
ds.getRecordID = () => Promise.resolve(null)
await expect(ds.getRecordDocument('test', 'did')).resolves.toBeNull()
const getRecordID = jest.fn(() => Promise.resolve('ceramic://test'))
ds.getRecordID = getRecordID
const doc = { content: { test: true } }
const load = jest.fn(() => Promise.resolve(doc))
ds._loadDocument = load as any
await expect(ds.getRecordDocument('exists', 'did')).resolves.toBe(doc)
expect(getRecordID).toHaveBeenCalledWith('exists', 'did')
expect(load).toHaveBeenCalledWith('ceramic://test')
})
test('getRecord', async () => {
const content = {}
const getRecordDocument = jest.fn(() => ({ content }))
const ds = new DIDDataStore({ model } as any)
ds.getRecordDocument = getRecordDocument as any
await expect(ds.getRecord('streamId', 'did')).resolves.toBe(content)
expect(getRecordDocument).toBeCalledWith('streamId', 'did')
})
describe('_setRecordOnly', () => {
test('existing definition ID', async () => {
const ds = new DIDDataStore({ ceramic: { did: { id: 'did:foo:123' } }, model } as any)
const getRecordID = jest.fn(() => Promise.resolve('streamId'))
const update = jest.fn()
const loadDocument = jest.fn(() => Promise.resolve({ update, id: 'streamId' }))
ds._loadDocument = loadDocument as any
ds.getRecordID = getRecordID
const content = { test: true }
await expect(ds._setRecordOnly('defId', content)).resolves.toEqual([false, 'streamId'])
expect(getRecordID).toBeCalledWith('defId', 'did:foo:123')
expect(loadDocument).toBeCalledWith('streamId')
expect(update).toBeCalledWith(content)
})
test('adding definition ID', async () => {
const ds = new DIDDataStore({ ceramic: { did: { id: 'did' } }, model } as any)
ds._indexProxy = { get: (): Promise<any> => Promise.resolve(null) } as any
const definition = { name: 'test', schema: 'ceramic://...' }
const getDefinition = jest.fn(() => Promise.resolve(definition))
ds.getDefinition = getDefinition as any
const createRecord = jest.fn(() => Promise.resolve('streamId'))
ds._createRecord = createRecord as any
const content = { test: true }
await expect(ds._setRecordOnly('defId', content, { pin: true })).resolves.toEqual([
true,
'streamId',
])
expect(getDefinition).toBeCalledWith('defId')
expect(createRecord).toBeCalledWith(definition, content, { pin: true })
})
})
describe('setRecord', () => {
test('does not set the index key if it already exists', async () => {
const ds = new DIDDataStore({ model } as any)
const setRecord = jest.fn(() => Promise.resolve([false, 'streamId']))
ds._setRecordOnly = setRecord as any
const setReference = jest.fn()
ds._setReference = setReference
const content = { test: true }
await ds.setRecord('defId', content)
expect(setRecord).toBeCalledWith('defId', content, undefined)
expect(setReference).not.toBeCalled()
})
test('adds the new index key', async () => {
const ds = new DIDDataStore({ model } as any)
const setRecord = jest.fn(() => Promise.resolve([true, 'streamId']))
ds._setRecordOnly = setRecord as any
const setReference = jest.fn()
ds._setReference = setReference
const content = { test: true }
await ds.setRecord('defId', content)
expect(setRecord).toBeCalledWith('defId', content, undefined)
expect(setReference).toBeCalledWith('defId', 'streamId')
})
})
describe('_createRecord', () => {
test('creates the deterministic doc and updates it', async () => {
const id = 'did:test:123'
const add = jest.fn()
const update = jest.fn()
createTile.mockImplementationOnce(
jest.fn((_ceramic, _content, metadata, _opts) => {
return Promise.resolve({ id: 'streamId', update, metadata } as unknown as TileDocument)
})
)
const ceramic = { did: { id }, pin: { add } }
const ds = new DIDDataStore({ ceramic, model } as any)
const definition = {
id: { toString: () => 'defId' },
name: 'test',
schema: 'schemaId',
} as any
const content = { test: true }
await expect(ds._createRecord(definition, content, { pin: true })).resolves.toBe('streamId')
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(TileDocument.create).toBeCalledWith(
ceramic,
null,
{ deterministic: true, controllers: [id], family: 'defId' },
{ anchor: false, publish: false }
)
expect(update).toBeCalledWith(content, { schema: 'schemaId' })
expect(add).toBeCalledWith('streamId')
})
test('pin by default', async () => {
const add = jest.fn()
const update = jest.fn()
createTile.mockImplementationOnce(
jest.fn((_ceramic, _content, metadata) => {
return Promise.resolve({ id: 'streamId', update, metadata } as unknown as TileDocument)
})
)
const ds = new DIDDataStore({
ceramic: { did: { id: 'did:test:123' }, pin: { add } },
model,
} as any)
await ds._createRecord({ id: { toString: () => 'defId' } } as any, {})
expect(update).toBeCalled()
expect(add).toBeCalledWith('streamId')
})
test('no pinning by setting instance option', async () => {
const add = jest.fn()
const update = jest.fn()
createTile.mockImplementationOnce(
jest.fn((_ceramic, _content, metadata) => {
return Promise.resolve({ id: 'streamId', update, metadata } as unknown as TileDocument)
})
)
const ds = new DIDDataStore({
autopin: false,
ceramic: { did: { id: 'did:test:123' }, pin: { add } },
model,
} as any)
await ds._createRecord({ id: { toString: () => 'defId' } } as any, {})
expect(update).toBeCalled()
expect(add).not.toBeCalled()
})
test('explicit no pinning', async () => {
const add = jest.fn()
const update = jest.fn()
createTile.mockImplementationOnce(
jest.fn((_ceramic, _content, metadata) => {
return Promise.resolve({ id: 'streamId', update, metadata } as unknown as TileDocument)
})
)
const ds = new DIDDataStore({
autopin: true,
ceramic: { did: { id: 'did:test:123' }, pin: { add } },
model,
} as any)
await ds._createRecord({ id: { toString: () => 'defId' } } as any, {}, { pin: false })
expect(update).toBeCalled()
expect(add).not.toBeCalled()
})
})
})
describe('References methods', () => {
test('_setReference', async () => {
const content = { test: true }
const changeContent = jest.fn((change) => change(content))
const ds = new DIDDataStore({ model } as any)
ds._indexProxy = { changeContent } as any
await expect(ds._setReference('testId', testDocID)).resolves.toBeUndefined()
expect(changeContent).toReturnWith({ test: true, testId: testDocID.toUrl() })
})
test('_setReferences', async () => {
const content = { test: true }
const changeContent = jest.fn((change) => change(content))
const ds = new DIDDataStore({ model } as any)
ds._indexProxy = { changeContent } as any
await expect(ds._setReferences({ one: 'one', two: 'two' })).resolves.toBeUndefined()
expect(changeContent).toReturnWith({ test: true, one: 'one', two: 'two' })
})
})
}) | the_stack |
import {
BoundingBox,
DataTypes,
FeatureColumn,
GeometryColumns,
GeoPackage,
GeoPackageAPI,
FeatureTableStyles,
UserMappingTable,
} from '@ngageoint/geopackage';
import { StyleRow } from '@ngageoint/geopackage/built/lib/extension/style/styleRow';
import { IconRow } from '@ngageoint/geopackage/built/lib/extension/style/iconRow';
import { RelatedTablesExtension } from '@ngageoint/geopackage/built/lib/extension/relatedTables';
// Read KML
import fs, { PathLike } from 'fs';
import XmlStream from 'xml-stream-saxjs';
import path from 'path';
// Read KMZ
import JSZip from 'jszip';
import mkdirp from 'mkdirp';
// Utilities
import _ from 'lodash';
// Handle images
import Jimp from 'jimp';
import axios from 'axios';
// Utilities and Tags
import * as KMLTAGS from './KMLTags';
import { KMLUtilities } from './kmlUtilities';
import { GeoSpatialUtilities } from './geoSpatialUtilities';
import Streamer from 'stream';
import { isBrowser, isNode } from 'browser-or-node';
import { ImageUtilities } from './imageUtilities';
export interface KMLConverterOptions {
kmlOrKmzPath?: PathLike;
kmlOrKmzData?: Uint8Array;
isKMZ?: boolean | false;
mainTableName?: string;
append?: boolean;
preserverFolders?: boolean;
geoPackage?: GeoPackage | string;
srsNumber?: number | 4326;
indexTable?: boolean;
}
/**
* Convert KML file to GeoPackages.
*/
export class KMLToGeoPackage {
private options?: KMLConverterOptions;
hasStyles: boolean;
hasMultiGeometry: boolean;
zipFileMap: Map<string, any>;
styleMap: Map<string, object>;
styleUrlMap: Map<string, number>;
styleRowMap: Map<number, StyleRow>;
styleMapPair: Map<string, string>;
iconMap: Map<string, object>;
iconUrlMap: Map<string, number>;
iconRowMap: Map<number, IconRow>;
iconMapPair: Map<string, string>;
properties: Set<string>;
numberOfPlacemarks: number;
numberOfGroundOverLays: number;
constructor(optionsUser: KMLConverterOptions = {}) {
this.options = optionsUser;
// Icon and Style Map are used to help fill out cross reference tables in the Geopackage Database
this.zipFileMap = new Map();
this.styleMapPair = new Map();
this.styleMap = new Map();
this.styleUrlMap = new Map();
this.styleRowMap = new Map();
this.iconMap = new Map();
this.iconUrlMap = new Map();
this.iconRowMap = new Map();
this.iconMapPair = new Map();
this.hasMultiGeometry = false;
this.hasStyles = false;
this.properties = new Set();
this.numberOfPlacemarks = 0;
this.numberOfGroundOverLays = 0;
}
/**
* Converts KML and KMZ to GeoPackages.
*
* @param {KMLConverterOptions} options
* @param {Function} progressCallback
*/
async convert(options?: KMLConverterOptions, progressCallback?: Function): Promise<GeoPackage> {
const clonedOptions = { ...options };
const kmlOrKmzPath = clonedOptions.kmlOrKmzPath || undefined;
const isKMZ = clonedOptions.isKMZ || false;
const geopackage = clonedOptions.geoPackage || undefined;
const tableName = clonedOptions.mainTableName;
const kmlOrKmzData = clonedOptions.kmlOrKmzData;
return this.convertKMLOrKMZToGeopackage(kmlOrKmzPath, isKMZ, geopackage, tableName, kmlOrKmzData, progressCallback);
}
/**
* Determines the function calls depending on the type of file and the environment it is in
*
* @param {PathLike} kmlOrKmzPath
* @param {boolean} [isKMZ]
* @param {(GeoPackage | string)} [geopackage] String or instance of the Geopackage to use.
* @param {string} [tableName] Name of Main Geometry table
* @param {(Uint8Array | null)} [kmlOrKmzData]
* @param {Function} [progressCallback] Passed the current status of the function.
* @returns {Promise<GeoPackage>} Promise of a GeoPackage
* @memberof KMLToGeoPackage
*/
async convertKMLOrKMZToGeopackage(
kmlOrKmzPath: PathLike,
isKMZ?: boolean,
geopackage?: GeoPackage | string,
tableName?: string,
kmlOrKmzData?: Uint8Array | null,
progressCallback?: Function,
): Promise<GeoPackage> {
if (typeof geopackage === 'string' || _.isNil(geopackage)) {
geopackage = await this.createOrOpenGeoPackage(geopackage, this.options);
}
if (isKMZ) {
if (progressCallback)
await progressCallback({ status: 'Converting a KMZ file to GeoPackage', file: kmlOrKmzPath });
if (isNode) {
return this.convertKMZToGeoPackage(kmlOrKmzPath, geopackage, tableName, progressCallback);
} else if (isBrowser) {
return this.convertKMZToGeoPackage(kmlOrKmzData, geopackage, tableName, progressCallback);
}
} else {
if (progressCallback) await progressCallback({ status: 'Converting KML file to GeoPackage' });
if (isNode) {
return this.convertKMLToGeoPackage(kmlOrKmzPath, geopackage, tableName, progressCallback);
} else if (isBrowser) {
return this.convertKMLToGeoPackage(kmlOrKmzData, geopackage, tableName, progressCallback);
}
}
}
/**
* Unzips and stores data from a KMZ file in the current directory or in a Map
*
* @param {(PathLike | Uint8Array)} kmzData Path to KMZ file or Data of the KMZ file
* @param {(GeoPackage | string)} geopackage String or instance of Geopackage to use
* @param {string} tableName Name of the main Geometry Table
* @param {Function} [progressCallback] Passed the current status of the function.
* @returns {Promise<GeoPackage>} Promise of a GeoPackage
* @memberof KMLToGeoPackage
*/
async convertKMZToGeoPackage(
kmzData: PathLike | Uint8Array,
geopackage: GeoPackage | string,
tableName: string,
progressCallback?: Function,
): Promise<GeoPackage> {
if (typeof geopackage === 'string' || _.isNil(geopackage)) {
geopackage = await this.createOrOpenGeoPackage(geopackage, this.options);
}
let data: PathLike | Uint8Array;
if (kmzData instanceof Uint8Array) {
data = kmzData;
} else {
data = fs.readFileSync(kmzData);
}
const zip = await JSZip.loadAsync(data).catch(() => {
throw new Error('Invalid KMZ / ZIP file');
});
let kmlData: PathLike | Uint8Array;
let gp: GeoPackage;
await new Promise(async resolve => {
if (progressCallback) await progressCallback({ status: 'Extracting files form KMZ' });
for (const key in zip.files) {
await new Promise(async (resolve, reject) => {
if (zip.files.hasOwnProperty(key)) {
if (isNode) {
const fileDestination = path.join(path.dirname(kmzData.toString()), key);
kmlData = zip.files[key].name.endsWith('.kml') ? fileDestination : kmlData;
const dir = mkdirp(path.dirname(fileDestination));
if (!_.isNil(dir)) {
await dir.catch(err => {
console.error('mkdirp was not able to be made', err);
reject();
});
}
const file = zip.file(key);
if (!_.isNil(file)) {
file
.nodeStream()
.pipe(
fs.createWriteStream(fileDestination, {
flags: 'w',
}),
)
.on('finish', () => {
resolve();
});
} else {
resolve();
}
} else if (isBrowser) {
if (key.endsWith('.kml')) {
kmlData = await zip.files[key].async('uint8array');
} else {
this.zipFileMap.set(key, await zip.files[key].async('base64'));
}
resolve();
}
}
}).catch(err => {
if (progressCallback) progressCallback({ status: 'KMZ -> KML extraction was not successful.', error: err });
console.error('KMZ -> KML extraction was not successful');
throw err;
});
}
resolve();
})
.then(async () => {
if (progressCallback) progressCallback({ status: 'Converting kmz to a Geopackage', file: kmlData });
gp = await this.convertKMLToGeoPackage(kmlData, geopackage, tableName, progressCallback);
})
.catch(err => {
if (progressCallback) progressCallback({ status: 'KMZ -> KML extraction was not successful.', error: err });
console.error('KMZ -> KML extraction was not successful');
throw err;
});
return gp;
}
/**
* Takes a KML file and does a 2 pass method to exact the features and styles and inserts those item properly into a geopackage.
*
* @param {(PathLike | Uint8Array)} kmlData Path to KML file or Data of KML file
* @param {(GeoPackage | string)} geopackage String name or instance of Geopackage to use
* @param {string} tableName Name of table with geometry
* @param {Function} [progressCallback] Passed the current status of the function.
* @returns {Promise<GeoPackage>} Promise of a Geopackage
* @memberof KMLToGeoPackage
*/
async convertKMLToGeoPackage(
kmlData: PathLike | Uint8Array,
geopackage: GeoPackage | string,
tableName: string,
progressCallback?: Function,
): Promise<GeoPackage> {
if (typeof geopackage === 'string' || _.isNil(geopackage)) {
geopackage = await this.createOrOpenGeoPackage(geopackage, this.options);
}
if (progressCallback) progressCallback({ status: 'Obtaining Meta-Data about KML', file: kmlData });
const { props: props, bbox: BoundingBox } = await this.getMetaDataKML(kmlData, geopackage, progressCallback);
this.properties = props;
if (progressCallback)
progressCallback({
status: 'Setting Up Geometry table',
data: 'with props: ' + props.toString() + ', Bounding Box: ' + BoundingBox.toString(),
});
geopackage = await this.setUpTableKML(tableName, geopackage, props, BoundingBox, progressCallback);
if (progressCallback) progressCallback({ status: 'Setting Up Style and Icon Tables' });
const defaultStyles = await this.setUpStyleKML(geopackage, tableName);
// Geometry and Style Insertion
if (progressCallback) progressCallback({ status: 'Adding Data to the Geopackage' });
await this.addKMLDataToGeoPackage(kmlData, geopackage, defaultStyles, tableName, progressCallback);
if (this.options.indexTable && props.size !== 0) {
if (progressCallback) progressCallback({ status: 'Indexing the Geopackage' });
await geopackage.indexFeatureTable(tableName);
}
return geopackage;
}
/**
* Takes in KML and the properties of the KML and creates a table in the geopackage folder.
*
* @param {string} tableName name the Database table will be called
* @param {GeoPackage} geopackage file name or GeoPackage object
* @param {Set<string>} properties columns name gotten from getMetaDataKML
* @param {BoundingBox} boundingBox
* @callback progressCallback Passed the current status of the function.
* @returns {Promise<GeoPackage>} Promise of a GeoPackage
*/
async setUpTableKML(
tableName: string,
geopackage: GeoPackage,
properties: Set<string>,
boundingBox: BoundingBox,
progressCallback?: Function,
): Promise<GeoPackage> {
return new Promise(async resolve => {
if (properties.size !== 0) {
const geometryColumns = new GeometryColumns();
geometryColumns.table_name = tableName;
geometryColumns.column_name = 'geometry';
geometryColumns.geometry_type_name = 'GEOMETRY';
geometryColumns.z = 2;
geometryColumns.m = 2;
const columns = [];
columns.push(FeatureColumn.createPrimaryKeyColumnWithIndexAndName(0, 'id'));
columns.push(FeatureColumn.createGeometryColumn(1, 'geometry', 'GEOMETRY', false, null));
let index = 2;
for (const prop of properties) {
columns.push(FeatureColumn.createColumn(index, prop, DataTypes.fromName('TEXT'), false, null));
index++;
}
if (progressCallback) progressCallback({ status: 'Creating Geometry Table' });
await geopackage.createFeatureTable(
tableName,
geometryColumns,
columns,
boundingBox,
this.options.hasOwnProperty('srsNumber') ? this.options.srsNumber : 4326,
);
}
resolve(geopackage);
});
}
/**
* Inserts style information from the KML in the GeoPackage.
*
* @param {GeoPackage} geopackage Geopackage instance of
* @param {string} tableName Name of Main Table
* @param {Function} [progressCallback] Passed the current status of the function.
* @returns {Promise<FeatureTableStyles>} Promise of a Feature Table of Styles
* @memberof KMLToGeoPackage
*/
setUpStyleKML(geopackage: GeoPackage, tableName: string, progressCallback?: Function): Promise<FeatureTableStyles> {
return new Promise(async resolve => {
if (this.hasStyles) {
if (progressCallback) progressCallback({ status: 'Creating Default KML Styles and Icons.' });
const defaultStyles = await KMLUtilities.setUpKMLDefaultStylesAndIcons(geopackage, tableName, progressCallback);
// Specific Styles SetUp
if (progressCallback) progressCallback({ status: 'Adding Styles and Icon if they exist.' });
if (this.styleMap.size !== 0) this.addSpecificStyles(defaultStyles, this.styleMap);
if (this.iconMap.size !== 0) await this.addSpecificIcons(defaultStyles, this.iconMap);
resolve(defaultStyles);
}
resolve(null);
});
}
/**
* Reads the KML file and extracts Geometric data and matches styles with the Geometric data.
* Also read the Ground Overlays.
*
* @param {(PathLike | Uint8Array)} kmlData Path to KML file or KML Data
* @param {GeoPackage} geopackage GeoPackage instance
* @param {FeatureTableStyles} defaultStyles Feature Table Style Object
* @param {string} tableName Name of Main table for Geometry
* @param {Function} [progressCallback]
* @returns {Promise<void>}
* @memberof KMLToGeoPackage
*/
async addKMLDataToGeoPackage(
kmlData: PathLike | Uint8Array,
geopackage: GeoPackage,
defaultStyles: FeatureTableStyles,
tableName: string,
progressCallback?: Function,
): Promise<void> {
return new Promise(async resolve => {
if (progressCallback) progressCallback({ status: 'Setting up Multi Geometry table.' });
const multiGeometryTableName = 'multi_geometry';
const multiGeometryMapName = multiGeometryTableName + '_' + tableName;
const relatedTableExtension = new RelatedTablesExtension(geopackage);
const multiGeometryMap = UserMappingTable.create(multiGeometryMapName);
if (this.hasMultiGeometry) {
if (progressCallback) progressCallback({ status: 'Creating MultiGeometry Tables' });
geopackage.createSimpleAttributesTable(multiGeometryTableName, [
{ name: 'number_of_geometries', dataType: 'INT' },
]);
const relationShip = RelatedTablesExtension.RelationshipBuilder()
.setBaseTableName(tableName)
.setRelatedTableName(multiGeometryTableName)
.setUserMappingTable(multiGeometryMap);
await relatedTableExtension.addSimpleAttributesRelationship(relationShip);
}
let stream: Streamer.Duplex | fs.ReadStream;
if (kmlData instanceof Uint8Array) {
stream = new Streamer.Duplex();
stream.push(kmlData);
stream.push(null);
} else {
stream = fs.createReadStream(kmlData);
}
const kml = new XmlStream(stream, 'UTF-8');
kml.preserve('coordinates', true);
kml.collect('LinearRing');
kml.collect('Polygon');
kml.collect('Point');
kml.collect('LineString');
kml.collect('Data');
kml.collect('value');
// kml.collect('Folder');
// kml.collect('Placemark');
let asyncProcessesRunning = 0;
kml.on('endElement: ' + KMLTAGS.GROUND_OVERLAY_TAG, async node => {
asyncProcessesRunning++;
if (progressCallback) progressCallback({ status: 'Handling GroundOverlay Tag.', data: node });
let image: Jimp | void;
if (isNode) {
if (progressCallback) progressCallback({ status: 'Moving Ground Overlay image into Memory' });
// Determines whether the image is local or online.
image = await ImageUtilities.getJimpImage(node.Icon.href, path.dirname(kmlData.toString())).catch(err =>
console.error(err),
);
} else if (isBrowser) {
image = await ImageUtilities.getJimpImage(node.Icon.href, null, this.zipFileMap).catch(err =>
console.error(err),
);
}
if (image) {
KMLUtilities.handleGroundOverLay(node, geopackage, image, progressCallback).catch(err =>
console.error('Error not able to Handle Ground Overlay :', err),
);
}
asyncProcessesRunning--;
});
kml.on('endElement: ' + KMLTAGS.PLACEMARK_TAG, node => {
if (progressCallback) progressCallback({ status: 'Handling Placemark Tag.', data: node });
let isMultiGeometry = false;
const geometryIds = [];
const geometryNodes = KMLUtilities.setUpGeometryNodes(node);
if (geometryNodes.length > 1) isMultiGeometry = true;
do {
const currentNode = geometryNodes.pop();
const geometryId = this.addPropertiesAndGeometryValues(currentNode, defaultStyles, geopackage, tableName);
if (geometryId !== -1) geometryIds.push(geometryId);
} while (geometryNodes.length !== 0);
if (isMultiGeometry && this.hasMultiGeometry) {
KMLUtilities.writeMultiGeometry(
geometryIds,
geopackage,
multiGeometryTableName,
relatedTableExtension,
multiGeometryMapName,
);
}
});
kml.on('end', async () => {
while (asyncProcessesRunning > 0) {
if (progressCallback) progressCallback({ status: 'Waiting on Async Functions' });
await new Promise(resolve => setTimeout(resolve, 1000));
}
if (progressCallback) progressCallback({ status: 'Finished adding data to the Geopackage' });
resolve();
});
});
}
/**
* Runs through KML and finds name for Columns and Style information. Handles Networks Links. Handles Bounding Boxes
* @param kmlData Path to KML File or Uint8 array
* @param {GeoPackage} geopackage
* @param progressCallback
*/
/**
* Runs through KML and finds name for Columns and Style information. Handles Networks Links. Handles Bounding Boxes
*
* @param {(PathLike | Uint8Array)} kmlData Path to KML File or KML Data
* @param {GeoPackage} [geopackage] Geopackage instance; Needed when using Network Links
* @param {Function} [progressCallback]
* @returns {Promise<{ props: Set<string>; bbox: BoundingBox }>} Object of the set of property name and the total Bounding Box
* @memberof KMLToGeoPackage
*/
getMetaDataKML(
kmlData: PathLike | Uint8Array,
geopackage?: GeoPackage,
progressCallback?: Function,
): Promise<{ props: Set<string>; bbox: BoundingBox }> {
return new Promise(async resolve => {
if (progressCallback)
progressCallback({ status: 'Setting up XML-Stream to find Meta-data about the KML file', file: kmlData });
const properties = new Set<string>();
// Bounding box
const boundingBox = new BoundingBox(null);
let kmlOnsRunning = 0;
let stream: Streamer.Duplex | fs.ReadStream;
if (kmlData instanceof Uint8Array) {
stream = new Streamer.Duplex();
stream.push(kmlData);
stream.push(null);
} else {
stream = fs.createReadStream(kmlData);
}
const kml = new XmlStream(stream, 'UTF-8');
kml.preserve(KMLTAGS.COORDINATES_TAG, true);
kml.collect(KMLTAGS.PAIR_TAG);
kml.collect(KMLTAGS.GEOMETRY_TAGS.POINT);
kml.collect(KMLTAGS.GEOMETRY_TAGS.LINESTRING);
kml.collect(KMLTAGS.GEOMETRY_TAGS.POLYGON);
kml.collect(KMLTAGS.DATA_TAG);
kml.collect(KMLTAGS.VALUE_TAG);
kml.collect(KMLTAGS.PLACEMARK_TAG);
kml.on('endElement: ' + KMLTAGS.NETWORK_LINK_TAG, async (node: any) => {
kmlOnsRunning++;
if (node.hasOwnProperty('Link') || node.hasOwnProperty('Url')) {
const linkType = node.hasOwnProperty('Link') ? 'Link' : 'Url';
if (progressCallback) {
progressCallback({
status: 'Handling Network Link Tag. Handling Meta Data',
file: node[linkType].href,
data: node,
});
}
// TODO: Handle Browser Case.
if (node[linkType].href.toString().startsWith('http')) {
await axios
.get(node[linkType].href.toString())
.then(async response => {
const fileName = path.join(__dirname, path.basename(node[linkType].href));
fs.createWriteStream(fileName).write(response.data);
this.options.append = true;
const linkedFile = new KMLToGeoPackage({ append: true });
await linkedFile.convertKMLOrKMZToGeopackage(
fileName,
false,
geopackage,
path.basename(fileName, path.extname(fileName)),
);
kmlOnsRunning--;
})
.catch(error => {
console.error(error);
});
} else {
console.error(node[linkType].href.toString(), 'locator is not supported.');
}
// Need to add handling for other files
} else {
kmlOnsRunning--;
}
});
kml.on('endElement: ' + KMLTAGS.PLACEMARK_TAG, (node: {}) => {
this.numberOfPlacemarks++;
if (progressCallback) {
progressCallback({
status: 'Handling Placemark Tag. Adds an addition KML file',
data: node,
});
}
kmlOnsRunning++;
for (const property in node) {
// Item to be treated like a Geometry
if (
_.findIndex(KMLTAGS.ITEM_TO_SEARCH_WITHIN, o => {
return o === property;
}) !== -1
) {
node[property].forEach(element => {
for (const subProperty in element) {
if (
_.findIndex(KMLTAGS.INNER_ITEMS_TO_IGNORE, o => {
return o === subProperty;
}) === -1
) {
properties.add(subProperty);
}
}
});
} else if (property === KMLTAGS.GEOMETRY_TAGS.MULTIGEOMETRY) {
this.hasMultiGeometry = true;
for (const subProperty in node[property]) {
node[property][subProperty].forEach(element => {
for (const subSubProperty in element) {
if (
_.findIndex(KMLTAGS.INNER_ITEMS_TO_IGNORE, o => {
return o === subSubProperty;
}) === -1
) {
properties.add(subSubProperty);
}
}
});
}
} else {
properties.add(property);
}
}
kmlOnsRunning--;
});
kml.on('endElement: ' + KMLTAGS.PLACEMARK_TAG + ' ' + KMLTAGS.COORDINATES_TAG, node => {
kmlOnsRunning++;
if (!_.isEmpty(node)) {
try {
const rows = node[KMLTAGS.XML_STREAM_TEXT_SELECTOR].split(/\s+/);
rows.forEach((element: string) => {
const temp = element.split(',').map(s => Number(s));
GeoSpatialUtilities.expandBoundingBoxToIncludeLatLonPoint(boundingBox, temp[0], temp[1]);
});
} catch (error) {
console.error('Something went wrong when reading coordinates:', error);
}
}
kmlOnsRunning--;
});
kml.on('endElement: ' + KMLTAGS.DOCUMENT_TAG + ' ' + KMLTAGS.STYLE_TAG, (node: {}) => {
kmlOnsRunning++;
if (
node.hasOwnProperty(KMLTAGS.STYLE_TYPE_TAGS.LINE_STYLE) ||
node.hasOwnProperty(KMLTAGS.STYLE_TYPE_TAGS.POLY_STYLE)
) {
try {
this.styleMap.set(node['$'].id, node);
} catch (err) {
console.error(err);
} finally {
this.hasStyles = true;
}
}
if (node.hasOwnProperty(KMLTAGS.STYLE_TYPE_TAGS.ICON_STYLE)) {
try {
this.iconMap.set(node['$'].id, node);
} finally {
this.hasStyles = true;
}
}
kmlOnsRunning--;
});
kml.on('endElement: ' + KMLTAGS.DOCUMENT_TAG + '>' + KMLTAGS.STYLE_MAP_TAG, node => {
kmlOnsRunning++;
node.Pair.forEach((item: { key: string; styleUrl: string }) => {
if (item.key === 'normal') {
this.styleMapPair.set('#' + node['$'].id, item.styleUrl);
this.iconMapPair.set('#' + node['$'].id, item.styleUrl);
}
});
kmlOnsRunning--;
});
kml.on('end', async () => {
while (kmlOnsRunning > 0) {
await new Promise(resolve => setTimeout(resolve, 100));
}
if (progressCallback) {
progressCallback({
status: 'Finished Reading KML File.',
});
}
resolve({ props: properties, bbox: boundingBox });
});
});
}
/**
* Determines whether to create a new file or open an existing file.
*
* @param {(GeoPackage | string)} geopackage String Name or instance of a GeoPackage
* @param {KMLConverterOptions} options
* @param {Function} [progressCallback]
* @returns {Promise<GeoPackage>} Promise of a GeoPackage
* @memberof KMLUtilities
*/
async createOrOpenGeoPackage(
geopackage: GeoPackage | string,
options: KMLConverterOptions,
progressCallback?: Function,
): Promise<GeoPackage> {
if (typeof geopackage === 'object') {
if (progressCallback) await progressCallback({ status: 'Opening GeoPackage' });
return geopackage;
} else {
let stats: fs.Stats;
try {
stats = fs.statSync(geopackage);
} catch (e) {}
if (stats && !options.append) {
console.log('GeoPackage file already exists, refusing to overwrite ' + geopackage);
throw new Error('GeoPackage file already exists, refusing to overwrite ' + geopackage);
} else if (stats) {
console.log('open geopackage');
return GeoPackageAPI.open(geopackage);
}
if (progressCallback) await progressCallback({ status: 'Creating GeoPackage' });
console.log('Create new geopackage', geopackage);
return GeoPackageAPI.create(geopackage);
}
}
/*
* Private/Helper Methods
*/
/**
* Adds style and geometries to the geopackage.
*
* @private
* @param {*} node node from kml by xml-stream
* @param {FeatureTableStyles} defaultStyles style table
* @param {GeoPackage} geopackage Geopackage information will be entered into
* @param {string} tableName name of geometry table
* @param {Function} [progressCallback]
* @returns {number} Id of the Feature
* @memberof KMLToGeoPackage
*/
private addPropertiesAndGeometryValues(
node: any,
defaultStyles: FeatureTableStyles,
geopackage: GeoPackage,
tableName: string,
progressCallback?: Function,
): number {
const props = {};
let styleRow: StyleRow;
let iconRow: IconRow;
for (const prop in node) {
if (prop === KMLTAGS.STYLE_URL_TAG) {
try {
let styleId = this.styleUrlMap.get(node[prop]);
let iconId = this.iconUrlMap.get(node[prop]);
if (styleId !== undefined) {
styleRow = this.styleRowMap.get(styleId);
} else {
const normalStyle = this.styleMapPair.get(node[prop]);
styleId = this.styleUrlMap.get(normalStyle);
styleRow = this.styleRowMap.get(styleId);
}
if (iconId !== undefined) {
iconRow = this.iconRowMap.get(iconId);
} else {
const normalStyle = this.iconMapPair.get(node[prop]);
iconId = this.iconUrlMap.get(normalStyle);
iconRow = this.iconRowMap.get(iconId);
}
} catch (error) {
console.error('Error in mapping style or icons', error);
}
} else if (prop === KMLTAGS.STYLE_TAG) {
try {
const tempMap = new Map<string, object>();
tempMap.set(node[KMLTAGS.NAME_TAG], node[KMLTAGS.STYLE_TAG]);
this.addSpecificStyles(defaultStyles, tempMap);
this.addSpecificIcons(defaultStyles, tempMap);
const styleId = this.styleUrlMap.get('#' + node[KMLTAGS.NAME_TAG]);
styleRow = this.styleRowMap.get(styleId);
const iconId = this.iconUrlMap.get('#' + node[KMLTAGS.NAME_TAG]);
iconRow = this.iconRowMap.get(iconId);
} catch (err) {
console.error('Error in mapping local style tags:', err);
}
} else if (prop === KMLTAGS.STYLE_MAP_TAG) {
try {
const normalStyle = this.styleMapPair.get(node['$'].id);
const styleId = this.styleUrlMap.get(normalStyle);
styleRow = this.styleRowMap.get(styleId);
} catch (err) {
console.error('Error in Style Map:', err);
}
}
const element = _.findIndex(KMLTAGS.ITEM_TO_SEARCH_WITHIN, o => {
return o === prop;
});
if (element !== -1) {
for (const subProp in node[prop][0]) {
if (
_.findIndex(KMLTAGS.INNER_ITEMS_TO_IGNORE, o => {
return o === subProp;
}) === -1
) {
props[subProp] = node[prop][0][subProp];
}
}
} else {
if (typeof node[prop] === 'string') {
props[prop] = node[prop];
} else if (typeof node[prop] === 'object') {
props[prop] = JSON.stringify(node[prop]);
} else if (typeof node[prop] === 'number') {
props[prop] = node[prop];
}
}
}
const geometryData = KMLUtilities.kmlToGeoJSON(node);
const isGeom = !_.isNil(geometryData);
const feature: any = {
type: 'Feature',
geometry: geometryData,
properties: props,
};
let featureID = -1;
if (isGeom) {
featureID = geopackage.addGeoJSONFeatureToGeoPackage(feature, tableName);
if (!_.isNil(styleRow)) {
defaultStyles.setStyle(featureID, geometryData.type, styleRow);
}
if (!_.isNil(iconRow) && !_.isNil(iconRow.data)) {
defaultStyles.setIcon(featureID, geometryData.type, iconRow).catch(e => console.error(e));
}
} else {
featureID = geopackage.addGeoJSONFeatureToGeoPackage(feature, tableName);
}
return featureID;
}
/**
* Loops through provided map of names of icons and object data of the icons.
*
* @private
* @param {FeatureTableStyles} styleTable Feature Table Style
* @param {Map<string, object>} items icons to add to the style table
* @returns {Promise<void>}
* @memberof KMLToGeoPackage
*/
private async addSpecificIcons(styleTable: FeatureTableStyles, items: Map<string, object>): Promise<void> {
return new Promise(async resolve => {
for (const item of items) {
const { id: id, newIcon: icon } = await KMLUtilities.addSpecificIcon(styleTable, item).catch(e => {
console.error(e);
return { id: -1, newIcon: null };
});
if (id >= 0 && !_.isNil(icon)) {
this.iconUrlMap.set('#' + item[0], id);
this.iconRowMap.set(id, icon);
}
}
resolve();
});
}
/**
* Adds styles to the table provided.
* Saves id and name in this.styleRowMap and this.styleUrlMap
*
* @private
* @param {FeatureTableStyles} styleTable Feature Style Table
* @param {Map<string, object>} items Map of the name of the style and the style itself from the KML
* @memberof KMLToGeoPackage
*/
private addSpecificStyles(styleTable: FeatureTableStyles, items: Map<string, object>): void {
for (const item of items) {
let isStyle = false;
const styleName = item[0];
const kmlStyle = item[1];
const newStyle = styleTable.getStyleDao().newRow();
newStyle.setName(styleName);
// Styling for Lines
if (kmlStyle.hasOwnProperty(KMLTAGS.STYLE_TYPE_TAGS.LINE_STYLE)) {
isStyle = true;
if (kmlStyle[KMLTAGS.STYLE_TYPE_TAGS.LINE_STYLE].hasOwnProperty('color')) {
const abgr = kmlStyle[KMLTAGS.STYLE_TYPE_TAGS.LINE_STYLE]['color'];
const { rgb, a } = KMLUtilities.abgrStringToColorOpacity(abgr);
newStyle.setColor(rgb, a);
}
if (kmlStyle[KMLTAGS.STYLE_TYPE_TAGS.LINE_STYLE].hasOwnProperty('width')) {
newStyle.setWidth(kmlStyle[KMLTAGS.STYLE_TYPE_TAGS.LINE_STYLE]['width']);
}
}
// Styling for Polygons
if (kmlStyle.hasOwnProperty(KMLTAGS.STYLE_TYPE_TAGS.POLY_STYLE)) {
isStyle = true;
if (kmlStyle[KMLTAGS.STYLE_TYPE_TAGS.POLY_STYLE].hasOwnProperty('color')) {
const abgr = kmlStyle[KMLTAGS.STYLE_TYPE_TAGS.POLY_STYLE]['color'];
const { rgb, a } = KMLUtilities.abgrStringToColorOpacity(abgr);
newStyle.setFillColor(rgb, a);
}
if (kmlStyle[KMLTAGS.STYLE_TYPE_TAGS.POLY_STYLE].hasOwnProperty('fill')) {
if (!kmlStyle[KMLTAGS.STYLE_TYPE_TAGS.POLY_STYLE]['fill']) {
newStyle.setFillOpacity(0);
}
}
if (kmlStyle[KMLTAGS.STYLE_TYPE_TAGS.POLY_STYLE].hasOwnProperty('outline')) {
// console.log(kmlStyle[KMLTAGS.STYLE_TYPES.POLY_STYLE]);
// No property Currently TODO
// newStyle.(item[1]['LineStyle']['outline']);
}
}
// Add Style to Geopackage
if (isStyle) {
const newStyleId = styleTable.getFeatureStyleExtension().getOrInsertStyle(newStyle);
this.styleUrlMap.set('#' + styleName, newStyleId);
this.styleRowMap.set(newStyleId, newStyle);
}
}
}
} | the_stack |
import {
$el,
bind,
getBooleanTypeAttr,
getNumTypeAttr,
getStrTypeAttr,
removeAttrs,
setHtml
} from '../../dom-utils';
import { warn } from '../../mixins';
import { type, validComps } from '../../utils';
import PREFIX from '../prefix';
interface Config {
config(
el: string
): {
value: number;
step: number;
disabled: boolean;
readOnly: boolean;
editable: boolean;
events({ onChange, onFocus, onBlur }: InputNumberEvents): void;
};
}
interface InputNumberEvents {
onChange?: (value: number) => void;
onFocus?: (event: InputEvent) => void;
onBlur?: () => void;
}
function addNum(num1: number, num2: number): number {
let sq1: number, sq2: number;
try {
sq1 = num1.toString().split('.')[1].length;
} catch (e) {
sq1 = 0;
}
try {
sq2 = num2.toString().split('.')[1].length;
} catch (e) {
sq2 = 0;
}
const m = Math.pow(10, Math.max(sq1, sq2));
return (Math.round(num1 * m) + Math.round(num2 * m)) / m;
}
class InputNumber implements Config {
readonly VERSION: string;
readonly COMPONENTS: NodeListOf<HTMLElement>;
constructor() {
this.VERSION = 'v1.0';
this.COMPONENTS = $el('r-input-number', { all: true });
this._create(this.COMPONENTS);
}
public config(
el: string
): {
value: number;
step: number;
disabled: boolean;
readOnly: boolean;
editable: boolean;
events({ onChange, onFocus, onBlur }: InputNumberEvents): void;
} {
const target = $el(el) as HTMLElement;
validComps(target, 'input-number');
const { _attrs, _setValue, _setDisabled } = InputNumber.prototype;
const { min, max, step, disabled, readOnly, editable, precision, formatter } = _attrs(
target
);
const Input = target.querySelector(`.${PREFIX.inputnb}-input`)! as HTMLInputElement;
const ArrowUp = target.querySelector(`.${PREFIX.inputnb}-handler-up`);
const ArrowDown = target.querySelector(`.${PREFIX.inputnb}-handler-down`);
const BtnUp = target.querySelector(`.${PREFIX.inputnb}-controls-outside-up`);
const BtnDown = target.querySelector(`.${PREFIX.inputnb}-controls-outside-down`);
return {
get value() {
return Number(Input.value);
},
set value(newVal: number) {
if (newVal && !type.isNum(newVal)) return;
_setValue(Input, newVal, formatter, precision, min, max);
},
get step() {
return step;
},
set step(newVal: number) {
if (newVal && !type.isNum(newVal)) return;
Input.step = step;
},
get disabled() {
return disabled;
},
set disabled(newVal: boolean) {
if (newVal && !type.isBol(newVal)) return;
_setDisabled(target, Input, newVal);
},
get readOnly() {
return readOnly;
},
set readOnly(newVal: boolean) {
if (newVal && !type.isBol(newVal)) return;
Input.readOnly = newVal;
const disableArrow = (elem1: Element | null, elem2: Element | null) => {
if (elem1) {
// @ts-ignore
elem1.style.pointerEvents = newVal ? 'none' : '';
// @ts-ignore
elem2.style.pointerEvents = newVal ? 'none' : '';
}
};
disableArrow(ArrowUp, ArrowDown);
disableArrow(BtnUp, BtnDown);
},
get editable() {
return editable;
},
set editable(newVal: boolean) {
if (newVal && !type.isBol(newVal)) return;
Input.style.pointerEvents = !newVal ? 'none' : '';
},
events({ onChange, onFocus, onBlur }) {
let value: number;
const changeEv = (e: Event) => {
e.stopPropagation();
value = Number(Input.value);
if (!isNaN(value)) {
onChange && type.isFn(onChange, value);
} else {
warn(`Invalid input value --> '${Input.value}' at '${el}'`);
return;
}
};
if (ArrowUp) {
bind(ArrowUp, 'click', changeEv);
bind(ArrowDown, 'click', changeEv);
}
if (BtnUp) {
bind(BtnUp, 'click', changeEv);
bind(BtnDown, 'click', changeEv);
}
bind(Input, 'keydown', (e: KeyboardEvent) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') changeEv(e);
});
bind(Input, 'input', (e: InputEvent) => changeEv(e));
bind(Input, 'focus', (e: InputEvent) => {
e.stopPropagation();
onFocus && type.isFn(onFocus, e);
});
bind(Input, 'blur', (e: InputEvent) => {
e.stopPropagation();
onBlur && type.isFn(onBlur);
});
}
};
}
private _create(COMPONENTS: NodeListOf<HTMLElement>) {
COMPONENTS.forEach((node) => {
const {
min,
max,
step,
value,
name,
inputId,
parser,
formatter,
precision,
disabled,
editable,
readOnly,
size,
placeholder,
controlsOutside
} = this._attrs(node);
this._setMainTemplate(node);
this._setOutSide(node, controlsOutside);
const Input = node.querySelector(`.${PREFIX.inputnb}-input`)! as HTMLInputElement;
const ArrowUp = node.querySelector(`.${PREFIX.inputnb}-handler-up`);
const ArrowDown = node.querySelector(`.${PREFIX.inputnb}-handler-down`);
const BtnUp = node.querySelector(`.${PREFIX.inputnb}-controls-outside-up`);
const BtnDown = node.querySelector(`.${PREFIX.inputnb}-controls-outside-down`);
this._setInput(Input, min, max, step, name, inputId, placeholder);
this._setValue(Input, value, formatter, precision, min, max);
this._setSize(node, size);
this._setDisabled(node, Input, disabled);
this._setReadonlyAndEditable(Input, readOnly, editable);
this._setHandler(ArrowUp, ArrowDown, BtnUp, BtnDown, value, min, max);
this._handleChange(
Input,
ArrowUp,
ArrowDown,
BtnUp,
BtnDown,
min,
max,
step,
precision,
readOnly,
parser,
formatter
);
removeAttrs(node, [
'min',
'max',
'step',
'value',
'precision',
'size',
'name',
'parser',
'formatter',
'input-id',
'placeholder',
'disabled',
'editable',
'readOnly',
'controls-outside'
]);
});
}
private _setMainTemplate(node: HTMLElement): void {
node.classList.add(`${PREFIX.inputnb}`);
const template = `
<div class="${PREFIX.inputnb}-handler-wrap">
<a class="${PREFIX.inputnb}-handler ${PREFIX.inputnb}-handler-up">
<span class="${PREFIX.inputnb}-handler-up-inner ${PREFIX.icon} ${PREFIX.icon}-ios-arrow-up"></span>
</a>
<a class="${PREFIX.inputnb}-handler ${PREFIX.inputnb}-handler-down">
<span class="${PREFIX.inputnb}-handler-down-inner ${PREFIX.icon} ${PREFIX.icon}-ios-arrow-down"></span>
</a>
</div>
<div class="${PREFIX.inputnb}-input-wrap">
<input autocomplete="off" spellcheck="false" class="${PREFIX.inputnb}-input">
</div>
`;
setHtml(node, template);
}
private _setOutSide(node: HTMLElement, controlsOutside: boolean): void {
if (!controlsOutside) return;
node.classList.add(`${PREFIX.inputnb}-controls-outside`);
const handlerWrap = node.querySelector(`.${PREFIX.inputnb}-handler-wrap`)!;
const template = `
<div class="${PREFIX.inputnb}-controls-outside-btn ${PREFIX.inputnb}-controls-outside-down">
<i class="${PREFIX.icon} ${PREFIX.icon}-ios-remove"></i>
</div>
<div class="${PREFIX.inputnb}-controls-outside-btn ${PREFIX.inputnb}-controls-outside-up">
<i class="${PREFIX.icon} ${PREFIX.icon}-ios-add"></i>
</div>
`;
handlerWrap.insertAdjacentHTML('afterend', template);
handlerWrap.remove();
}
private _setInput(
input: HTMLInputElement,
min: number,
max: number,
step: number,
name: string,
inputId: string,
placeholder: string
): void {
isNaN(min) || min === 0 ? (input.min = `${min}`) : '';
isNaN(max) || min === 0 ? (input.max = `${max}`) : '';
isNaN(step) && step !== 1 ? (input.step = `${step}`) : '';
name ? (input.name = name) : '';
inputId ? (input.id = inputId) : '';
placeholder ? (input.placeholder = placeholder) : '';
}
private _formatterVal(input: HTMLInputElement, formatter: string, val: number): void {
// `约定的 ${value}`替换为 `${val}`
const resVal = formatter.replace('value', 'val');
input.value = `${formatter ? eval(resVal) : val}`;
}
private _parserVal(parser: string, val: string): string {
if (parser) {
const _parser = eval(parser) as any[];
return val.replace(_parser[0], _parser[1]);
} else {
// 如果没有指定从 formatter 里转换回数字的方式,则使用默认正则方式
return val.replace(/[^\d.-]/g, '');
}
}
private _handleChange(
input: HTMLInputElement,
aUp: Element | null,
aDown: Element | null,
btnUp: Element | null,
btnDown: Element | null,
min: number,
max: number,
step: number,
precision: number,
readOnly: boolean,
parser: string,
formatter: string
): void {
if (readOnly) return;
const setValue = (val: number) => {
this._setValue(input, val, formatter, precision, min, max);
this._setHandler(aUp, aDown, btnUp, btnDown, val, min, max);
};
const changeStep = (type: 'up' | 'down'): false | undefined => {
// 如果指定了输入框展示值的格式,那么这里就要用 parser 的值转换为原来的值
const val = this._parserVal(parser, input.value);
const targetVal = Number(val);
if (type === 'up') {
if (addNum(targetVal, step) <= max) {
setValue(targetVal);
} else {
return false;
}
setValue(addNum(targetVal, step));
} else if (type === 'down') {
if (addNum(targetVal, step) >= min) {
setValue(targetVal);
} else {
return false;
}
setValue(addNum(targetVal, -step));
}
};
const handleKeyBoardChange = () => {
bind(input, 'keydown', (e: KeyboardEvent) => {
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return false;
if (e.key === 'ArrowUp') {
e.preventDefault();
changeStep('up');
}
if (e.key === 'ArrowDown') {
e.preventDefault();
changeStep('down');
}
});
};
const handleInputChange = () => {
bind(input, 'input', (e: InputEvent) => {
e.stopPropagation();
// 当输入框输入时只匹配数字、小数点和减号
const val = input.value.replace(/[^\d.-]/g, '');
setValue(Number(val));
});
};
const handleArrowChange = () => {
if (aUp && aDown) {
bind(aUp, 'click', () => changeStep('up'));
bind(aDown, 'click', () => changeStep('down'));
}
if (btnUp && btnDown) {
bind(btnUp, 'click', () => changeStep('up'));
bind(btnDown, 'click', () => changeStep('down'));
}
};
handleKeyBoardChange();
handleInputChange();
handleArrowChange();
}
private _setValue(
input: HTMLInputElement,
value: number,
formatter: string,
precision: number,
min: number,
max: number
): void {
let targetVal: any = !isNaN(precision) ? value.toFixed(precision) : value;
if ((targetVal && !isNaN(targetVal)) || targetVal === 0) {
if (targetVal > max && !isNaN(max)) {
targetVal = max;
} else if (targetVal < min && !isNaN(min)) {
targetVal = min;
}
// 如果指定了输入框展示值的格式则使用它,否则反之
this._formatterVal(input, formatter, targetVal);
}
}
private _setSize(node: Element, size: string): void {
if (!size) return;
node.classList.add(`${PREFIX.inputnb}-${size}`);
}
private _setReadonlyAndEditable(
input: HTMLInputElement,
readOnly: boolean,
editable: string
): void {
if (readOnly) input.readOnly = true;
if (readOnly || editable === 'false') input.style.pointerEvents = 'none';
}
private _setDisabled(node: HTMLElement, input: HTMLInputElement, disabled: boolean): void {
if (!disabled) {
node.classList.remove(`${PREFIX.inputnb}-disabled`);
input.disabled = false;
} else {
node.classList.add(`${PREFIX.inputnb}-disabled`);
input.disabled = true;
}
}
private _setHandler(
aUp: Element | null,
aDown: Element | null,
btnUp: Element | null,
btnDown: Element | null,
value: number,
min: number,
max: number
): void {
const isSetDisable = (elm1: Element, elm2: Element, outside: boolean) => {
const upDisabledCls = outside ? 'controls-outside-btn' : 'handler-up';
const downDisabledCls = outside ? 'controls-outside-btn' : 'handler-down';
if (Math.ceil(value) >= max) {
elm1.classList.add(`${PREFIX.inputnb}-${upDisabledCls}-disabled`);
} else {
elm1.classList.remove(`${PREFIX.inputnb}-${upDisabledCls}-disabled`);
}
if (Math.ceil(value) <= min) {
elm2.classList.add(`${PREFIX.inputnb}-${downDisabledCls}-disabled`);
} else {
elm2.classList.remove(`${PREFIX.inputnb}-${downDisabledCls}-disabled`);
}
};
if (aUp && aDown) isSetDisable(aUp, aDown, false);
if (btnUp && btnDown) isSetDisable(btnUp, btnDown, true);
}
private _attrs(node: HTMLElement) {
return {
min: getNumTypeAttr(node, 'min', -Infinity),
max: getNumTypeAttr(node, 'max', Infinity),
step: getNumTypeAttr(node, 'step', 1),
value: getNumTypeAttr(node, 'value', 0),
precision: getNumTypeAttr(node, 'precision'),
size: getStrTypeAttr(node, 'size', ''),
name: getStrTypeAttr(node, 'name', ''),
inputId: getStrTypeAttr(node, 'input-id', ''),
parser: getStrTypeAttr(node, 'parser', ''),
formatter: getStrTypeAttr(node, 'formatter', ''),
placeholder: getStrTypeAttr(node, 'placeholder', ''),
disabled: getBooleanTypeAttr(node, 'disabled'),
readOnly: getBooleanTypeAttr(node, 'readonly'),
editable: getStrTypeAttr(node, 'editable', 'true'),
controlsOutside: getBooleanTypeAttr(node, 'controls-outside')
};
}
}
export default InputNumber; | the_stack |
import * as fmc from "../../../disk/fileModelCache";
import * as fsu from "../../../utils/fsu";
import fs = require('fs');
import * as json from "../../../../common/json";
import { reverseKeysAndValues, uniq, extend, isJs } from "../../../../common/utils";
import { makeBlandError, PackageJsonParsed, TsconfigJsonParsed, TypeScriptConfigFileDetails } from "../../../../common/types";
import { increaseCompilationContext, getDefinitionsForNodeModules } from "./compilationContextExpander";
import { validate } from "./tsconfigValidation";
import * as types from '../../../../common/types';
/**
* The CompilerOptions as read from a `tsconfig.json` file.
* Most members copy pasted from ts.CompilerOptions
* - With few (e.g. `module`) replaced with `string`
* NOTE: see the changes in `types.ts` in the TypeScript sources to see what needs updating
*
* When adding you need to
* 0 Add in this interface
* 1 Add to `tsconfigValidation`
* 2 If its an enum : Update `typescriptEnumMap`
* 3 If its a path : Update `pathResolveTheseOptions`
* 4 Update the tsconfig.json file `properties` in schema from https://github.com/SchemaStore/schemastore/blob/master/src/schemas/json/tsconfig.json
*/
interface CompilerOptions {
allowJs?: boolean;
allowNonTsExtensions?: boolean;
allowSyntheticDefaultImports?: boolean;
allowUnreachableCode?: boolean;
allowUnusedLabels?: boolean;
baseUrl?: string;
charset?: string;
checkJs?: boolean;
codepage?: number;
declaration?: boolean;
declarationDir?: string;
diagnostics?: boolean;
emitBOM?: boolean;
experimentalAsyncFunctions?: boolean;
experimentalDecorators?: boolean;
emitDecoratorMetadata?: boolean;
forceConsistentCasingInFileNames?: boolean;
help?: boolean;
isolatedModules?: boolean;
init?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
jsx?: string;
locale?: string;
lib?: string[];
list?: string[];
listEmittedFiles?: boolean;
listFiles?: boolean;
mapRoot?: string;
module?: string;
moduleResolution?: string;
newLine?: string;
noEmit?: boolean;
noEmitHelpers?: boolean;
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noFallthroughCasesInSwitch?: boolean;
noImplicitAny?: boolean;
noImplicitReturns?: boolean;
noImplicitThis?: boolean
noImplicitUseStrict?: boolean;
noLib?: boolean;
noLibCheck?: boolean;
noResolve?: boolean;
noUnusedParameters?: boolean;
noUnusedLocals?: boolean;
out?: string;
outFile?: string;
outDir?: string;
paths?: ts.Map<string[]>;
preserveConstEnums?: boolean;
pretty?: string;
reactNamespace?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
skipDefaultLibCheck?: boolean;
skipLibCheck?: boolean;
sourceMap?: boolean;
sourceRoot?: string;
strict?: boolean;
strictNullChecks?: boolean;
stripInternal?: boolean;
suppressExcessPropertyErrors?: boolean;
suppressImplicitAnyIndexErrors?: boolean;
suppressOutputPathCheck?: boolean;
target?: string;
traceResolution?: boolean;
types?: string[];
typeRoots?: string[];
typesSearchPaths?: string[];
version?: boolean;
watch?: boolean;
}
/**
* This is the JSON.parse result of a tsconfig.json
*/
interface TypeScriptProjectRawSpecification {
compilerOptions?: CompilerOptions;
exclude?: string[]; // optional: An array of 'glob' patterns to specify directories / files to exclude
include?: string[]; // optional: An array of 'glob' patterns to specify directories / files to include
files?: string[]; // optional: paths to files
formatCodeOptions?: formatting.FormatCodeOptions; // optional: formatting options
compileOnSave?: boolean; // optional: compile on save. Ignored to build tools. Used by IDEs
buildOnSave?: boolean;
}
//////////////////////////////////////////////////////////////////////
export var errors = {
GET_PROJECT_INVALID_PATH: 'The path used to query for tsconfig.json does not exist',
GET_PROJECT_NO_PROJECT_FOUND: 'No Project Found',
GET_PROJECT_FAILED_TO_OPEN_PROJECT_FILE: 'Failed to fs.readFileSync the project file',
GET_PROJECT_PROJECT_FILE_INVALID_OPTIONS: 'Project file contains invalid options',
CREATE_FOLDER_MUST_EXIST: 'The folder must exist on disk in order to create a tsconfig.json',
CREATE_PROJECT_ALREADY_EXISTS: 'tsconfig.json file already exists',
};
export interface ProjectFileErrorDetails {
projectFilePath: string;
error: types.CodeError;
}
import path = require('path');
import os = require('os');
import formatting = require('./formatCodeOptions');
const projectFileName = 'tsconfig.json';
/**
* This is what we use when the user doesn't specify a files / include
*/
const invisibleFilesInclude = ["./**/*.ts", "./**/*.tsx"];
const invisibleFilesIncludeWithJS = ["./**/*.ts", "./**/*.tsx", "./**/*.js"];
/**
* What we use to
* - create a new tsconfig on disk
* - create an in memory project
* - default values for a tsconfig file read from disk. Therefore it must match ts defaults
*/
const defaultCompilerOptions: ts.CompilerOptions = {
target: ts.ScriptTarget.ES5,
module: ts.ModuleKind.CommonJS,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
jsx: ts.JsxEmit.None,
experimentalDecorators: false,
emitDecoratorMetadata: false,
declaration: false,
noImplicitAny: false,
suppressImplicitAnyIndexErrors: false,
strictNullChecks: false,
};
/**
* If you want to create a project on the fly
*/
export function getDefaultInMemoryProject(srcFile: string): TypeScriptConfigFileDetails {
var dir = path.dirname(srcFile);
const allowJs = isJs(srcFile);
var files = [srcFile];
var typings = getDefinitionsForNodeModules(dir, files);
files = increaseCompilationContext(files, allowJs);
files = uniq(files.map(fsu.consistentPath));
let project: TsconfigJsonParsed = {
compilerOptions: extend(defaultCompilerOptions, {
allowJs,
lib: [
'dom',
'es2017'
]
}),
files,
typings: typings.ours.concat(typings.implicit),
formatCodeOptions: formatting.defaultFormatCodeOptions(),
compileOnSave: true,
buildOnSave: false,
};
return {
projectFileDirectory: dir,
projectFilePath: srcFile,
project: project,
inMemory: true
};
}
/** Given an src (source file or directory) goes up the directory tree to find the project specifications.
* Use this to bootstrap the UI for what project the user might want to work on.
* Note: Definition files (.d.ts) are considered thier own project
*/
type GetProjectSyncResponse = { error?: types.CodeError, result?: TypeScriptConfigFileDetails };
export function getProjectSync(pathOrSrcFile: string): GetProjectSyncResponse {
if (!fsu.existsSync(pathOrSrcFile)) {
return {
error: makeBlandError(pathOrSrcFile, errors.GET_PROJECT_INVALID_PATH, 'tsconfig')
}
}
// Get the path directory
var dir = fs.lstatSync(pathOrSrcFile).isDirectory() ? pathOrSrcFile : path.dirname(pathOrSrcFile);
// Keep going up till we find the project file
var projectFile = '';
try {
projectFile = fsu.travelUpTheDirectoryTreeTillYouFind(dir, projectFileName);
}
catch (e) {
let err: Error = e;
if (err.message == "not found") {
let bland = makeBlandError(fsu.consistentPath(pathOrSrcFile), errors.GET_PROJECT_NO_PROJECT_FOUND, 'tsconfig');
return {
error: bland
};
}
}
projectFile = path.normalize(projectFile);
var projectFileDirectory = path.dirname(projectFile);
let projectFilePath = fsu.consistentPath(projectFile);
// We now have a valid projectFile. Parse it:
var projectSpec: TypeScriptProjectRawSpecification;
try {
var projectFileTextContent = fmc.getOrCreateOpenFile(projectFile).getContents();
} catch (ex) {
return {
error: makeBlandError(pathOrSrcFile, errors.GET_PROJECT_FAILED_TO_OPEN_PROJECT_FILE, 'tsconfig')
}
}
let res = json.parse(projectFileTextContent);
if (res.data) {
projectSpec = res.data;
}
else {
let bland = json.parseErrorToCodeError(projectFilePath, res.error, 'tsconfig');
return { error: bland };
}
// Setup default project options
if (!projectSpec.compilerOptions) projectSpec.compilerOptions = {};
// Additional global level validations
if (projectSpec.files && projectSpec.exclude) {
let bland = makeBlandError(projectFilePath, 'You cannot use both "files" and "exclude" in tsconfig.json', 'tsconfig');
return { error: bland };
}
if (projectSpec.compilerOptions.allowJs && !projectSpec.compilerOptions.outDir) {
let bland = makeBlandError(projectFilePath, 'You must use an `outDir` if you are using `allowJs` in tsconfig.json', 'tsconfig');
return { error: bland };
}
if (projectSpec.compilerOptions.allowJs && projectSpec.compilerOptions.allowNonTsExtensions) {
// Bad because otherwise all `package.json`s in the `files` start to give *JavaScript parsing* errors.
let bland = makeBlandError(projectFilePath, 'If you are using `allowJs` you should not specify `allowNonTsExtensions` in tsconfig.json', 'tsconfig');
return { error: bland };
}
/**
* Always add `outDir`(if any) to exclude
*/
if (projectSpec.compilerOptions.outDir) {
projectSpec.exclude = (projectSpec.exclude || []).concat(projectSpec.compilerOptions.outDir);
}
/**
* Finally expand whatever needs expanding
* See : https://github.com/TypeStrong/tsconfig/issues/19
*/
try {
const tsResult = ts.parseJsonConfigFileContent(projectSpec, ts.sys, path.dirname(projectFile), null, projectFile);
// console.log(tsResult); // DEBUG
projectSpec.files = tsResult.fileNames || [];
}
catch (ex) {
return {
error: makeBlandError(projectFilePath, ex.message, 'tsconfig')
}
}
var pkg: PackageJsonParsed = null;
try {
const packageJSONPath = fsu.travelUpTheDirectoryTreeTillYouFind(projectFileDirectory, 'package.json');
if (packageJSONPath) {
const parsedPackage = JSON.parse(fmc.getOrCreateOpenFile(packageJSONPath).getContents());
pkg = {
main: parsedPackage.main,
name: parsedPackage.name,
directory: path.dirname(packageJSONPath),
definition: parsedPackage.typescript && parsedPackage.typescript.definition
};
}
}
catch (ex) {
// console.error('no package.json found', projectFileDirectory, ex.message);
}
var project: TsconfigJsonParsed = {
compilerOptions: {},
files: projectSpec.files.map(x => path.resolve(projectFileDirectory, x)),
formatCodeOptions: formatting.makeFormatCodeOptions(projectSpec.formatCodeOptions),
compileOnSave: projectSpec.compileOnSave == undefined ? true : projectSpec.compileOnSave,
package: pkg,
typings: [],
buildOnSave: !!projectSpec.buildOnSave,
};
// Validate the raw compiler options before converting them to TS compiler options
var validationResult = validate(projectSpec.compilerOptions);
if (validationResult.errorMessage) {
return {
error: makeBlandError(projectFilePath, validationResult.errorMessage, 'tsconfig')
};
}
// Convert the raw options to TS options
project.compilerOptions = rawToTsCompilerOptions(projectSpec.compilerOptions, projectFileDirectory);
// Expand files to include references
project.files = increaseCompilationContext(project.files, !!project.compilerOptions.allowJs);
// Expand files to include node_modules / package.json / typescript.definition
var typings = getDefinitionsForNodeModules(dir, project.files);
project.files = project.files.concat(typings.implicit);
project.typings = typings.ours.concat(typings.implicit);
project.files = project.files.concat(typings.packagejson);
// Normalize to "/" for all files
// And take the uniq values
project.files = uniq(project.files.map(fsu.consistentPath));
projectFileDirectory = fsu.consistentPath(projectFileDirectory);
return {
result: {
projectFileDirectory: projectFileDirectory,
projectFilePath: projectFileDirectory + '/' + projectFileName,
project: project,
inMemory: false
}
};
}
/** Creates a project by source file location. Defaults are assumed unless overriden by the optional spec. */
export function createProjectRootSync(
srcFolder: string,
defaultOptions: ts.CompilerOptions = extend(defaultCompilerOptions, {
jsx: ts.JsxEmit.React,
declaration: true,
experimentalDecorators: true,
emitDecoratorMetadata: true,
outDir: 'lib',
lib: [
'dom',
'es2017',
],
}),
overWrite = true) {
if (!fs.existsSync(srcFolder)) {
throw new Error(errors.CREATE_FOLDER_MUST_EXIST);
}
var projectFilePath = path.normalize(srcFolder + '/' + projectFileName);
if (!overWrite && fs.existsSync(projectFilePath))
throw new Error(errors.CREATE_PROJECT_ALREADY_EXISTS);
// We need to write the raw spec
var projectSpec: TypeScriptProjectRawSpecification = {};
projectSpec.compilerOptions = tsToRawCompilerOptions(defaultOptions);
projectSpec.compileOnSave = true;
projectSpec.exclude = ["node_modules"];
projectSpec.include = ["src"];
fs.writeFileSync(projectFilePath, json.stringify(projectSpec, os.EOL));
return getProjectSync(srcFolder);
}
//////////////////////////////////////////////////////////////////////
/**
* ENUM to String and String to ENUM
*/
const typescriptEnumMap = {
target: {
'es3': ts.ScriptTarget.ES3,
'es5': ts.ScriptTarget.ES5,
'es6': ts.ScriptTarget.ES2015,
'es2015': ts.ScriptTarget.ES2015,
'es2016': ts.ScriptTarget.ES2016,
'es2017': ts.ScriptTarget.ES2017,
'esnext': ts.ScriptTarget.ESNext,
'next': ts.ScriptTarget.ESNext,
'latest': ts.ScriptTarget.Latest
},
module: {
'none': ts.ModuleKind.None,
'commonjs': ts.ModuleKind.CommonJS,
'amd': ts.ModuleKind.AMD,
'umd': ts.ModuleKind.UMD,
'system': ts.ModuleKind.System,
'es6': ts.ModuleKind.ES2015,
'es2015': ts.ModuleKind.ES2015,
},
moduleResolution: {
'node': ts.ModuleResolutionKind.NodeJs,
'classic': ts.ModuleResolutionKind.Classic
},
jsx: {
'none': ts.JsxEmit.None,
'preserve': ts.JsxEmit.Preserve,
'react': ts.JsxEmit.React,
'react-native': ts.JsxEmit.ReactNative,
},
newLine: {
'CRLF': ts.NewLineKind.CarriageReturnLineFeed,
'LF': ts.NewLineKind.LineFeed
}
};
/**
* These are options that are relative paths to tsconfig.json
* Note: There is also `rootDirs` that is handled manually
*/
const pathResolveTheseOptions = [
'out',
'outFile',
'outDir',
'rootDir',
'baseUrl',
];
//////////////////////////////////////////////////////////////////////
/**
* Raw To Compiler
*/
function rawToTsCompilerOptions(jsonOptions: CompilerOptions, projectDir: string): ts.CompilerOptions {
const compilerOptions = extend(defaultCompilerOptions);
/** Parse the enums */
for (var key in jsonOptions) {
if (typescriptEnumMap[key]) {
let name = jsonOptions[key];
let map = typescriptEnumMap[key];
compilerOptions[key] = map[name.toLowerCase()] || map[name.toUpperCase()];
}
else {
compilerOptions[key] = jsonOptions[key];
}
}
/**
* Parse all paths to not be relative
*/
pathResolveTheseOptions.forEach(option => {
if (compilerOptions[option] !== undefined) {
compilerOptions[option] = fsu.resolve(projectDir, compilerOptions[option] as string);
}
});
/**
* Support `rootDirs`
* https://github.com/Microsoft/TypeScript-Handbook/blob/release-2.0/pages/Module%20Resolution.md#virtual-directories-with-rootdirs
*/
if (compilerOptions.rootDirs !== undefined && Array.isArray(compilerOptions.rootDirs)) {
compilerOptions.rootDirs = compilerOptions.rootDirs.map(rd => {
return fsu.resolve(projectDir, rd as string);
});
}
/**
* Till `out` is removed. Support it by just copying it to `outFile`
*/
if (compilerOptions.out !== undefined) {
compilerOptions.outFile = path.resolve(projectDir, compilerOptions.out);
}
/**
* The default for moduleResolution as implemented by the compiler
*/
if (!jsonOptions.moduleResolution && compilerOptions.module !== ts.ModuleKind.CommonJS) {
compilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;
}
return compilerOptions;
}
/**
* Compiler to Raw
*/
function tsToRawCompilerOptions(compilerOptions: ts.CompilerOptions): CompilerOptions {
const jsonOptions = extend({}, compilerOptions) as (ts.CompilerOptions & CompilerOptions);
/**
* Convert enums to raw
*/
Object.keys(compilerOptions).forEach((key) => {
if (typescriptEnumMap[key] !== undefined && compilerOptions[key] !== undefined) {
const value = compilerOptions[key] as string;
const rawToTsMapForKey = typescriptEnumMap[key];
const reverseMap = reverseKeysAndValues(rawToTsMapForKey);
jsonOptions[key] = reverseMap[value];
}
});
return jsonOptions;
} | the_stack |
import { STORE } from "./util";
/**
* The Buffer class is an ArrayBuffer backed data writer that utilizes the internal STORE function
* provided by AssemblyScript to write data as fast as possible to memory. The generic type
* parameter represents an enum indicating the instruction type values coupled with the memory
* writes. Each instruction write results in the following values written to the buffer:
*
* 1. [instruction] `T` - This value is the instruction type cast to a `f64`
* 2. [nextIndex] `i32` - This value is the pointer to the next instruction index
* 3. [...args] `f64[]` - These values are the argument values for the instruction
*/
export class Buffer<T extends i32> {
/**
* The buffer property is a reference to an allocated block of memory that contains all the
* currently written values to the buffer. The browser eventually should obtain a pointer to this
* block and read the values from it to perform actions.
*/
protected _buffer: ArrayBuffer = new ArrayBuffer(0x10000 * sizeof<f64>());
/**
* The set of retained pointers that need to be cleaned up after a commit().
*/
protected _retained: ArrayBuffer = new ArrayBuffer(0x10000 << alignof<usize>());
/**
* The offset into the _retained pointer list.
*/
protected _retainedOffset: i32 = 0;
/**
* The offset property is a pointer to the next index that will receive a written value.
*/
private _offset: i32 = 0;
/**
* Write a single instruction to the buffer without any parameters. This results in two values
* written to the buffer.
*
* @param {T} inst - The instruction type to be written to the buffer.
*/
@inline
protected _writeZero(inst: T): void {
var buff = changetype<usize>(this._buffer);
var index: i32 = this._offset;
var next: i32 = index + 2;
STORE<f64>(buff, index, <f64>inst);
STORE<f64>(buff, index + 1, <f64>next);
this._offset = next;
}
/**
* Write a single instruction to the buffer with a single parameter. This results in three values
* written to the buffer.
*
* @param {T} inst - The instruction type to be written to the buffer.
* @param {f64} a - The first parameter for the instruction to be written to the buffer.
*/
@inline
protected _writeOne(inst: T, a: f64): void {
var buff = changetype<usize>(this._buffer);
var index: i32 = this._offset;
var next: i32 = index + 3;
STORE<f64>(buff, index, <f64>inst);
STORE<f64>(buff, index + 1, <f64>next);
STORE<f64>(buff, index + 2, a);
this._offset = next;
}
/**
* Write a single instruction to the buffer with two parameters. This results in four values
* written to the buffer.
*
* @param {T} inst - The instruction type to be written to the buffer.
* @param {f64} a - The first parameter for the instruction to be written to the buffer.
* @param {f64} b - The second parameter for the instruction to be written to the buffer.
*/
@inline
protected _writeTwo(inst: T, a: f64, b: f64): void {
var buff = changetype<usize>(this._buffer);
var index: i32 = this._offset;
var next: i32 = index + 4;
STORE<f64>(buff, index, <f64>inst);
STORE<f64>(buff, index + 1, <f64>next);
STORE<f64>(buff, index + 2, a);
STORE<f64>(buff, index + 3, b);
this._offset = next;
}
/**
* Write a single instruction to the buffer with three parameters. This results in five values
* written to the buffer.
*
* @param {T} inst - The instruction type to be written to the buffer.
* @param {f64} a - The first parameter for the instruction to be written to the buffer.
* @param {f64} b - The second parameter for the instruction to be written to the buffer.
* @param {f64} c - The third parameter for the instruction to be written to the buffer.
*/
@inline
protected _writeThree(inst: T, a: f64, b: f64, c: f64): void {
var buff = changetype<usize>(this._buffer);
var index: i32 = this._offset;
var next: i32 = index + 5;
STORE<f64>(buff, index, <f64>inst);
STORE<f64>(buff, index + 1, <f64>next);
STORE<f64>(buff, index + 2, a);
STORE<f64>(buff, index + 3, b);
STORE<f64>(buff, index + 4, c);
this._offset = next;
}
/**
* Write a single instruction to the buffer with four parameters. This results in six values
* written to the buffer.
*
* @param {T} inst - The instruction type to be written to the buffer.
* @param {f64} a - The first parameter for the instruction to be written to the buffer.
* @param {f64} b - The second parameter for the instruction to be written to the buffer.
* @param {f64} c - The third parameter for the instruction to be written to the buffer.
* @param {f64} d - The fourth parameter for the instruction to be written to the buffer.
*/
@inline
protected _writeFour(inst: T, a: f64, b: f64, c: f64, d: f64): void {
var buff = changetype<usize>(this._buffer);
var index: i32 = this._offset;
var next: i32 = index + 6;
STORE<f64>(buff, index, <f64>inst);
STORE<f64>(buff, index + 1, <f64>next);
STORE<f64>(buff, index + 2, a);
STORE<f64>(buff, index + 3, b);
STORE<f64>(buff, index + 4, c);
STORE<f64>(buff, index + 5, d);
this._offset = next;
}
/**
* Write a single instruction to the buffer with five parameters. This results in seven values
* written to the buffer.
*
* @param {T} inst - The instruction type to be written to the buffer.
* @param {f64} a - The first parameter for the instruction to be written to the buffer.
* @param {f64} b - The second parameter for the instruction to be written to the buffer.
* @param {f64} c - The third parameter for the instruction to be written to the buffer.
* @param {f64} d - The fourth parameter for the instruction to be written to the buffer.
* @param {f64} d - The fifth parameter for the instruction to be written to the buffer.
*/
@inline
protected _writeFive(inst: T, a: f64, b: f64, c: f64, d: f64, e: f64): void {
var buff = changetype<usize>(this._buffer);
var index: i32 = this._offset;
var next: i32 = index + 7;
STORE<f64>(buff, index, <f64>inst);
STORE<f64>(buff, index + 1, <f64>next);
STORE<f64>(buff, index + 2, a);
STORE<f64>(buff, index + 3, b);
STORE<f64>(buff, index + 4, c);
STORE<f64>(buff, index + 5, d);
STORE<f64>(buff, index + 6, e);
this._offset = next;
}
/**
* Write a single instruction to the buffer with six parameters. This results in eight values
* written to the buffer.
*
* @param {T} inst - The instruction type to be written to the buffer.
* @param {f64} a - The first parameter for the instruction to be written to the buffer.
* @param {f64} b - The second parameter for the instruction to be written to the buffer.
* @param {f64} c - The third parameter for the instruction to be written to the buffer.
* @param {f64} d - The fourth parameter for the instruction to be written to the buffer.
* @param {f64} e - The fifth parameter for the instruction to be written to the buffer.
* @param {f64} f - The sixth parameter for the instruction to be written to the buffer.
*/
@inline
protected _writeSix(inst: T, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64): void {
var buff = changetype<usize>(this._buffer);
var index: i32 = this._offset;
var next: i32 = index + 8;
STORE<f64>(buff, index, <f64>inst);
STORE<f64>(buff, index + 1, <f64>next);
STORE<f64>(buff, index + 2, a);
STORE<f64>(buff, index + 3, b);
STORE<f64>(buff, index + 4, c);
STORE<f64>(buff, index + 5, d);
STORE<f64>(buff, index + 6, e);
STORE<f64>(buff, index + 7, f);
this._offset = next;
}
/**
* Write a single instruction to the buffer with eight parameters. This results in ten values
* written to the buffer.
*
* @param {T} inst - The instruction type to be written to the buffer.
* @param {f64} a - The first parameter for the instruction to be written to the buffer.
* @param {f64} b - The second parameter for the instruction to be written to the buffer.
* @param {f64} c - The third parameter for the instruction to be written to the buffer.
* @param {f64} d - The fourth parameter for the instruction to be written to the buffer.
* @param {f64} e - The fifth parameter for the instruction to be written to the buffer.
* @param {f64} f - The sixth parameter for the instruction to be written to the buffer.
* @param {f64} g - The seventh parameter for the instruction to be written to the buffer.
* @param {f64} h - The eighth parameter for the instruction to be written to the buffer.
*/
@inline
protected _writeEight(inst: T, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64, g: f64, h: f64): void {
var buff = changetype<usize>(this._buffer);
var index: i32 = this._offset;
var next: i32 = index + 10;
STORE<f64>(buff, index, <f64>inst);
STORE<f64>(buff, index + 1, <f64>next);
STORE<f64>(buff, index + 2, a);
STORE<f64>(buff, index + 3, b);
STORE<f64>(buff, index + 4, c);
STORE<f64>(buff, index + 5, d);
STORE<f64>(buff, index + 6, e);
STORE<f64>(buff, index + 7, f);
STORE<f64>(buff, index + 8, g);
STORE<f64>(buff, index + 9, h);
this._offset = next;
}
/**
* Write a single instruction to the buffer with nine parameters. This results in eleven values
* written to the buffer.
*
* @param {T} inst - The instruction type to be written to the buffer.
* @param {f64} a - The first parameter for the instruction to be written to the buffer.
* @param {f64} b - The second parameter for the instruction to be written to the buffer.
* @param {f64} c - The third parameter for the instruction to be written to the buffer.
* @param {f64} d - The fourth parameter for the instruction to be written to the buffer.
* @param {f64} e - The fifth parameter for the instruction to be written to the buffer.
* @param {f64} f - The sixth parameter for the instruction to be written to the buffer.
* @param {f64} g - The seventh parameter for the instruction to be written to the buffer.
* @param {f64} h - The eighth parameter for the instruction to be written to the buffer.
* @param {f64} i - The ninth parameter for the instruction to be written to the buffer.
*/
@inline
protected _writeNine(inst: T, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64, g: f64, h: f64, i: f64): void {
var buff = changetype<usize>(this._buffer);
var index: i32 = this._offset;
var next: i32 = index + 11;
STORE<f64>(buff, index, <f64>inst);
STORE<f64>(buff, index + 1, <f64>next);
STORE<f64>(buff, index + 2, a);
STORE<f64>(buff, index + 3, b);
STORE<f64>(buff, index + 4, c);
STORE<f64>(buff, index + 5, d);
STORE<f64>(buff, index + 6, e);
STORE<f64>(buff, index + 7, f);
STORE<f64>(buff, index + 8, g);
STORE<f64>(buff, index + 9, h);
STORE<f64>(buff, index + 10, i);
this._offset = next;
}
/**
* Reset the buffer back to position 0.
*/
@inline
protected _resetBuffer(): void {
this._offset = 0;
let length = this._retainedOffset;
let pointer = changetype<usize>(this._retained);
for (let i = 0; i < length; i++) {
__release(load<usize>(pointer + (<usize>i << alignof<usize>())));
}
// all the pointers are released
this._retainedOffset = 0;
}
/**
* Retain a pointer in the buffer for later use.
*
* @param {usize} pointer - The pointer to be retained and released after the buffer is reset.
*/
protected _retain(pointer: usize): void {
__retain(pointer);
var retained = changetype<usize>(this._retained);
var index = this._retainedOffset;
store<usize>(retained + (index << alignof<usize>()), pointer);
this._retainedOffset = index + 1;
}
} | the_stack |
import { expect } from './spec-helper';
import {
init,
Vector2 as vec2,
Vector3 as vec3,
Vector4 as vec4,
Matrix2 as mat2,
Matrix2d as mat2d,
Matrix3 as mat3,
Matrix4 as mat4,
Quaternion as quat,
Quaternion2 as quat2,
} from '../pkg/gl_matrix_wasm';
describe("quat2", function() {
let out, outVec, quat2A, quat2B, result, resultVec, outQuat;
let matrixA, matOut, quatOut;
let vec, ax;
before(done => {
init().then(() => done());
});
beforeEach(function() {
quat2A = quat2.fromValues(1, 2, 3, 4, 2, 5, 6, -2);
quat2B = quat2.fromValues(5, 6, 7, 8, 9, 8, 6, -4);
out= quat2.fromValues(0, 0, 0, 0, 0, 0, 0, 0);
outVec= vec3.fromValues(0, 0, 0);
outQuat= quat.fromValues(0, 0, 0, 0);
vec = vec3.fromValues(1, 1, -1);
});
describe("translate", function() {
beforeEach(function() {
matrixA = mat4.create(), matOut = mat4.create(), quatOut = quat2.create();
//quat2A only seems to work when created using this function?
quat2.fromRotationTranslation(quat2A, quat.fromValues(1,2,3,4), vec3.fromValues(-5, 4, 10));
quat2.normalize(quat2A, quat2A);
quat2.copy(quat2B, quat2A);
mat4.fromQuat2(matrixA, quat2A);
});
describe("with a separate output quaternion", function() {
beforeEach(function() {
result = quat2.translate(out, quat2A, vec);
//Same thing with a matrix
mat4.translate(matOut, matrixA, vec);
quat2.fromMat4(quatOut, matOut);
});
it("should place values into out", function() { expect(out).toBeEqualishQuat2(quatOut); });
it("should not modify quat2A", function() {
expect(quat2A).toBeEqualishQuat2(quat2B);
});
it("should not modify vec", function() { expect(vec).toBeEqualish([1,1,-1]); });
});
describe("when quat2A is the output quaternion", function() {
beforeEach(function() {
result = quat2.translate(quat2A, quat2A, vec);
//Same thing with a matrix
mat4.translate(matOut, matrixA, vec);
quat2.fromMat4(quatOut, matOut);
});
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2(quatOut); });
});
});
describe("rotateAroundAxis", function() {
beforeEach(function() {
matrixA = mat4.create(), matOut = mat4.create(), ax = vec3.fromValues(1,4,2);
//quat2A only seems to work when created using this function?
quat2.fromRotationTranslation(quat2A, quat.fromValues(1,2,3,4), vec3.fromValues(-5, 4, 10));
quat2.normalize(quat2A, quat2A);
mat4.fromQuat2(matrixA, quat2A);
});
describe("with a separate output quaternion", function() {
beforeEach(function() {
result = quat2.rotateAroundAxis(out, quat2A, ax, 5);
//Same thing with a matrix
mat4.rotate(matOut, matrixA, 5, ax);
quat2.fromMat4(quat2B, matOut);
});
it("should place values into out", function() { expect(out).toBeEqualishQuat2(quat2B); });
it("should not modify quat2A", function() {
expect(quat2A).toBeEqualishQuat2(
[0.18257418583505536, 0.3651483716701107, 0.5477225575051661, 0.7302967433402214,
-2.556038601690775, 3.742770809618635, 2.37346441585572, -3.0124740662784135]
); });
it("should not modify ax", function() { expect(ax).toBeEqualish([1, 4, 2]); });
});
describe("when quat2A is the output quaternion", function() {
beforeEach(function() {
result = quat2.rotateAroundAxis(quat2A, quat2A, ax, 5);
//Same thing with a matrix
mat4.rotate(matOut, matrixA, 5, ax);
quat2.fromMat4(quat2B, matOut);
});
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2(quat2B); });
it("should not modify ax", function() { expect(ax).toBeEqualish([1, 4, 2]); });
});
});
describe("rotateByQuatAppend", function() {
let correctResult;
let rotationQuat;
beforeEach(function() {
correctResult = quat2.create();
rotationQuat = quat2.create();
rotationQuat[0] = 2;
rotationQuat[1] = 5;
rotationQuat[2] = 2;
rotationQuat[3] = -10;
quat2.multiply(correctResult, quat2A, rotationQuat);
})
describe("with a separate output quaternion", function() {
beforeEach(function() {
result = quat2.rotateByQuatAppend(out, quat2A, quat.fromValues(2, 5, 2, -10));
});
it("should place values into out", function() { expect(out).toBeEqualishQuat2(correctResult); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
it("should not modify the rotation quaternion", function() { expect(rotationQuat).toBeEqualishQuat2([2,5,2,-10,0,0,0,0]); });
});
describe("when quat2A is the output quaternion", function() {
beforeEach(function() { result = quat2.rotateByQuatAppend(quat2A, quat2A, quat.fromValues(2, 5, 2, -10)); });
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2(correctResult); });
it("should not modify the rotation quaternion", function() { expect(rotationQuat).toBeEqualishQuat2([2,5,2,-10,0,0,0,0]); });
});
});
describe("rotateByQuatPrepend", function() {
let correctResult;
let rotationQuat;
beforeEach(function() {
correctResult = quat2.create();
rotationQuat = quat2.create();
rotationQuat[0] = 2;
rotationQuat[1] = 5;
rotationQuat[2] = 2;
rotationQuat[3] = -10;
quat2.multiply(correctResult, rotationQuat, quat2A);
})
describe("with a separate output quaternion", function() {
beforeEach(function() {
quat2.getReal(outQuat, rotationQuat);
result = quat2.rotateByQuatPrepend(out, outQuat, quat2A);
});
it("should place values into out", function() { expect(out).toBeEqualishQuat2(correctResult); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
it("should not modify the rotation quaternion", function() { expect(rotationQuat).toBeEqualishQuat2([2,5,2,-10,0,0,0,0]); });
});
describe("when quat2A is the output quaternion", function() {
beforeEach(function() {
quat2.getReal(outQuat, rotationQuat);
result = quat2.rotateByQuatPrepend(quat2A, outQuat, quat2A);
});
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2(correctResult); });
it("should not modify the rotation quaternion", function() { expect(rotationQuat).toBeEqualishQuat2([2,5,2,-10,0,0,0,0]); });
});
});
describe("rotateX", function() {
beforeEach(function() {
matrixA = mat4.create(), matOut = mat4.create(), quatOut = quat2.create();
//quat2A only seems to work when created using this function?
quat2.fromRotationTranslation(quat2A, quat.fromValues(1,2,3,4), vec3.fromValues(-5, 4, 10));
quat2.normalize(quat2A, quat2A);
quat2.copy(quat2B, quat2A);
mat4.fromQuat2(matrixA, quat2A);
});
describe("with a separate output quaternion", function() {
beforeEach(function() {
result = quat2.rotateX(out, quat2A, 5);
//Same thing with a matrix
mat4.rotateX(matOut, matrixA, 5);
quat2.fromMat4(quatOut, matOut);
});
it("should place values into out", function() { expect(out).toBeEqualishQuat2(quatOut); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2(quat2B); });
});
describe("when quat2A is the output quaternion", function() {
beforeEach(function() {
result = quat2.rotateX(quat2A, quat2A, 5);
//Same thing with a matrix
mat4.rotateX(matOut, matrixA, 5);
quat2.fromMat4(quatOut, matOut);
});
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2(quatOut); });
});
});
describe("rotateY", function() {
beforeEach(function() {
matrixA = mat4.create(), matOut = mat4.create(), quatOut = quat2.create();
//quat2A only seems to work when created using this function?
quat2.fromRotationTranslation(quat2A, quat.fromValues(1,2,3,4), vec3.fromValues(5, 4, -10));
quat2.normalize(quat2A, quat2A);
quat2.copy(quat2B, quat2A);
mat4.fromQuat2(matrixA, quat2A);
});
describe("with a separate output quaternion", function() {
beforeEach(function() {
result = quat2.rotateY(out, quat2A, -2);
//Same thing with a matrix
mat4.rotateY(matOut, matrixA, -2);
quat2.fromMat4(quatOut, matOut);
});
it("should place values into out", function() { expect(out).toBeEqualishQuat2(quatOut); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2(quat2B); });
});
describe("when quat2A is the output quaternion", function() {
beforeEach(function() {
result = quat2.rotateY(quat2A, quat2A, -2);
//Same thing with a matrix
mat4.rotateY(matOut, matrixA, -2);
quat2.fromMat4(quatOut, matOut);
});
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2(quatOut); });
});
});
describe("rotateZ", function() {
beforeEach(function() {
matrixA = mat4.create(), matOut = mat4.create(), quatOut = quat2.create();
//quat2A only seems to work when created using this function?
quat2.fromRotationTranslation(quat2A, quat.fromValues(1,0,3,-4), vec3.fromValues(0, -4, -10));
quat2.normalize(quat2A, quat2A);
quat2.copy(quat2B, quat2A);
mat4.fromQuat2(matrixA, quat2A);
});
describe("with a separate output quaternion", function() {
beforeEach(function() {
result = quat2.rotateZ(out, quat2A, 1);
//Same thing with a matrix
mat4.rotateZ(matOut, matrixA, 1);
quat2.fromMat4(quatOut, matOut);
});
it("should place values into out", function() { expect(out).toBeEqualishQuat2(quatOut); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2(quat2B); });
});
describe("when quat2A is the output quaternion", function() {
beforeEach(function() {
result = quat2.rotateZ(quat2A, quat2A, 1);
//Same thing with a matrix
mat4.rotateZ(matOut, matrixA, 1);
quat2.fromMat4(quatOut, matOut);
});
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2(quatOut); });
});
});
describe("from/toMat4", function() {
let matRes, matOut;
let rotationQuat;
describe("quat to matrix and back", function() {
beforeEach(function() {
matRes = mat4.create(), matOut = mat4.create();
rotationQuat = quat.create();
quat.normalize(rotationQuat, quat.fromValues(1,2,3,4));
quat2.fromRotationTranslation(quat2A, rotationQuat, vec3.fromValues(1,-5,3));
mat4.fromQuat2(matOut, quat2A);
result = quat2.fromMat4(out, matOut);
});
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([0.18257418, 0.36514836, 0.54772257, 0.73029673, -1.5518806, -1.82574184, 1.73445473, 0 ]); });
it("should be equal to the starting dual quat", function() {
expect(quat2A).toBeEqualishQuat2(out);
});
});
});
describe("create", function() {
beforeEach(function() { result = quat2.create(); });
it("should return 2 4 element arrays initialized to an identity dual quaternion", function() { expect(result).toBeEqualishQuat2([0, 0, 0, 1, 0, 0, 0, 0]); });
});
describe("clone", function() {
beforeEach(function() { result = quat2.clone(quat2A); });
it("should return 2 4 element arrays initialized to the values in quat2A", function() { expect(result).toBeEqualishQuat2(quat2A); });
});
describe("fromValues", function() {
beforeEach(function() { result = quat2.fromValues(1, 2, 3, 4, 5, 7, 8, -2); });
it("should return 2 4 element arrays initialized to the values passedd to the values passed", function() {
expect(result).toBeEqualishQuat2([1, 2, 3, 4, 5, 7, 8, -2]);
});
});
describe("copy", function() {
beforeEach(function() { result = quat2.copy(out, quat2A); });
it("should place values into out", function() { expect(out).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
});
describe("set", function() {
beforeEach(function() { result = quat2.set(out, 1, 2, 3, 4, 2, 5, 6, -2); });
it("should place values into out", function() { expect(out).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
});
describe("identity", function() {
beforeEach(function() { result = quat2.identity(out); });
it("should place values into out", function() { expect(out).toBeEqualishQuat2([0, 0, 0, 1, 0, 0, 0, 0]); });
});
describe("add", function() {
describe("with a separate output dual quaternion", function() {
beforeEach(function() { result = quat2.add(out, quat2A, quat2B); });
it("should place values into out", function() { expect(out).toBeEqualishQuat2([6, 8, 10, 12, 11, 13, 12, -6]); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
it("should not modify quat2B", function() { expect(quat2B).toBeEqualishQuat2([5, 6, 7, 8, 9, 8, 6, -4]); });
});
describe("when quat2A is the output dual quaternion", function() {
beforeEach(function() { result = quat2.add(quat2A, quat2A, quat2B); });
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2([6, 8, 10, 12, 11, 13, 12, -6]); });
it("should not modify quat2B", function() { expect(quat2B).toBeEqualishQuat2([5, 6, 7, 8, 9, 8, 6, -4])});
});
describe("when quat2B is the output dual quaternion", function() {
beforeEach(function() { result = quat2.add(quat2B, quat2A, quat2B); });
it("should place values into quat2B", function() { expect(quat2B).toBeEqualishQuat2([6, 8, 10, 12, 11, 13, 12, -6]); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
});
});
describe("multiply", function() {
describe("with a separate output quaternion", function() {
beforeEach(function() { result = quat2.multiply(out, quat2A, quat2B); });
it("should place values into out", function() { expect(out).toBeEqualishQuat2([24, 48, 48, -6, 25, 89, 23, -157 ]); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
it("should not modify quat2B", function() { expect(quat2B).toBeEqualishQuat2([5, 6, 7, 8, 9, 8, 6, -4]); });
});
describe("when quat2A is the output quaternion", function() {
beforeEach(function() { result = quat2.multiply(quat2A, quat2A, quat2B); });
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2([24, 48, 48, -6, 25, 89, 23, -157 ]); });
it("should not modify quat2B", function() { expect(quat2B).toBeEqualishQuat2([5, 6, 7, 8, 9, 8, 6, -4]); });
});
describe("when quat2B is the output quaternion", function() {
beforeEach(function() { result = quat2.multiply(quat2B, quat2A, quat2B); });
it("should place values into quat2B", function() { expect(quat2B).toBeEqualishQuat2([24, 48, 48, -6, 25, 89, 23, -157 ]); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
});
describe("same as matrix multiplication", function() {
let matrixA, matrixB;
let matOut, quatOut;
beforeEach(function() {
matrixA = mat4.create(), matrixB = mat4.create();
matOut = mat4.create(), quatOut = quat2.create();
//quat2A and quat2B only seem to work when created using this function?
quat2.fromRotationTranslation(quat2A, quat.fromValues(1,2,3,4), vec3.fromValues(-5, 4, 10));
quat2.normalize(quat2A, quat2A);
mat4.fromQuat2(matrixA, quat2A);
quat2.fromRotationTranslation(quat2B, quat.fromValues(5, 6, 7, 8), vec3.fromValues(9, 8, 6));
quat2.normalize(quat2B, quat2B);
mat4.fromQuat2(matrixB, quat2B);
});
it("the matrices should be equal to the dual quaternions", function() {
let testQuat = quat2.create();
quat2.fromMat4(testQuat, matrixA);
expect(testQuat).toBeEqualishQuat2(quat2A);
quat2.fromMat4(testQuat, matrixB);
expect(testQuat).toBeEqualishQuat2(quat2B);
});
it("should be equal to the matrix multiplication", function() {
quat2.multiply(out, quat2A, quat2B);
mat4.mul(matOut, matrixA, matrixB);
quat2.fromMat4(quatOut, matOut);
expect(out).toBeEqualishQuat2(quatOut);
});
});
});
describe("scale", function() {
describe("with a separate output dual quaternion", function() {
beforeEach(function() { result = quat2.scale(out, quat2A, 2); });
it("should place values into out", function() { expect(out).toBeEqualishQuat2([2, 4, 6, 8, 4, 10, 12, -4]); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
});
describe("when quat2A is the output dual quaternion", function() {
beforeEach(function() { result = quat2.scale(quat2A, quat2A, 2); });
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2([2, 4, 6, 8, 4, 10, 12, -4]); });
});
});
describe("length", function() {
beforeEach(function() { result = quat2.len(quat2A); });
it("should return the length", function() { expect(result).toBeEqualish(5.477225); });
});
describe("squaredLength", function() {
beforeEach(function() { result = quat2.squaredLength(quat2A); });
it("should return the squared length", function() { expect(result).toEqual(30); });
});
describe("fromRotation", function() {
beforeEach(function() { result = quat2.fromRotation(out, quat.fromValues(1, 2, 3, 4)); });
it("should place values into out", function() { expect(out).toBeEqualishQuat2([1, 2, 3, 4, 0, 0, 0, 0]); });
it("should not modify the quaternion", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
});
describe("fromTranslation", function(){
beforeEach(function() { vec = vec3.fromValues(1, 2, 3); result = quat2.fromTranslation(out, vec); });
it("should place values into out", function() { expect(out).toBeEqualishQuat2([0, 0, 0, 1, 0.5, 1, 1.5, 0]); });
it("should not modify the vector", function() { expect(vec).toBeEqualish([1, 2, 3]); });
});
describe("fromRotationTranslation", function() {
beforeEach(function() {
vec = vec3.fromValues(1, 2, 3);
result = quat2.fromRotationTranslation(out, quat.fromValues(1, 2, 3, 4), vec);
});
it("should place values into out", function() { expect(out).toBeEqualishQuat2([1, 2, 3, 4, 2, 4, 6, -7]); });
it("should not modify the quaternion", function() {quat2.getReal(outQuat, quat2A); expect(outQuat).toBeEqualish([1, 2, 3, 4]); });
it("should not modify the vector", function() { expect(vec).toBeEqualish([1, 2, 3]); });
it("should have a translation that can be retrieved with getTranslation", function() {
let t = vec3.fromValues(0, 0, 0);
quat2.normalize(out, out);
quat2.getTranslation(t, out);
expect(t).toBeEqualish([1, 2, 3]);
});
});
describe("fromRotationTranslationValues", function() {
beforeEach(function() { result = quat2.fromRotationTranslationValues(1,2,3,4, 1,2,3); });
it("should return the correct result", function() { expect(result).toBeEqualishQuat2([1, 2, 3, 4, 2, 4, 6, -7]); });
it("should have a translation that can be retrieved with getTranslation", function() {
let t = vec3.fromValues(0, 0, 0);
quat2.normalize(result, result);
quat2.getTranslation(t, result);
expect(t).toBeEqualish([1, 2, 3]);
});
});
describe("getTranslation", function() {
describe("without a real part", function() {
beforeEach(function() {
quat2.fromTranslation(out, vec3.fromValues(1,2,3));
resultVec = quat2.getTranslation(outVec, out);
});
describe("not normalized", function() {
it("should return the same translation value", function() {
expect(outVec).toBeEqualish([1, 2, 3]);
});
});
describe("normalized", function() {
it("should return the same translation value", function() {
quat2.normalize(out, out);
quat2.getTranslation(outVec, out);
expect(outVec).toBeEqualish([1, 2, 3]);
});
});
});
describe("with a real part", function() {
beforeEach(function() {
quat2.fromRotationTranslation(out, quat.fromValues(2, 4, 6, 2), vec3.fromValues(1, 2, 3));
resultVec = quat2.getTranslation(outVec, out);
});
describe("not normalized", function() {
it("should not return the same translation value", function() {
expect(outVec).not.toBeEqualish([1, 2, 3]);
});
});
describe("normalized", function() {
it("should return the same translation value", function() {
quat2.normalize(out, out);
quat2.getTranslation(outVec, out);
expect(outVec).toBeEqualish([1, 2, 3]);
});
});
});
});
describe("normalize", function() {
describe("when it is normalizing quat2A", function() {
beforeEach(function() {
quat2A = quat2.fromValues(1, 2, 3, 4, 2, 5, 6, -2);
quat2.normalize(out, quat2A);
});
it("both parts should have been normalized", function() { expect(out).toBeEqualishQuat2([1/5.4772255, 2/5.4772255, 3/5.4772255, 4/5.4772255, 0.231260, 0.6450954, 0.693781,-0.9006993]); });
});
beforeEach(function() { quat2A = quat2.fromValues(5, 0, 0, 0, 0, 0, 0, 0); });
describe("with a separate output quaternion", function() {
beforeEach(function() { result = quat2.normalize(out, quat2A); });
it("should place values into out", function() { expect(out).toBeEqualishQuat2([1, 0, 0, 0, 0, 0, 0, 0]); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([5, 0, 0, 0, 0, 0, 0, 0]); });
});
describe("when quat2A is the output quaternion", function() {
beforeEach(function() { result = quat2.normalize(quat2A, quat2A); });
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 0, 0, 0, 0, 0, 0, 0]); });
});
describe("when it contains a translation", function() {
beforeEach(function() {
quat2.set(out, 5, 0, 0, 0, 1, 2, 3, 5);
quat2.normalize(out, out);
});
it("both parts should have been normalized", function() { expect(out).toBeEqualishQuat2([1, 0, 0, 0, 0, 0.4, 0.6, 1]); });
});
});
describe("lerp", function() {
describe("with a separate output quaternion", function() {
beforeEach(function() { result = quat2.lerp(out, quat2A, quat2B, 0.7); });
it("should place values into out", function() { expect(out).toBeEqualishQuat2([3.8, 4.8, 5.8, 6.8, 6.9, 7.1, 6.0, -3.4]); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
it("should not modify quat2B", function() { expect(quat2B).toBeEqualishQuat2([5, 6, 7, 8, 9, 8, 6, -4]); });
});
describe("when quat2A is the output quaternion", function() {
beforeEach(function() { result = quat2.lerp(quat2A, quat2A, quat2B, 0.5); });
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2([3, 4, 5, 6,5.5, 6.5, 6, -3]); });
it("should not modify quat2B", function() { expect(quat2B).toBeEqualishQuat2([5, 6, 7, 8, 9, 8, 6, -4]); });
});
describe("when quat2B is the output quaternion", function() {
beforeEach(function() { result = quat2.lerp(quat2B, quat2A, quat2B, 0.5); });
it("should place values into quat2B", function() { expect(quat2B).toBeEqualishQuat2([3, 4, 5, 6,5.5, 6.5, 6, -3]); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
});
describe("shortest path", function() {
beforeEach(function() { result = quat2.lerp(out, quat2.fromValues(1, 2, 3, -4, 2, 5, 6, -2), quat2.fromValues(5, -6, 7, 8, 9, 8, 6, -4), 0.4); });
it("should pick the shorter path", function() { expect(out).toBeEqualishQuat2([ -1.4, 3.6, -1, -5.6, -2.4, -0.2, 1.2, 0.4 ]); });
});
});
describe("dot", function() {
describe("with a separate output dual quaternion", function() {
beforeEach(function() { result = quat2.dot(quat2A, quat2B); });
it("should return the dot product", function() { expect(result).toBeEqualish(70); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
it("should not modify quat2B", function() { expect(quat2B).toBeEqualishQuat2([5, 6, 7, 8, 9, 8, 6, -4]); });
});
});
describe("invert", function() {
describe("with a separate output dual quaternion", function() {
beforeEach(function() { result = quat2.invert(out, quat2A); });
it("should place values into out", function() { expect(out).toBeEqualishQuat2([-0.0333333333, -0.06666666666, -0.1, 0.13333333333, -2/30, -5/30, -6/30, -2/30]); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
it("the real part should be equal to a inverted quaternion", function() {
quat.invert(outQuat, quat.fromValues(1, 2, 3, 4));
quat2.getReal(outQuat, out);
expect(outQuat).toBeEqualish(outQuat);
});
});
describe("when quat2A is the output quaternion", function() {
beforeEach(function() { result = quat2.invert(quat2A, quat2A); });
it("should place values into quat2A", function() { expect(quat2A).toBeEqualish([-0.0333333333, -0.06666666666, -0.1, 0.13333333333, -2/30, -5/30, -6/30, -2/30]); });
});
});
describe("get real/dual", function() {
describe("get real", function() {
beforeEach(function() { result = quat2.getReal(outQuat, quat2A); });
it("should place values into out", function() { expect(outQuat).toBeEqualish([1, 2, 3, 4]); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
});
describe("get dual", function() {
beforeEach(function() { result = quat2.getDual(outQuat, quat2A); });
it("should place values into out", function() { expect(outQuat).toBeEqualish([2, 5, 6, -2]); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
});
});
describe("set real/dual", function() {
describe("set real", function() {
beforeEach(function() {
outQuat= quat.fromValues(4, 6, 8, -100);
result = quat2.setReal(quat2A, outQuat);
});
it("should place values into out", function() { expect(quat2A).toBeEqualishQuat2([4, 6, 8, -100, 2, 5, 6, -2]); });
it("should not modify outQuat", function() { expect(outQuat).toBeEqualish([4, 6, 8, -100]); });
});
describe("set dual", function() {
beforeEach(function() {
outQuat= quat.fromValues(4.3, 6, 8, -100);
result = quat2.setDual(quat2A, outQuat);
});
it("should place values into out", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 4.3, 6, 8, -100]); });
it("should not modify outQuat", function() { expect(outQuat).toBeEqualish([4.3, 6, 8, -100]); });
});
});
describe("conjugate", function() {
describe("with a separate output dual quaternion", function() {
beforeEach(function() { result = quat2.conjugate(out, quat2A); });
it("should place values into out", function() { expect(out).toBeEqualishQuat2([-1, -2, -3, 4, -2, -5, -6, -2]); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([1, 2, 3, 4, 2, 5, 6, -2]); });
});
describe("when quat2A is the output dual quaternion", function() {
beforeEach(function() { result = quat2.conjugate(quat2A, quat2A); });
it("should place values into quat2A", function() { expect(quat2A).toBeEqualishQuat2([-1, -2, -3, 4, -2, -5, -6, -2]); });
});
});
describe("exactEquals", function() {
let quat2C, r0, r1;
beforeEach(function() {
quat2A = quat2.fromValues(0, 1, 2, 3, 4, 5, 6, 7);
quat2B = quat2.fromValues(0, 1, 2, 3, 4, 5, 6, 7);
quat2C = quat2.fromValues(1, 2, 3, 4, 5, 6, 7, 8);
r0 = quat2.exactEquals(quat2A, quat2B);
r1 = quat2.exactEquals(quat2A, quat2C);
});
it("should return true for identical quaternions", function() { expect(r0).toBe(true); });
it("should return false for different quaternions", function() { expect(r1).toBe(false); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([0, 1, 2, 3, 4, 5, 6, 7]); });
it("should not modify quat2B", function() { expect(quat2B).toBeEqualishQuat2([0, 1, 2, 3, 4, 5, 6, 7]); });
});
describe("equals", function() {
let quat2C, quat2D, r0, r1, r2;
beforeEach(function() {
quat2A = quat2.fromValues(0, 1, 2, 3, 4, 5, 6, 7);
quat2B = quat2.fromValues(0, 1, 2, 3, 4, 5, 6, 7);
quat2C = quat2.fromValues(1, 2, 3, 4, 5, 6, 7, 8);
quat2D = quat2.fromValues(1e-16, 1, 2, 3, 4, 5, 6, 7);
r0 = quat2.equals(quat2A, quat2B);
r1 = quat2.equals(quat2A, quat2C);
r2 = quat2.equals(quat2A, quat2D);
});
it("should return true for identical dual quaternions", function() { expect(r0).toBe(true); });
it("should return false for different dual quaternions", function() { expect(r1).toBe(false); });
it("should return true for close but not identical quaternions", function() { expect(r2).toBe(true); });
it("should not modify quat2A", function() { expect(quat2A).toBeEqualishQuat2([0, 1, 2, 3, 4, 5, 6, 7]); });
it("should not modify quat2B", function() { expect(quat2B).toBeEqualishQuat2([0, 1, 2, 3, 4, 5, 6, 7]); });
});
}); | the_stack |
import { TypeInference as ti } from "./type_inference";
import { Myna as m } from "./node_modules/myna-parser/myna";
var verbose = false;
// Defines syntax parsers for type expressions and a simple lambda calculus
function registerGrammars()
{
// A simple grammar for parsing type expressions
var typeGrammar = new function()
{
var _this = this;
this.typeExprRec = m.delay(() => { return _this.typeExpr});
this.typeList = m.guardedSeq('(', m.ws, this.typeExprRec.ws.zeroOrMore, ')').ast;
this.typeVar = m.guardedSeq("'", m.identifier).ast;
this.typeConstant = m.identifier.or(m.digits).or("->").or("*").or("[]").ast;
this.typeExpr = m.choice(this.typeList, this.typeVar, this.typeConstant).ast;
}
m.registerGrammar('type', typeGrammar, typeGrammar.typeExpr);
// A simple grammar for parsing the lambda calculus
var lambdaGrammar = new function()
{
var _this = this;
this.recExpr = m.delay(() => _this.expr);
this.var = m.identifier.ast;
this.abstraction = m.guardedSeq("\\", this.var, ".").then(this.recExpr).ast;
this.parenExpr = m.guardedSeq("(", this.recExpr, ")").ast;
this.expr = m.choice(this.parenExpr, this.abstraction, this.var).then(m.ws).oneOrMore.ast;
}
m.registerGrammar('lambda', lambdaGrammar, lambdaGrammar.expr);
}
registerGrammars();
var typeParser = m.parsers['type'];
var lcParser = m.parsers['lambda'];
function runTest(f:() => any, testName:string, expectFail:boolean = false) {
try {
console.log("Running test: " + testName);
var result = f();
console.log("Result = " + result);
if (result && !expectFail || !result && expectFail) {
console.log("PASSED");
}
else {
console.log("FAILED");
}
}
catch (e) {
if (expectFail) {
console.log("PASSED: expected fail, error caught: " + e.message);
}
else {
console.log("FAILED: error caught: " + e.message);
}
}
}
function stringToType(input:string) : ti.Type {
var ast = typeParser(input);
if (ast.end != input.length)
throw new Error("Only part of input was consumed");
return astToType(ast);
}
function typeToString(t:ti.Type) : string {
if (t instanceof ti.TypeVariable)
return "'" + t.name;
else if (t instanceof ti.TypeArray)
return "(" + t.types.map(typeToString).join(" ") + ")";
else
return t.toString();
}
function astToType(ast) : ti.Type {
if (!ast)
return null;
switch (ast.name)
{
case "typeVar":
return ti.typeVariable(ast.allText.substr(1));
case "typeConstant":
return ti.typeConstant(ast.allText);
case "typeList":
return ti.typeArray(ast.children.map(astToType));
case "typeExpr":
if (ast.children.length != 1)
throw new Error("Expected only one child of node, not " + ast.children.length);
return astToType(ast.children[0]);
default:
throw new Error("Unrecognized type expression: " + ast.name);
}
}
function testParse(input:string, fail:boolean=false) {
runTest(() => stringToType(input), input, fail);
}
var coreTypes = {
apply : "((('a -> 'b) 'a) -> 'b)",
compose : "((('b -> 'c) (('a -> 'b) 'd)) -> (('a -> 'c) 'd))",
quote : "(('a 'b) -> (('c -> ('a 'c)) 'b))",
dup : "(('a 'b) -> ('a ('a 'b)))",
swap : "(('a ('b 'c)) -> ('b ('a 'c)))",
pop : "(('a 'b) -> 'b)",
};
var combinators = {
i : "\\x.x",
k : "\\x.\\y.x",
s : "\\x.\\y.\\z.x z (y z)",
b : "\\x.\\y.\\z.x (y z)",
c : "\\x.\\y.\\z.x y z",
w : "\\x.\\y.x y y",
m : "\\x.x x",
succ : "\\n.\\f.\\x.f (n f x)",
pred : "\\n.\\f.\\x.n (\\g.\\h.h (g f)) (\\u.x) (\\t.t)",
plus : "\\m.\\n.\\f.\\x.m f (n f x)",
mul : "\\m.\\n.\\f.m (n f)",
zero : "\\f.\\x.x",
one : "\\f.\\x.f x",
two : "\\f.\\x.f (f x)",
three : "\\f.\\x.f (f (f x))",
True : "\\x.\\y.x",
False : "\\x.\\y.y",
pair : "\\x.\\y.\\f.f x y",
first : "\\p.p \\x.\\y.x",
second : "\\p.p \\x.\\y.y",
nil : "\\a.\\x.\\y.x",
null : "\\p.p (\\a.\\b.\\x.\\y.y)",
};
function lambdaAstToType(ast:m.AstNode, engine:ti.ScopedTypeInferenceEngine) : ti.Type {
switch (ast.rule.name)
{
case "abstraction":
{
var arg = engine.introduceVariable(ast.children[0].allText);
var body = lambdaAstToType(ast.children[1], engine);
var fxn : ti.Type = ti.functionType(arg, body);
engine.popVariable();
return fxn;
}
case "parenExpr":
return lambdaAstToType(ast.children[0], engine);
case "var":
return engine.lookupVariable(ast.allText);
case "expr":
{
var r : ti.Type = lambdaAstToType(ast.children[0], engine);
for (var i=1; i < ast.children.length; ++i) {
var args = lambdaAstToType(ast.children[i], engine);
r = engine.applyFunction(r, args);
}
return r;
}
default:
throw new Error("Unrecognized ast rule " + ast.rule);
}
}
function stringToLambdaExprType(s:string) : ti.Type {
var e = new ti.ScopedTypeInferenceEngine();
var ast = lcParser(s);
if (ast.end != s.length)
throw new Error("Only part of input was consumed");
var t = lambdaAstToType(ast, e);
t = e.getUnifiedType(t);
t = ti.alphabetizeVarNames(t);
return t;
}
function testLambdaCalculus() {
for (var k in combinators) {
try {
var s = combinators[k];
var t = stringToLambdaExprType(s);
console.log(k + " = " + s + " : " + t);
}
catch (e) {
console.log("FAILED: " + k + " " + e);
}
}
}
function printCoreTypes() {
for (var k in coreTypes) {
var ts = coreTypes[k];
var t = stringToType(ts);
console.log(k);
console.log(ts);
console.log(t.toString());
}
}
function testForallInference() {
var data = {
apply : "!t1.(!t0.((t0 -> t1) t0) -> t1)",
compose : "!t1!t2!t3.(!t0.((t0 -> t1) ((t2 -> t0) t3)) -> ((t2 -> t1) t3))",
quote : "!t0!t1.((t0 t1) -> (!t2.(t2 -> (t0 t2)) t1))",
dup : "!t0!t1.((t0 t1) -> (t0 (t0 t1)))",
swap : "!t0!t1!t2.((t0 (t1 t2)) -> (t1 (t0 t2)))",
pop : "!t1.(!t0.(t0 t1) -> t1)",
};
for (var k in data) {
var expType = data[k];
var infType = ti.normalizeVarNames(stringToType(coreTypes[k]));
if (infType != expType)
console.log("FAILED: " + k + " + expected " + expType + " got " + infType);
else
console.log("PASSED: " + k);
}
}
function regressionTestComposition() {
var data = [
["apply apply", "!t2.(!t0.((t0 -> !t1.((t1 -> t2) t1)) t0) -> t2)"],
["apply compose", "!t2!t3!t4.(!t0.((t0 -> !t1.((t1 -> t2) ((t3 -> t1) t4))) t0) -> ((t3 -> t2) t4))"],
["apply quote", "!t1!t2.(!t0.((t0 -> (t1 t2)) t0) -> (!t3.(t3 -> (t1 t3)) t2))"],
["apply dup", "!t1!t2.(!t0.((t0 -> (t1 t2)) t0) -> (t1 (t1 t2)))"],
["apply swap", "!t1!t2!t3.(!t0.((t0 -> (t1 (t2 t3))) t0) -> (t2 (t1 t3)))"],
["apply pop", "!t2.(!t0.((t0 -> !t1.(t1 t2)) t0) -> t2)"],
["compose apply", "!t1.(!t0.((t0 -> t1) !t2.((t2 -> t0) t2)) -> t1)"],
["compose compose", "!t1!t3!t4.(!t0.((t0 -> t1) !t2.((t2 -> t0) ((t3 -> t2) t4))) -> ((t3 -> t1) t4))"],
["compose quote", "!t1!t2!t3.(!t0.((t0 -> t1) ((t2 -> t0) t3)) -> (!t4.(t4 -> ((t2 -> t1) t4)) t3))"],
["compose dup", "!t1!t2!t3.(!t0.((t0 -> t1) ((t2 -> t0) t3)) -> ((t2 -> t1) ((t2 -> t1) t3)))"],
["compose swap", "!t1!t2!t3!t4.(!t0.((t0 -> t1) ((t2 -> t0) (t3 t4))) -> (t3 ((t2 -> t1) t4)))"],
["compose pop", "!t3.(!t0.(!t1.(t0 -> t1) (!t2.(t2 -> t0) t3)) -> t3)"],
["quote apply", "!t0!t1.((t0 t1) -> (t0 t1))"],
["quote compose", "!t0!t1!t2!t3.((t0 ((t1 -> t2) t3)) -> ((t1 -> (t0 t2)) t3))"],
["quote quote", "!t0!t1.((t0 t1) -> (!t2.(t2 -> (!t3.(t3 -> (t0 t3)) t2)) t1))"],
["quote dup", "!t0!t1.((t0 t1) -> (!t2.(t2 -> (t0 t2)) (!t3.(t3 -> (t0 t3)) t1)))"],
["quote swap", "!t0!t1!t2.((t0 (t1 t2)) -> (t1 (!t3.(t3 -> (t0 t3)) t2)))"],
["quote pop", "!t1.(!t0.(t0 t1) -> t1)"],
["dup apply", "!t1.(!t0.((((rec 1) t0) -> t1) t0) -> t1)"],
["dup compose", "!t0!t1.(((t0 -> t0) t1) -> ((t0 -> t0) t1))"],
["dup quote", "!t0!t1.((t0 t1) -> (!t2.(t2 -> (t0 t2)) (t0 t1)))"],
["dup dup", "!t0!t1.((t0 t1) -> (t0 (t0 (t0 t1))))"],
["dup swap", "!t0!t1.((t0 t1) -> (t0 (t0 t1)))"],
["dup pop", "!t0!t1.((t0 t1) -> (t0 t1))"],
["swap apply", "!t2.(!t0.(t0 !t1.(((t0 t1) -> t2) t1)) -> t2)"],
["swap compose", "!t0!t2!t3.(!t1.((t0 -> t1) ((t1 -> t2) t3)) -> ((t0 -> t2) t3))"],
["swap quote", "!t0!t1!t2.((t0 (t1 t2)) -> (!t3.(t3 -> (t1 t3)) (t0 t2)))"],
["swap dup", "!t0!t1!t2.((t0 (t1 t2)) -> (t1 (t1 (t0 t2))))"],
["swap swap", "!t0!t1!t2.((t0 (t1 t2)) -> (t0 (t1 t2)))"],
["swap pop", "!t0!t2.((t0 !t1.(t1 t2)) -> (t0 t2))"],
["pop apply", "!t2.(!t0.(t0 !t1.((t1 -> t2) t1)) -> t2)"],
["pop compose", "!t2!t3!t4.(!t0.(t0 !t1.((t1 -> t2) ((t3 -> t1) t4))) -> ((t3 -> t2) t4))"],
["pop quote", "!t1!t2.(!t0.(t0 (t1 t2)) -> (!t3.(t3 -> (t1 t3)) t2))"],
["pop dup", "!t1!t2.(!t0.(t0 (t1 t2)) -> (t1 (t1 t2)))"],
["pop swap", "!t1!t2!t3.(!t0.(t0 (t1 (t2 t3))) -> (t2 (t1 t3)))"],
["pop pop", "!t2.(!t0.(t0 !t1.(t1 t2)) -> t2)"],
];
for (var xs of data) {
var ops = xs[0].split(" ");
var exp = xs[1];
var expr1 = stringToType(coreTypes[ops[0]]);
var expr2 = stringToType(coreTypes[ops[1]]);
var r = ti.composeFunctions(expr1 as ti.TypeArray, expr2 as ti.TypeArray);
r = ti.normalizeVarNames(r) as ti.TypeArray;
if (r.toString() != exp) {
console.log("FAILED: " + xs[0] + " + expected " + exp + " got " + r);
}
else {
console.log("PASSED: " + xs[0]);
}
}
}
printCoreTypes();
testLambdaCalculus();
testForallInference();
regressionTestComposition();
declare var process : any;
process.exit(); | the_stack |
import { GlobalProps } from 'ojs/ojvcomponent';
import { ComponentChildren } from 'preact';
import { DataProvider } from '../ojdataprovider';
import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojNBox<K, D extends ojNBox.Node<K> | any> extends dvtBaseComponent<ojNBoxSettableProperties<K, D>> {
animationOnDataChange?: 'auto' | 'none';
animationOnDisplay?: 'auto' | 'none';
as?: string;
cellContent?: 'counts' | 'auto';
cellMaximize?: 'off' | 'on';
cells?: Promise<ojNBox.Cell[]> | null;
columns: Promise<ojNBox.Column[]> | null;
columnsTitle?: string;
countLabel?: ((context: ojNBox.CountLabelContext) => (string | null));
data: DataProvider<K, D> | null;
groupAttributes?: 'color' | 'indicatorColor' | 'indicatorIconColor' | 'indicatorIconPattern' | 'indicatorIconShape';
groupBehavior?: 'acrossCells' | 'none' | 'withinCell';
hiddenCategories?: string[];
highlightMatch?: 'any' | 'all';
highlightedCategories?: string[];
hoverBehavior?: 'dim' | 'none';
labelTruncation?: 'ifRequired' | 'on';
maximizedColumn?: string;
maximizedRow?: string;
otherColor?: string;
otherThreshold?: number;
rows: Promise<ojNBox.Row[]> | null;
rowsTitle?: string;
selection?: K[];
selectionMode?: 'none' | 'single' | 'multiple';
styleDefaults?: {
animationDuration?: number;
cellDefaults?: {
labelHalign?: 'center' | 'end' | 'start';
labelStyle?: Partial<CSSStyleDeclaration>;
maximizedSvgStyle?: Partial<CSSStyleDeclaration>;
minimizedSvgStyle?: Partial<CSSStyleDeclaration>;
showCount?: 'on' | 'off' | 'auto';
svgStyle?: Partial<CSSStyleDeclaration>;
};
columnLabelStyle?: Partial<CSSStyleDeclaration>;
columnsTitleStyle?: Partial<CSSStyleDeclaration>;
hoverBehaviorDelay?: number;
nodeDefaults?: {
borderColor?: string;
borderWidth?: number;
color?: string;
iconDefaults?: {
background?: 'neutral' | 'red' | 'orange' | 'forest' | 'green' | 'teal' | 'blue' | 'slate' | 'pink' | 'mauve' | 'purple' | 'lilac' | 'gray' | string;
borderColor?: string;
borderRadius?: string;
borderWidth?: number;
color?: string;
height?: number;
opacity?: number;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' |
'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
shape?: 'circle' | 'ellipse' | 'square' | 'plus' | 'diamond' | 'triangleUp' | 'triangleDown' | 'human' | 'rectangle' | 'star' | string;
source?: string;
width?: number;
};
indicatorColor?: string;
indicatorIconDefaults?: {
borderColor?: string;
borderRadius?: string;
borderWidth?: number;
color?: string;
height?: number;
opacity?: number;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' |
'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
shape?: 'circle' | 'ellipse' | 'square' | 'plus' | 'diamond' | 'triangleUp' | 'triangleDown' | 'human' | 'rectangle' | 'star' | string;
source?: string;
width?: number;
};
labelStyle?: Partial<CSSStyleDeclaration>;
secondaryLabelStyle?: Partial<CSSStyleDeclaration>;
};
rowLabelStyle?: Partial<CSSStyleDeclaration>;
rowsTitleStyle?: Partial<CSSStyleDeclaration>;
};
tooltip?: {
renderer: ((context: ojNBox.TooltipContext<K>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
})) | null;
};
touchResponse?: 'touchStart' | 'auto';
translations: {
componentName?: string;
highlightedCount?: string;
labelAdditionalData?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelGroup?: string;
labelInvalidData?: string;
labelNoData?: string;
labelOther?: string;
labelSize?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
addEventListener<T extends keyof ojNBoxEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojNBoxEventMap<K, D>[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojNBoxSettableProperties<K, D>>(property: T): ojNBox<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojNBoxSettableProperties<K, D>>(property: T, value: ojNBoxSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojNBoxSettableProperties<K, D>>): void;
setProperties(properties: ojNBoxSettablePropertiesLenient<K, D>): void;
getContextByNode(node: Element): ojNBox.NodeContext<K> | ojNBox.CellContext | ojNBox.DialogContext | ojNBox.GroupNodeContext | null;
}
export namespace ojNBox {
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type cellContentChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["cellContent"]>;
// tslint:disable-next-line interface-over-type-literal
type cellMaximizeChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["cellMaximize"]>;
// tslint:disable-next-line interface-over-type-literal
type cellsChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["cells"]>;
// tslint:disable-next-line interface-over-type-literal
type columnsChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["columns"]>;
// tslint:disable-next-line interface-over-type-literal
type columnsTitleChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["columnsTitle"]>;
// tslint:disable-next-line interface-over-type-literal
type countLabelChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["countLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type groupAttributesChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["groupAttributes"]>;
// tslint:disable-next-line interface-over-type-literal
type groupBehaviorChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["groupBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type hiddenCategoriesChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["hiddenCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightMatchChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["highlightMatch"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightedCategoriesChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["highlightedCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["hoverBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type labelTruncationChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["labelTruncation"]>;
// tslint:disable-next-line interface-over-type-literal
type maximizedColumnChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["maximizedColumn"]>;
// tslint:disable-next-line interface-over-type-literal
type maximizedRowChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["maximizedRow"]>;
// tslint:disable-next-line interface-over-type-literal
type otherColorChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["otherColor"]>;
// tslint:disable-next-line interface-over-type-literal
type otherThresholdChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["otherThreshold"]>;
// tslint:disable-next-line interface-over-type-literal
type rowsChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["rows"]>;
// tslint:disable-next-line interface-over-type-literal
type rowsTitleChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["rowsTitle"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type styleDefaultsChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["styleDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type touchResponseChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["touchResponse"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends Node<K> | any> = dvtBaseComponent.trackResizeChanged<ojNBoxSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type Cell = {
column: string;
label?: string;
labelHalign?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
maximizedSvgClassName?: string;
maximizedSvgStyle?: Partial<CSSStyleDeclaration>;
minimizedSvgClassName?: string;
minimizedSvgStyle?: Partial<CSSStyleDeclaration>;
row: string;
shortDesc?: string;
showCount?: 'on' | 'off' | 'auto';
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type CellContext = {
column: string;
row: string;
subId: 'oj-nbox-cell';
};
// tslint:disable-next-line interface-over-type-literal
type Column = {
id: string;
label?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type CountLabelContext = {
column: string;
highlightedNodeCount: number;
nodeCount: number;
row: string;
totalNodeCount: number;
};
// tslint:disable-next-line interface-over-type-literal
type DialogContext = {
subId: 'oj-nbox-dialog';
};
// tslint:disable-next-line interface-over-type-literal
type GroupNodeContext = {
column: string;
groupCategory: string;
row: string;
subId: 'oj-nbox-group-node';
};
// tslint:disable-next-line interface-over-type-literal
type Node<K> = {
borderColor?: string;
borderWidth?: number;
categories?: string[];
color?: string;
column: string;
groupCategory?: string;
icon?: {
background?: 'neutral' | 'red' | 'orange' | 'forest' | 'green' | 'teal' | 'mauve' | 'purple';
borderColor?: string;
borderRadius?: string;
borderWidth?: number;
color?: string;
height?: number;
initials?: string;
opacity?: number;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'smallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
source?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
width?: number;
};
id?: K;
indicatorColor?: string;
indicatorIcon?: {
borderColor?: string;
borderRadius?: string;
borderWidth?: number;
color?: string;
height?: number;
opacity?: number;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'smallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
source?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
width?: number;
};
label?: string;
row: string;
secondaryLabel?: string;
shortDesc?: (string | ((context: NodeShortDescContext<K>) => string));
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
xPercentage?: number;
yPercentage?: number;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext<K> = {
id: K;
subId: 'oj-nbox-node';
};
// tslint:disable-next-line interface-over-type-literal
type NodeShortDescContext<K> = {
column: string;
id: K;
label: string;
row: string;
secondaryLabel: string;
};
// tslint:disable-next-line interface-over-type-literal
type NodeTemplateContext = {
componentElement: Element;
data: object;
index: number;
key: any;
};
// tslint:disable-next-line interface-over-type-literal
type Row = {
id: string;
label?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K> = {
color: string;
column: string;
componentElement: Element;
id: K;
indicatorColor: string;
label: string;
parentElement: Element;
row: string;
secondaryLabel: string;
};
}
export interface ojNBoxEventMap<K, D extends ojNBox.Node<K> | any> extends dvtBaseComponentEventMap<ojNBoxSettableProperties<K, D>> {
'animationOnDataChangeChanged': JetElementCustomEvent<ojNBox<K, D>["animationOnDataChange"]>;
'animationOnDisplayChanged': JetElementCustomEvent<ojNBox<K, D>["animationOnDisplay"]>;
'asChanged': JetElementCustomEvent<ojNBox<K, D>["as"]>;
'cellContentChanged': JetElementCustomEvent<ojNBox<K, D>["cellContent"]>;
'cellMaximizeChanged': JetElementCustomEvent<ojNBox<K, D>["cellMaximize"]>;
'cellsChanged': JetElementCustomEvent<ojNBox<K, D>["cells"]>;
'columnsChanged': JetElementCustomEvent<ojNBox<K, D>["columns"]>;
'columnsTitleChanged': JetElementCustomEvent<ojNBox<K, D>["columnsTitle"]>;
'countLabelChanged': JetElementCustomEvent<ojNBox<K, D>["countLabel"]>;
'dataChanged': JetElementCustomEvent<ojNBox<K, D>["data"]>;
'groupAttributesChanged': JetElementCustomEvent<ojNBox<K, D>["groupAttributes"]>;
'groupBehaviorChanged': JetElementCustomEvent<ojNBox<K, D>["groupBehavior"]>;
'hiddenCategoriesChanged': JetElementCustomEvent<ojNBox<K, D>["hiddenCategories"]>;
'highlightMatchChanged': JetElementCustomEvent<ojNBox<K, D>["highlightMatch"]>;
'highlightedCategoriesChanged': JetElementCustomEvent<ojNBox<K, D>["highlightedCategories"]>;
'hoverBehaviorChanged': JetElementCustomEvent<ojNBox<K, D>["hoverBehavior"]>;
'labelTruncationChanged': JetElementCustomEvent<ojNBox<K, D>["labelTruncation"]>;
'maximizedColumnChanged': JetElementCustomEvent<ojNBox<K, D>["maximizedColumn"]>;
'maximizedRowChanged': JetElementCustomEvent<ojNBox<K, D>["maximizedRow"]>;
'otherColorChanged': JetElementCustomEvent<ojNBox<K, D>["otherColor"]>;
'otherThresholdChanged': JetElementCustomEvent<ojNBox<K, D>["otherThreshold"]>;
'rowsChanged': JetElementCustomEvent<ojNBox<K, D>["rows"]>;
'rowsTitleChanged': JetElementCustomEvent<ojNBox<K, D>["rowsTitle"]>;
'selectionChanged': JetElementCustomEvent<ojNBox<K, D>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojNBox<K, D>["selectionMode"]>;
'styleDefaultsChanged': JetElementCustomEvent<ojNBox<K, D>["styleDefaults"]>;
'tooltipChanged': JetElementCustomEvent<ojNBox<K, D>["tooltip"]>;
'touchResponseChanged': JetElementCustomEvent<ojNBox<K, D>["touchResponse"]>;
'trackResizeChanged': JetElementCustomEvent<ojNBox<K, D>["trackResize"]>;
}
export interface ojNBoxSettableProperties<K, D extends ojNBox.Node<K> | any> extends dvtBaseComponentSettableProperties {
animationOnDataChange?: 'auto' | 'none';
animationOnDisplay?: 'auto' | 'none';
as?: string;
cellContent?: 'counts' | 'auto';
cellMaximize?: 'off' | 'on';
cells?: ojNBox.Cell[] | Promise<ojNBox.Cell[]> | null;
columns: ojNBox.Column[] | Promise<ojNBox.Column[]> | null;
columnsTitle?: string;
countLabel?: ((context: ojNBox.CountLabelContext) => (string | null));
data: DataProvider<K, D> | null;
groupAttributes?: 'color' | 'indicatorColor' | 'indicatorIconColor' | 'indicatorIconPattern' | 'indicatorIconShape';
groupBehavior?: 'acrossCells' | 'none' | 'withinCell';
hiddenCategories?: string[];
highlightMatch?: 'any' | 'all';
highlightedCategories?: string[];
hoverBehavior?: 'dim' | 'none';
labelTruncation?: 'ifRequired' | 'on';
maximizedColumn?: string;
maximizedRow?: string;
otherColor?: string;
otherThreshold?: number;
rows: ojNBox.Row[] | Promise<ojNBox.Row[]> | null;
rowsTitle?: string;
selection?: K[];
selectionMode?: 'none' | 'single' | 'multiple';
styleDefaults?: {
animationDuration?: number;
cellDefaults?: {
labelHalign?: 'center' | 'end' | 'start';
labelStyle?: Partial<CSSStyleDeclaration>;
maximizedSvgStyle?: Partial<CSSStyleDeclaration>;
minimizedSvgStyle?: Partial<CSSStyleDeclaration>;
showCount?: 'on' | 'off' | 'auto';
svgStyle?: Partial<CSSStyleDeclaration>;
};
columnLabelStyle?: Partial<CSSStyleDeclaration>;
columnsTitleStyle?: Partial<CSSStyleDeclaration>;
hoverBehaviorDelay?: number;
nodeDefaults?: {
borderColor?: string;
borderWidth?: number;
color?: string;
iconDefaults?: {
background?: 'neutral' | 'red' | 'orange' | 'forest' | 'green' | 'teal' | 'blue' | 'slate' | 'pink' | 'mauve' | 'purple' | 'lilac' | 'gray' | string;
borderColor?: string;
borderRadius?: string;
borderWidth?: number;
color?: string;
height?: number;
opacity?: number;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' |
'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
shape?: 'circle' | 'ellipse' | 'square' | 'plus' | 'diamond' | 'triangleUp' | 'triangleDown' | 'human' | 'rectangle' | 'star' | string;
source?: string;
width?: number;
};
indicatorColor?: string;
indicatorIconDefaults?: {
borderColor?: string;
borderRadius?: string;
borderWidth?: number;
color?: string;
height?: number;
opacity?: number;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' |
'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
shape?: 'circle' | 'ellipse' | 'square' | 'plus' | 'diamond' | 'triangleUp' | 'triangleDown' | 'human' | 'rectangle' | 'star' | string;
source?: string;
width?: number;
};
labelStyle?: Partial<CSSStyleDeclaration>;
secondaryLabelStyle?: Partial<CSSStyleDeclaration>;
};
rowLabelStyle?: Partial<CSSStyleDeclaration>;
rowsTitleStyle?: Partial<CSSStyleDeclaration>;
};
tooltip?: {
renderer: ((context: ojNBox.TooltipContext<K>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
})) | null;
};
touchResponse?: 'touchStart' | 'auto';
translations: {
componentName?: string;
highlightedCount?: string;
labelAdditionalData?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelGroup?: string;
labelInvalidData?: string;
labelNoData?: string;
labelOther?: string;
labelSize?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
}
export interface ojNBoxSettablePropertiesLenient<K, D extends ojNBox.Node<K> | any> extends Partial<ojNBoxSettableProperties<K, D>> {
[key: string]: any;
}
export interface ojNBoxNode<K = any> extends dvtBaseComponent<ojNBoxNodeSettableProperties<K>> {
borderColor?: string;
borderWidth?: number;
categories?: string[];
color?: string;
column: string;
groupCategory?: string;
icon?: {
background?: 'neutral' | 'red' | 'orange' | 'forest' | 'green' | 'teal' | 'blue' | 'slate' | 'mauve' | 'pink' | 'purple' | 'lilac' | 'gray' | string;
borderColor?: string;
borderRadius?: string;
borderWidth?: number;
color?: string;
height?: number | null;
initials?: string;
opacity?: number;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'mallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
source?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
width?: number | null;
};
indicatorColor?: string;
indicatorIcon?: {
borderColor?: string;
borderRadius?: string;
borderWidth?: number;
color?: string;
height?: number | null;
opacity?: number;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'smallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
source?: string | null;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration> | null;
width?: number | null;
};
label?: string;
row: string;
secondaryLabel?: string;
shortDesc?: (string | ((context: ojNBox.NodeShortDescContext<K>) => string));
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration> | null;
xPercentage?: number | null;
yPercentage?: number | null;
addEventListener<T extends keyof ojNBoxNodeEventMap<K>>(type: T, listener: (this: HTMLElement, ev: ojNBoxNodeEventMap<K>[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojNBoxNodeSettableProperties<K>>(property: T): ojNBoxNode<K>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojNBoxNodeSettableProperties<K>>(property: T, value: ojNBoxNodeSettableProperties<K>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojNBoxNodeSettableProperties<K>>): void;
setProperties(properties: ojNBoxNodeSettablePropertiesLenient<K>): void;
}
export namespace ojNBoxNode {
// tslint:disable-next-line interface-over-type-literal
type borderColorChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["borderColor"]>;
// tslint:disable-next-line interface-over-type-literal
type borderWidthChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["borderWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type columnChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["column"]>;
// tslint:disable-next-line interface-over-type-literal
type groupCategoryChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["groupCategory"]>;
// tslint:disable-next-line interface-over-type-literal
type iconChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["icon"]>;
// tslint:disable-next-line interface-over-type-literal
type indicatorColorChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["indicatorColor"]>;
// tslint:disable-next-line interface-over-type-literal
type indicatorIconChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["indicatorIcon"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type rowChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["row"]>;
// tslint:disable-next-line interface-over-type-literal
type secondaryLabelChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["secondaryLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type xPercentageChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["xPercentage"]>;
// tslint:disable-next-line interface-over-type-literal
type yPercentageChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["yPercentage"]>;
}
export interface ojNBoxNodeEventMap<K = any> extends dvtBaseComponentEventMap<ojNBoxNodeSettableProperties<K>> {
'borderColorChanged': JetElementCustomEvent<ojNBoxNode<K>["borderColor"]>;
'borderWidthChanged': JetElementCustomEvent<ojNBoxNode<K>["borderWidth"]>;
'categoriesChanged': JetElementCustomEvent<ojNBoxNode<K>["categories"]>;
'colorChanged': JetElementCustomEvent<ojNBoxNode<K>["color"]>;
'columnChanged': JetElementCustomEvent<ojNBoxNode<K>["column"]>;
'groupCategoryChanged': JetElementCustomEvent<ojNBoxNode<K>["groupCategory"]>;
'iconChanged': JetElementCustomEvent<ojNBoxNode<K>["icon"]>;
'indicatorColorChanged': JetElementCustomEvent<ojNBoxNode<K>["indicatorColor"]>;
'indicatorIconChanged': JetElementCustomEvent<ojNBoxNode<K>["indicatorIcon"]>;
'labelChanged': JetElementCustomEvent<ojNBoxNode<K>["label"]>;
'rowChanged': JetElementCustomEvent<ojNBoxNode<K>["row"]>;
'secondaryLabelChanged': JetElementCustomEvent<ojNBoxNode<K>["secondaryLabel"]>;
'shortDescChanged': JetElementCustomEvent<ojNBoxNode<K>["shortDesc"]>;
'svgClassNameChanged': JetElementCustomEvent<ojNBoxNode<K>["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojNBoxNode<K>["svgStyle"]>;
'xPercentageChanged': JetElementCustomEvent<ojNBoxNode<K>["xPercentage"]>;
'yPercentageChanged': JetElementCustomEvent<ojNBoxNode<K>["yPercentage"]>;
}
export interface ojNBoxNodeSettableProperties<K = any> extends dvtBaseComponentSettableProperties {
borderColor?: string;
borderWidth?: number;
categories?: string[];
color?: string;
column: string;
groupCategory?: string;
icon?: {
background?: 'neutral' | 'red' | 'orange' | 'forest' | 'green' | 'teal' | 'blue' | 'slate' | 'mauve' | 'pink' | 'purple' | 'lilac' | 'gray' | string;
borderColor?: string;
borderRadius?: string;
borderWidth?: number;
color?: string;
height?: number | null;
initials?: string;
opacity?: number;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'mallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
source?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
width?: number | null;
};
indicatorColor?: string;
indicatorIcon?: {
borderColor?: string;
borderRadius?: string;
borderWidth?: number;
color?: string;
height?: number | null;
opacity?: number;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'smallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
source?: string | null;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration> | null;
width?: number | null;
};
label?: string;
row: string;
secondaryLabel?: string;
shortDesc?: (string | ((context: ojNBox.NodeShortDescContext<K>) => string));
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration> | null;
xPercentage?: number | null;
yPercentage?: number | null;
}
export interface ojNBoxNodeSettablePropertiesLenient<K = any> extends Partial<ojNBoxNodeSettableProperties<K>> {
[key: string]: any;
}
export type NBoxElement<K, D extends ojNBox.Node<K> | any> = ojNBox<K, D>;
export type NBoxNodeElement<K = any> = ojNBoxNode<K>;
export namespace NBoxElement {
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type cellContentChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["cellContent"]>;
// tslint:disable-next-line interface-over-type-literal
type cellMaximizeChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["cellMaximize"]>;
// tslint:disable-next-line interface-over-type-literal
type cellsChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["cells"]>;
// tslint:disable-next-line interface-over-type-literal
type columnsChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["columns"]>;
// tslint:disable-next-line interface-over-type-literal
type columnsTitleChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["columnsTitle"]>;
// tslint:disable-next-line interface-over-type-literal
type countLabelChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["countLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type groupAttributesChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["groupAttributes"]>;
// tslint:disable-next-line interface-over-type-literal
type groupBehaviorChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["groupBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type hiddenCategoriesChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["hiddenCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightMatchChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["highlightMatch"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightedCategoriesChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["highlightedCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["hoverBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type labelTruncationChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["labelTruncation"]>;
// tslint:disable-next-line interface-over-type-literal
type maximizedColumnChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["maximizedColumn"]>;
// tslint:disable-next-line interface-over-type-literal
type maximizedRowChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["maximizedRow"]>;
// tslint:disable-next-line interface-over-type-literal
type otherColorChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["otherColor"]>;
// tslint:disable-next-line interface-over-type-literal
type otherThresholdChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["otherThreshold"]>;
// tslint:disable-next-line interface-over-type-literal
type rowsChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["rows"]>;
// tslint:disable-next-line interface-over-type-literal
type rowsTitleChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["rowsTitle"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type styleDefaultsChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["styleDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type touchResponseChanged<K, D extends ojNBox.Node<K> | any> = JetElementCustomEvent<ojNBox<K, D>["touchResponse"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends ojNBox.Node<K> | any> = dvtBaseComponent.trackResizeChanged<ojNBoxSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type Cell = {
column: string;
label?: string;
labelHalign?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
maximizedSvgClassName?: string;
maximizedSvgStyle?: Partial<CSSStyleDeclaration>;
minimizedSvgClassName?: string;
minimizedSvgStyle?: Partial<CSSStyleDeclaration>;
row: string;
shortDesc?: string;
showCount?: 'on' | 'off' | 'auto';
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type Column = {
id: string;
label?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type DialogContext = {
subId: 'oj-nbox-dialog';
};
// tslint:disable-next-line interface-over-type-literal
type Node<K> = {
borderColor?: string;
borderWidth?: number;
categories?: string[];
color?: string;
column: string;
groupCategory?: string;
icon?: {
background?: 'neutral' | 'red' | 'orange' | 'forest' | 'green' | 'teal' | 'mauve' | 'purple';
borderColor?: string;
borderRadius?: string;
borderWidth?: number;
color?: string;
height?: number;
initials?: string;
opacity?: number;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'smallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
source?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
width?: number;
};
id?: K;
indicatorColor?: string;
indicatorIcon?: {
borderColor?: string;
borderRadius?: string;
borderWidth?: number;
color?: string;
height?: number;
opacity?: number;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'smallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
source?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
width?: number;
};
label?: string;
row: string;
secondaryLabel?: string;
shortDesc?: (string | ((context: ojNBox.NodeShortDescContext<K>) => string));
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
xPercentage?: number;
yPercentage?: number;
};
// tslint:disable-next-line interface-over-type-literal
type NodeShortDescContext<K> = {
column: string;
id: K;
label: string;
row: string;
secondaryLabel: string;
};
// tslint:disable-next-line interface-over-type-literal
type Row = {
id: string;
label?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
};
}
export namespace NBoxNodeElement {
// tslint:disable-next-line interface-over-type-literal
type borderColorChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["borderColor"]>;
// tslint:disable-next-line interface-over-type-literal
type borderWidthChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["borderWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type columnChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["column"]>;
// tslint:disable-next-line interface-over-type-literal
type groupCategoryChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["groupCategory"]>;
// tslint:disable-next-line interface-over-type-literal
type iconChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["icon"]>;
// tslint:disable-next-line interface-over-type-literal
type indicatorColorChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["indicatorColor"]>;
// tslint:disable-next-line interface-over-type-literal
type indicatorIconChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["indicatorIcon"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type rowChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["row"]>;
// tslint:disable-next-line interface-over-type-literal
type secondaryLabelChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["secondaryLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type xPercentageChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["xPercentage"]>;
// tslint:disable-next-line interface-over-type-literal
type yPercentageChanged<K = any> = JetElementCustomEvent<ojNBoxNode<K>["yPercentage"]>;
}
export interface NBoxIntrinsicProps extends Partial<Readonly<ojNBoxSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onanimationOnDataChangeChanged?: (value: ojNBoxEventMap<any, any>['animationOnDataChangeChanged']) => void;
onanimationOnDisplayChanged?: (value: ojNBoxEventMap<any, any>['animationOnDisplayChanged']) => void;
onasChanged?: (value: ojNBoxEventMap<any, any>['asChanged']) => void;
oncellContentChanged?: (value: ojNBoxEventMap<any, any>['cellContentChanged']) => void;
oncellMaximizeChanged?: (value: ojNBoxEventMap<any, any>['cellMaximizeChanged']) => void;
oncellsChanged?: (value: ojNBoxEventMap<any, any>['cellsChanged']) => void;
oncolumnsChanged?: (value: ojNBoxEventMap<any, any>['columnsChanged']) => void;
oncolumnsTitleChanged?: (value: ojNBoxEventMap<any, any>['columnsTitleChanged']) => void;
oncountLabelChanged?: (value: ojNBoxEventMap<any, any>['countLabelChanged']) => void;
ondataChanged?: (value: ojNBoxEventMap<any, any>['dataChanged']) => void;
ongroupAttributesChanged?: (value: ojNBoxEventMap<any, any>['groupAttributesChanged']) => void;
ongroupBehaviorChanged?: (value: ojNBoxEventMap<any, any>['groupBehaviorChanged']) => void;
onhiddenCategoriesChanged?: (value: ojNBoxEventMap<any, any>['hiddenCategoriesChanged']) => void;
onhighlightMatchChanged?: (value: ojNBoxEventMap<any, any>['highlightMatchChanged']) => void;
onhighlightedCategoriesChanged?: (value: ojNBoxEventMap<any, any>['highlightedCategoriesChanged']) => void;
onhoverBehaviorChanged?: (value: ojNBoxEventMap<any, any>['hoverBehaviorChanged']) => void;
onlabelTruncationChanged?: (value: ojNBoxEventMap<any, any>['labelTruncationChanged']) => void;
onmaximizedColumnChanged?: (value: ojNBoxEventMap<any, any>['maximizedColumnChanged']) => void;
onmaximizedRowChanged?: (value: ojNBoxEventMap<any, any>['maximizedRowChanged']) => void;
onotherColorChanged?: (value: ojNBoxEventMap<any, any>['otherColorChanged']) => void;
onotherThresholdChanged?: (value: ojNBoxEventMap<any, any>['otherThresholdChanged']) => void;
onrowsChanged?: (value: ojNBoxEventMap<any, any>['rowsChanged']) => void;
onrowsTitleChanged?: (value: ojNBoxEventMap<any, any>['rowsTitleChanged']) => void;
onselectionChanged?: (value: ojNBoxEventMap<any, any>['selectionChanged']) => void;
onselectionModeChanged?: (value: ojNBoxEventMap<any, any>['selectionModeChanged']) => void;
onstyleDefaultsChanged?: (value: ojNBoxEventMap<any, any>['styleDefaultsChanged']) => void;
ontooltipChanged?: (value: ojNBoxEventMap<any, any>['tooltipChanged']) => void;
ontouchResponseChanged?: (value: ojNBoxEventMap<any, any>['touchResponseChanged']) => void;
ontrackResizeChanged?: (value: ojNBoxEventMap<any, any>['trackResizeChanged']) => void;
children?: ComponentChildren;
}
export interface NBoxNodeIntrinsicProps extends Partial<Readonly<ojNBoxNodeSettableProperties<any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onborderColorChanged?: (value: ojNBoxNodeEventMap<any>['borderColorChanged']) => void;
onborderWidthChanged?: (value: ojNBoxNodeEventMap<any>['borderWidthChanged']) => void;
oncategoriesChanged?: (value: ojNBoxNodeEventMap<any>['categoriesChanged']) => void;
oncolorChanged?: (value: ojNBoxNodeEventMap<any>['colorChanged']) => void;
oncolumnChanged?: (value: ojNBoxNodeEventMap<any>['columnChanged']) => void;
ongroupCategoryChanged?: (value: ojNBoxNodeEventMap<any>['groupCategoryChanged']) => void;
oniconChanged?: (value: ojNBoxNodeEventMap<any>['iconChanged']) => void;
onindicatorColorChanged?: (value: ojNBoxNodeEventMap<any>['indicatorColorChanged']) => void;
onindicatorIconChanged?: (value: ojNBoxNodeEventMap<any>['indicatorIconChanged']) => void;
onlabelChanged?: (value: ojNBoxNodeEventMap<any>['labelChanged']) => void;
onrowChanged?: (value: ojNBoxNodeEventMap<any>['rowChanged']) => void;
onsecondaryLabelChanged?: (value: ojNBoxNodeEventMap<any>['secondaryLabelChanged']) => void;
onshortDescChanged?: (value: ojNBoxNodeEventMap<any>['shortDescChanged']) => void;
onsvgClassNameChanged?: (value: ojNBoxNodeEventMap<any>['svgClassNameChanged']) => void;
onsvgStyleChanged?: (value: ojNBoxNodeEventMap<any>['svgStyleChanged']) => void;
onxPercentageChanged?: (value: ojNBoxNodeEventMap<any>['xPercentageChanged']) => void;
onyPercentageChanged?: (value: ojNBoxNodeEventMap<any>['yPercentageChanged']) => void;
children?: ComponentChildren;
}
declare global {
namespace preact.JSX {
interface IntrinsicElements {
"oj-n-box": NBoxIntrinsicProps;
"oj-n-box-node": NBoxNodeIntrinsicProps;
}
}
} | the_stack |
import { ApiProperty } from "@nestjs/swagger";
import {
ValidateNested,
IsIP,
IsString,
IsIn,
IsBoolean,
IsInt,
Min,
IsEmail,
IsOptional,
IsArray,
ArrayNotEmpty,
ArrayUnique,
IsUrl
} from "class-validator";
import { Type } from "class-transformer";
import { If, isEmoji, IsEmoji, IsPortNumber } from "@/common/validators";
import { ConfigRelation, ConfigRelationType } from "./config-relation.decorator";
class ServerConfig {
@IsIP()
readonly hostname: string;
@IsPortNumber()
readonly port: number;
@IsArray()
@IsString({ each: true })
readonly trustProxy: string;
@IsOptional()
@IsInt()
@Min(0)
readonly clusters: number;
}
class ServicesConfigDatabase {
@IsIn(["mysql", "mariadb"])
readonly type: "mysql" | "mariadb";
@IsString()
readonly host: string;
@IsPortNumber()
readonly port: number;
@IsString()
readonly username: string;
@IsString()
readonly password: string;
@IsString()
readonly database: string;
}
class ServicesConfigMinio {
@IsUrl({ require_tld: false })
readonly endpoint: string;
@IsUrl({ require_tld: false })
@IsOptional()
readonly endpointForUser: string;
@IsUrl({ require_tld: false })
@IsOptional()
readonly endpointForJudge: string;
@IsString()
readonly accessKey: string;
@IsString()
readonly secretKey: string;
@IsString()
readonly bucket: string;
}
class ServicesConfigMail {
@IsEmail()
@IsOptional()
readonly address: string;
readonly transport: unknown;
}
class ServicesConfig {
@ValidateNested()
@Type(() => ServicesConfigDatabase)
readonly database: ServicesConfigDatabase;
@ValidateNested()
@Type(() => ServicesConfigMinio)
readonly minio: ServicesConfigMinio;
@IsString()
readonly redis: string;
@ValidateNested()
@Type(() => ServicesConfigMail)
readonly mail: ServicesConfigMail;
}
class SecurityConfigCrossOrigin {
@IsBoolean()
readonly enabled: boolean;
@IsString({
each: true
})
readonly whiteList: string[];
}
class SecurityConfigRecaptcha {
@IsString()
@IsOptional()
readonly secretKey: string;
@IsBoolean()
readonly useRecaptchaNet: boolean;
@IsString()
@IsOptional()
readonly proxyUrl: string;
}
class SecurityConfigRateLimit {
@IsInt()
readonly maxRequests: number;
@IsInt()
readonly durationSeconds: number;
}
class SecurityConfig {
@IsString()
readonly sessionSecret: string;
@IsString()
readonly maintainceKey: string;
@ValidateNested()
@Type(() => SecurityConfigRecaptcha)
readonly recaptcha: SecurityConfigRecaptcha;
@ValidateNested()
@Type(() => SecurityConfigCrossOrigin)
readonly crossOrigin: SecurityConfigCrossOrigin;
@ValidateNested()
@Type(() => SecurityConfigRateLimit)
@IsOptional()
readonly rateLimit: SecurityConfigRateLimit;
}
// These config items will be sent to client
class PreferenceConfigSecurity {
@IsBoolean()
@ApiProperty()
readonly recaptchaEnabled: boolean;
@IsString()
@IsOptional()
@ApiProperty()
readonly recaptchaKey: string;
@IsBoolean()
@ApiProperty()
readonly requireEmailVerification: boolean;
@IsBoolean()
@ApiProperty()
readonly allowUserChangeUsername: boolean;
@IsBoolean()
@ApiProperty()
readonly allowEveryoneCreateProblem: boolean;
@IsBoolean()
@ApiProperty()
readonly allowNonPrivilegedUserEditPublicProblem: boolean;
@IsBoolean()
@ApiProperty()
readonly allowOwnerManageProblemPermission: boolean;
@IsBoolean()
@ApiProperty()
readonly allowOwnerDeleteProblem: boolean;
@IsBoolean()
@ApiProperty()
readonly discussionDefaultPublic: boolean;
@IsBoolean()
@ApiProperty()
readonly discussionReplyDefaultPublic: boolean;
@IsBoolean()
@ApiProperty()
readonly allowEveryoneCreateDiscussion: boolean;
}
// These config items will be sent to client
class PreferenceConfigPagination {
@IsInt()
@Min(1)
@ApiProperty()
readonly homepageUserList: number;
@IsInt()
@Min(1)
@ApiProperty()
readonly homepageProblemList: number;
@IsInt()
@Min(1)
@ConfigRelation("queryLimit.problemSet", ConfigRelationType.LessThanOrEqual)
@ApiProperty()
readonly problemSet: number;
@IsInt()
@Min(1)
@ConfigRelation("queryLimit.problemSet", ConfigRelationType.LessThanOrEqual)
@ApiProperty()
readonly searchProblemsPreview: number;
@IsInt()
@Min(1)
@ConfigRelation("queryLimit.submissions", ConfigRelationType.LessThanOrEqual)
@ApiProperty()
readonly submissions: number;
@IsInt()
@Min(1)
@ConfigRelation("queryLimit.submissionStatistics", ConfigRelationType.LessThanOrEqual)
@ApiProperty()
readonly submissionStatistics: number;
@IsInt()
@Min(1)
@ConfigRelation("queryLimit.userList", ConfigRelationType.LessThanOrEqual)
@ApiProperty()
readonly userList: number;
@IsInt()
@Min(1)
@ConfigRelation("queryLimit.userAuditLogs", ConfigRelationType.LessThanOrEqual)
@ApiProperty()
readonly userAuditLogs: number;
@IsInt()
@Min(1)
@ConfigRelation("queryLimit.discussions", ConfigRelationType.LessThanOrEqual)
@ApiProperty()
readonly discussions: number;
@IsInt()
@Min(1)
@ConfigRelation("queryLimit.discussions", ConfigRelationType.LessThanOrEqual)
@ApiProperty()
readonly searchDiscussionsPreview: number;
@IsInt()
@Min(1)
@ConfigRelation("queryLimit.discussionReplies", ConfigRelationType.LessThanOrEqual)
@ApiProperty()
readonly discussionReplies: number;
@IsInt()
@Min(1)
@ConfigRelation("preference.pagination.discussionReplies", ConfigRelationType.LessThan)
@ApiProperty()
readonly discussionRepliesHead: number;
@IsInt()
@Min(1)
@ConfigRelation("queryLimit.discussionReplies", ConfigRelationType.LessThanOrEqual)
@ApiProperty()
readonly discussionRepliesMore: number;
}
// These config items will be sent to client
class PreferenceConfigMisc {
@IsString()
@ApiProperty()
readonly appLogo: string;
@If(value => typeof value === "object" && Object.values(value).every(s => typeof s === "string"))
@ApiProperty()
readonly appLogoForTheme: Record<string, string>;
@IsString()
@IsOptional()
@ApiProperty()
readonly googleAnalyticsId: string;
@IsString()
@ApiProperty()
readonly gravatarCdn: string;
@IsBoolean()
@ApiProperty()
readonly redirectLegacyUrls: boolean;
@IsString()
@IsOptional()
@ApiProperty()
readonly legacyContestsEntryUrl: boolean;
@IsBoolean()
@ApiProperty()
readonly homepageUserListOnMainView: boolean;
@IsBoolean()
@ApiProperty()
readonly sortUserByRating: boolean;
@IsBoolean()
@ApiProperty()
readonly renderMarkdownInUserBio: boolean;
@IsEmoji({ each: true })
@IsString({ each: true })
@ArrayUnique()
@ArrayNotEmpty()
@IsArray()
@ApiProperty()
readonly discussionReactionEmojis: string[];
@IsBoolean()
@ApiProperty()
readonly discussionReactionAllowCustomEmojis: boolean;
}
class PreferenceConfigServerSideOnly {
@If((blacklist: string | unknown[]) =>
(function validate(value: string | unknown[]) {
if (typeof value === "string") return (value.startsWith("/") && value.endsWith("/")) || isEmoji(value);
else if (Array.isArray(value)) return value.every(validate);
else return false;
})(blacklist)
)
discussionReactionCustomEmojisBlacklist: string | unknown[];
@IsBoolean()
dynamicTaskPriority: boolean;
}
// These config items will be sent to client
export class PreferenceConfig {
@IsString()
@ApiProperty()
readonly siteName: string;
@ValidateNested()
@Type(() => PreferenceConfigSecurity)
@ApiProperty()
readonly security: PreferenceConfigSecurity;
@ValidateNested()
@Type(() => PreferenceConfigPagination)
@ApiProperty()
readonly pagination: PreferenceConfigPagination;
@ValidateNested()
@Type(() => PreferenceConfigMisc)
@ApiProperty()
readonly misc: PreferenceConfigMisc;
@ValidateNested()
@Type(() => PreferenceConfigServerSideOnly)
serverSideOnly: PreferenceConfigServerSideOnly;
}
class ResourceLimitConfig {
@IsInt()
@Min(0)
readonly problemTestdataFiles: number;
@IsInt()
@Min(0)
readonly problemTestdataSize: number;
@IsInt()
@Min(0)
readonly problemAdditionalFileFiles: number;
@IsInt()
@Min(0)
readonly problemAdditionalFileSize: number;
@IsInt()
@Min(0)
readonly problemSamplesToRun: number;
@IsInt()
@Min(1)
readonly problemTestcases: number;
@IsInt()
@Min(1)
readonly problemTimeLimit: number;
@IsInt()
@Min(1)
readonly problemMemoryLimit: number;
@IsInt()
@Min(0)
readonly submissionFileSize: number;
}
class QueryLimitConfig {
@IsInt()
@Min(1)
readonly problemSet: number;
@IsInt()
@Min(1)
readonly submissions: number;
@IsInt()
@Min(1)
readonly submissionStatistics: number;
@IsInt()
@Min(1)
readonly searchUser: number;
@IsInt()
@Min(1)
readonly searchGroup: number;
@IsInt()
@Min(1)
readonly userList: number;
@IsInt()
@Min(1)
readonly userAuditLogs: number;
@IsInt()
@Min(1)
@ApiProperty()
readonly discussions: number;
@IsInt()
@Min(1)
@ApiProperty()
readonly discussionReplies: number;
}
class JudgeLimitConfig {
@IsInt()
@Min(1)
compilerMessage: number;
@IsInt()
@Min(1)
outputSize: number;
@IsInt()
@Min(1)
dataDisplay: number;
@IsInt()
@Min(1)
dataDisplayForSubmitAnswer: number;
@IsInt()
@Min(1)
stderrDisplay: number;
}
class JudgeConfig {
@ValidateNested()
@Type(() => JudgeLimitConfig)
readonly limit: JudgeLimitConfig;
}
class EventReportConfig {
@IsString()
@IsOptional()
readonly telegramBotToken?: string;
@IsUrl()
@IsOptional()
readonly telegramApiRoot?: string;
@If(value => typeof value === "string" || typeof value === "number")
@IsOptional()
readonly sentTo?: string | number;
@IsString()
@IsOptional()
readonly proxyUrl?: string;
}
class VendorIp2RegionConfig {
@IsString()
readonly ipv4db: string;
@IsString()
readonly ipv6db: string;
}
class VendorConfig {
@ValidateNested()
@Type(() => VendorIp2RegionConfig)
@IsOptional()
readonly ip2region: VendorIp2RegionConfig;
}
export class AppConfig {
@ValidateNested()
@Type(() => ServerConfig)
readonly server: ServerConfig;
@ValidateNested()
@Type(() => ServicesConfig)
readonly services: ServicesConfig;
@ValidateNested()
@Type(() => SecurityConfig)
readonly security: SecurityConfig;
@ValidateNested()
@Type(() => PreferenceConfig)
readonly preference: PreferenceConfig;
@ValidateNested()
@Type(() => ResourceLimitConfig)
readonly resourceLimit: ResourceLimitConfig;
@ValidateNested()
@Type(() => QueryLimitConfig)
readonly queryLimit: QueryLimitConfig;
@ValidateNested()
@Type(() => EventReportConfig)
readonly eventReport: EventReportConfig;
@ValidateNested()
@Type(() => JudgeConfig)
readonly judge: JudgeConfig;
@ValidateNested()
@Type(() => VendorConfig)
readonly vendor: VendorConfig;
} | the_stack |
import { Browser, KeyboardEventArgs } from '@syncfusion/ej2-base';
import { extend, isNullOrUndefined } from '@syncfusion/ej2-base';
import { closest, classList } from '@syncfusion/ej2-base';
import { SortSettings } from '../base/grid';
import { Column } from '../models/column';
import { IGrid, IAction, NotifyArgs, EJ2Intance } from '../base/interface';
import { SortDirection, ResponsiveDialogAction } from '../base/enum';
import { setCssInGridPopUp, getActualPropFromColl, isActionPrevent, iterateExtend, parentsUntil } from '../base/util';
import { addRemoveEventListener } from '../base/util';
import * as events from '../base/constant';
import { SortDescriptorModel } from '../base/grid-model';
import { AriaService } from '../services/aria-service';
import { ServiceLocator } from '../services/service-locator';
import { FocusStrategy } from '../services/focus-strategy';
import { ResponsiveDialogRenderer } from '../renderer/responsive-dialog-renderer';
import * as literals from '../base/string-literals';
/**
*
* The `Sort` module is used to handle sorting action.
*/
export class Sort implements IAction {
//Internal variables
private columnName: string;
private direction: SortDirection;
private isMultiSort: boolean;
private lastSortedCol: string;
private sortSettings: SortSettings;
private enableSortMultiTouch: boolean;
private contentRefresh: boolean = true;
private isRemove: boolean;
private sortedColumns: string[];
private isModelChanged: boolean = true;
private aria: AriaService = new AriaService();
private focus: FocusStrategy;
private lastSortedCols: SortDescriptorModel[];
private lastCols: string[];
private evtHandlers: { event: string, handler: Function }[];
//Module declarations
/** @hidden */
public parent: IGrid;
private currentTarget: Element = null;
/** @hidden */
public responsiveDialogRenderer: ResponsiveDialogRenderer;
/** @hidden */
public serviceLocator: ServiceLocator;
/**
* Constructor for Grid sorting module
*
* @param {IGrid} parent - specifies the IGrid
* @param {SortSettings} sortSettings - specifies the SortSettings
* @param {string[]} sortedColumns - specifies the string
* @param {ServiceLocator} locator - specifies the ServiceLocator
* @hidden
*/
constructor(parent?: IGrid, sortSettings?: SortSettings, sortedColumns?: string[], locator?: ServiceLocator) {
this.parent = parent;
this.sortSettings = sortSettings;
this.sortedColumns = sortedColumns;
this.serviceLocator = locator;
this.focus = locator.getService<FocusStrategy>('focus');
this.addEventListener();
this.setFullScreenDialog();
}
/**
* The function used to update sortSettings
*
* @returns {void}
* @hidden
*/
public updateModel(): void {
const sortedColumn: SortDescriptorModel = { field: this.columnName, direction: this.direction };
let index: number;
const gCols: string[] = this.parent.groupSettings.columns;
let flag: boolean = false;
if (!this.isMultiSort) {
if (!gCols.length) {
this.sortSettings.columns = [sortedColumn];
} else {
const sortedCols: SortDescriptorModel[] = [];
for (let i: number = 0, len: number = gCols.length; i < len; i++) {
index = this.getSortedColsIndexByField(gCols[i], sortedCols);
if (this.columnName === gCols[i]) {
flag = true;
sortedCols.push(sortedColumn);
} else {
const sCol: SortDescriptorModel = this.getSortColumnFromField(gCols[i]);
sortedCols.push({ field: sCol.field, direction: sCol.direction, isFromGroup: sCol.isFromGroup });
}
}
if (!flag) {
sortedCols.push(sortedColumn);
}
this.sortSettings.columns = sortedCols;
}
} else {
index = this.getSortedColsIndexByField(this.columnName);
if (index > -1) {
this.sortSettings.columns.splice(index, 1);
}
this.sortSettings.columns.push(sortedColumn);
// eslint-disable-next-line no-self-assign
this.sortSettings.columns = this.sortSettings.columns;
}
this.parent.dataBind();
this.lastSortedCol = this.columnName;
}
/**
* The function used to trigger onActionComplete
*
* @param {NotifyArgs} e - specifies the NotifyArgs
* @returns {void}
* @hidden
*/
public onActionComplete(e: NotifyArgs): void {
const args: Object = !this.isRemove ? {
columnName: this.columnName, direction: this.direction, requestType: 'sorting', type: events.actionComplete
} : { requestType: 'sorting', type: events.actionComplete };
this.isRemove = false;
this.parent.trigger(events.actionComplete, extend(e, args));
}
/**
* Sorts a column with the given options.
*
* @param {string} columnName - Defines the column name to sort.
* @param {SortDirection} direction - Defines the direction of sorting field.
* @param {boolean} isMultiSort - Specifies whether the previously sorted columns are to be maintained.
* @returns {void}
*/
public sortColumn(columnName: string, direction: SortDirection, isMultiSort?: boolean): void {
const gObj: IGrid = this.parent;
if (this.parent.getColumnByField(columnName).allowSorting === false || this.parent.isContextMenuOpen()) {
this.parent.log('action_disabled_column', {moduleName: this.getModuleName(), columnName: columnName});
return;
}
if (!gObj.allowMultiSorting) {
isMultiSort = gObj.allowMultiSorting;
}
if (this.isActionPrevent()) {
gObj.notify(
events.preventBatch,
{
instance: this, handler: this.sortColumn,
arg1: columnName, arg2: direction, arg3: isMultiSort
});
return;
}
this.backupSettings();
this.columnName = columnName;
this.direction = direction;
this.isMultiSort = isMultiSort;
this.removeSortIcons();
this.updateSortedCols(columnName, isMultiSort);
this.updateModel();
}
private setFullScreenDialog(): void {
if (this.serviceLocator) {
this.serviceLocator.registerAdaptiveService(this, this.parent.enableAdaptiveUI, ResponsiveDialogAction.isSort);
}
}
private backupSettings(): void {
this.lastSortedCols = iterateExtend(this.sortSettings.columns);
this.lastCols = this.sortedColumns;
}
private restoreSettings(): void {
this.isModelChanged = false;
this.isMultiSort = true;
this.parent.setProperties({ sortSettings: { columns: this.lastSortedCols } }, true);
//this.parent.sortSettings.columns = this.lastSortedCols;
this.sortedColumns = this.lastCols;
this.isModelChanged = true;
}
private updateSortedCols(columnName: string, isMultiSort: boolean): void {
if (!isMultiSort) {
if (this.parent.allowGrouping) {
for (let i: number = 0, len: number = this.sortedColumns.length; i < len; i++) {
if (this.parent.groupSettings.columns.indexOf(this.sortedColumns[i]) < 0) {
this.sortedColumns.splice(i, 1);
len--;
i--;
}
}
} else {
this.sortedColumns.splice(0, this.sortedColumns.length);
}
}
if (this.sortedColumns.indexOf(columnName) < 0) {
this.sortedColumns.push(columnName);
}
}
/**
* @param {NotifyArgs} e - specifies the NotifyArgs
* @returns {void}
* @hidden
*/
public onPropertyChanged(e: NotifyArgs): void {
if (e.module !== this.getModuleName()) {
return;
}
if (this.contentRefresh) {
const args: Object = this.sortSettings.columns.length ? {
columnName: this.columnName, direction: this.direction, requestType: 'sorting',
type: events.actionBegin, target: this.currentTarget, cancel: false
} : {
requestType: 'sorting', type: events.actionBegin, cancel: false,
target: this.currentTarget
};
this.parent.notify(events.modelChanged, args);
}
this.refreshSortSettings();
this.removeSortIcons();
this.addSortIcons();
}
private refreshSortSettings(): void {
this.sortedColumns.length = 0;
const sortColumns: SortDescriptorModel[] = this.sortSettings.columns;
for (let i: number = 0; i < sortColumns.length; i++) {
if (!sortColumns[i].isFromGroup) {
this.sortedColumns.push(sortColumns[i].field);
}
}
}
/**
* Clears all the sorted columns of the Grid.
*
* @returns {void}
*/
public clearSorting(): void {
const cols: SortDescriptorModel[] = getActualPropFromColl(this.sortSettings.columns);
if (this.isActionPrevent()) {
this.parent.notify(events.preventBatch, { instance: this, handler: this.clearSorting });
return;
}
for (let i: number = 0, len: number = cols.length; i < len; i++) {
this.removeSortColumn(cols[i].field);
}
}
private isActionPrevent(): boolean {
return isActionPrevent(this.parent);
}
/**
* Remove sorted column by field name.
*
* @param {string} field - Defines the column field name to remove sort.
* @returns {void}
* @hidden
*/
public removeSortColumn(field: string): void {
const gObj: IGrid = this.parent;
const cols: SortDescriptorModel[] = this.sortSettings.columns;
if (cols.length === 0 && this.sortedColumns.indexOf(field) < 0) {
return; }
if (this.isActionPrevent()) {
this.parent.notify(events.preventBatch, { instance: this, handler: this.removeSortColumn, arg1: field });
return;
}
this.backupSettings();
this.removeSortIcons();
const args: Object = { requestType: 'sorting', type: events.actionBegin, target: this.currentTarget };
for (let i: number = 0, len: number = cols.length; i < len; i++) {
if (cols[i].field === field) {
if (gObj.allowGrouping && gObj.groupSettings.columns.indexOf(cols[i].field) > -1) {
continue;
}
this.sortedColumns.splice(this.sortedColumns.indexOf(cols[i].field), 1);
cols.splice(i, 1);
this.isRemove = true;
if (this.isModelChanged) {
this.parent.notify(events.modelChanged, args);
}
break;
}
}
if (!(<{ cancel?: boolean }>args).cancel) {
this.addSortIcons();
}
}
private getSortedColsIndexByField(field: string, sortedColumns?: SortDescriptorModel[]): number {
const cols: SortDescriptorModel[] = sortedColumns ? sortedColumns : this.sortSettings.columns;
for (let i: number = 0, len: number = cols.length; i < len; i++) {
if (cols[i].field === field) {
return i;
}
}
return -1;
}
/**
* For internal use only - Get the module name.
*
* @returns {string} returns the module name
* @private
*/
protected getModuleName(): string {
return 'sort';
}
private initialEnd(): void {
this.parent.off(events.contentReady, this.initialEnd);
if (this.parent.getColumns().length && this.sortSettings.columns.length) {
const gObj: IGrid = this.parent;
this.contentRefresh = false;
this.isMultiSort = this.sortSettings.columns.length > 1;
for (const col of gObj.sortSettings.columns.slice()) {
if (this.sortedColumns.indexOf(col.field) > -1) {
this.sortColumn(col.field, col.direction, true);
}
}
this.isMultiSort = false;
this.contentRefresh = true;
}
}
/**
* @returns {void}
* @hidden
*/
public addEventListener(): void {
if (this.parent.isDestroyed) { return; }
this.evtHandlers = [{ event: events.setFullScreenDialog, handler: this.setFullScreenDialog },
{ event: events.contentReady, handler: this.initialEnd },
{ event: events.sortComplete, handler: this.onActionComplete },
{ event: events.inBoundModelChanged, handler: this.onPropertyChanged },
{ event: events.click, handler: this.clickHandler },
{ event: events.headerRefreshed, handler: this.refreshSortIcons },
{ event: events.keyPressed, handler: this.keyPressed },
{ event: events.cancelBegin, handler: this.cancelBeginEvent },
{ event: events.destroy, handler: this.destroy }];
addRemoveEventListener(this.parent, this.evtHandlers, true, this);
}
/**
* @returns {void}
* @hidden
*/
public removeEventListener(): void {
if (this.parent.isDestroyed) { return; }
addRemoveEventListener(this.parent, this.evtHandlers, false);
}
/**
* To destroy the sorting
*
* @returns {void}
* @hidden
*/
public destroy(): void {
this.isModelChanged = false;
const gridElement: Element = this.parent.element;
if (!gridElement || (!gridElement.querySelector('.' + literals.gridHeader) && !gridElement.querySelector( '.' + literals.gridContent))) { return; }
if (this.parent.element.querySelector('.e-gridpopup').getElementsByClassName('e-sortdirect').length) {
(this.parent.element.querySelector('.e-gridpopup') as HTMLElement).style.display = 'none';
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (!(<any>this.parent).refreshing && (this.parent.isDestroyed || !this.parent.allowSorting)) {
this.clearSorting();
}
this.isModelChanged = true;
this.removeEventListener();
}
private cancelBeginEvent(e: { requestType: string }): void {
if (e.requestType === 'sorting') {
this.restoreSettings();
this.refreshSortIcons();
this.isMultiSort = true;
}
}
private clickHandler(e: MouseEvent): void {
const gObj: IGrid = this.parent;
this.currentTarget = null;
this.popUpClickHandler(e);
const target: Element = closest(e.target as Element, '.e-headercell');
if (target && !(e.target as Element).classList.contains('e-grptogglebtn') &&
!(target.classList.contains('e-resized')) &&
!(e.target as Element).classList.contains('e-rhandler') &&
!(e.target as Element).classList.contains('e-columnmenu') &&
!(e.target as Element).classList.contains('e-filtermenudiv') &&
!parentsUntil(e.target as Element, 'e-stackedheadercell') &&
!(gObj.allowSelection && gObj.selectionSettings.allowColumnSelection &&
(e.target as Element).classList.contains('e-headercell'))) {
const gObj: IGrid = this.parent;
const colObj: Column = gObj.getColumnByUid(target.querySelector('.e-headercelldiv').getAttribute('e-mappinguid')) as Column;
if (colObj.type !== 'checkbox') {
this.initiateSort(target, e, colObj);
if (Browser.isDevice) {
this.showPopUp(e);
}
}
}
if (target) {
target.classList.remove('e-resized');
}
if (parentsUntil(e.target as Element, 'e-excel-ascending') ||
parentsUntil(e.target as Element, 'e-excel-descending')) {
const colUid: string = (<EJ2Intance>closest(e.target as Element, '.e-filter-popup')).getAttribute('uid');
const direction: SortDirection = isNullOrUndefined(parentsUntil(e.target as Element, 'e-excel-descending')) ?
'Ascending' : 'Descending';
this.sortColumn(gObj.getColumnByUid(colUid).field, direction, false);
}
}
private keyPressed(e: KeyboardEventArgs): void {
const ele: Element = e.target as Element;
if (!this.parent.isEdit && (e.action === 'enter' || e.action === 'ctrlEnter' || e.action === 'shiftEnter')
&& closest(ele as Element, '.e-headercell')) {
const target: Element = this.focus.getFocusedElement();
if (isNullOrUndefined(target) || !target.classList.contains('e-headercell')
|| !target.querySelector('.e-headercelldiv')) { return; }
const col: Column = this.parent.getColumnByUid(target.querySelector('.e-headercelldiv').getAttribute('e-mappinguid')) as Column;
this.initiateSort(target, e, col);
}
}
private initiateSort(target: Element, e: MouseEvent | KeyboardEventArgs, column: Column): void {
const gObj: IGrid = this.parent;
const field: string = column.field;
this.currentTarget = e.target as Element;
const direction: SortDirection = !target.getElementsByClassName('e-ascending').length ? 'Ascending' :
'Descending';
this.isMultiSort = e.ctrlKey || this.enableSortMultiTouch ||
(navigator.userAgent.indexOf('Mac OS') !== -1 && e.metaKey);
if (e.shiftKey || (this.sortSettings.allowUnsort && target.getElementsByClassName('e-descending').length)
&& !(gObj.groupSettings.columns.indexOf(field) > -1)) {
this.removeSortColumn(field);
} else {
this.sortColumn(field, direction, this.isMultiSort);
}
}
private showPopUp(e: MouseEvent): void {
const target: HTMLElement = closest(e.target as Element, '.e-headercell') as HTMLElement;
if (this.parent.allowMultiSorting && (!isNullOrUndefined(target) || this.parent.isContextMenuOpen())) {
setCssInGridPopUp(
<HTMLElement>this.parent.element.querySelector('.e-gridpopup'), e,
'e-sortdirect e-icons e-icon-sortdirect' + (this.sortedColumns.length > 1 ? ' e-spanclicked' : ''));
}
}
private popUpClickHandler(e: MouseEvent): void {
const target: Element = e.target as Element;
if (closest(target, '.e-headercell') || (e.target as HTMLElement).classList.contains(literals.rowCell) ||
closest(target, '.e-gridpopup')) {
if (target.classList.contains('e-sortdirect')) {
if (!target.classList.contains('e-spanclicked')) {
target.classList.add('e-spanclicked');
this.enableSortMultiTouch = true;
} else {
target.classList.remove('e-spanclicked');
this.enableSortMultiTouch = false;
(this.parent.element.querySelector('.e-gridpopup') as HTMLElement).style.display = 'none';
}
}
} else {
(this.parent.element.querySelector('.e-gridpopup') as HTMLElement).style.display = 'none';
}
}
private addSortIcons(): void {
const gObj: IGrid = this.parent;
let header: Element;
let filterElement: Element;
const cols: SortDescriptorModel[] = this.sortSettings.columns;
const fieldNames: string[] = this.parent.getColumns().map((c: Column) => c.field);
for (let i: number = 0, len: number = cols.length; i < len; i++) {
header = gObj.getColumnHeaderByField(cols[i].field);
if (fieldNames.indexOf(cols[i].field) === -1 || isNullOrUndefined(header)) { continue; }
this.aria.setSort(<HTMLElement>header, (cols[i].direction).toLowerCase() as SortDirection);
if (this.isMultiSort && cols.length > 1) {
header.querySelector('.e-headercelldiv').insertBefore(
this.parent.createElement('span', { className: 'e-sortnumber', innerHTML: (i + 1).toString() }),
header.querySelector('.e-headertext'));
}
filterElement = header.querySelector('.e-sortfilterdiv');
if (cols[i].direction === 'Ascending') {
classList(filterElement, ['e-ascending', 'e-icon-ascending'], []);
} else {
classList(filterElement, ['e-descending', 'e-icon-descending'], []);
}
}
}
private removeSortIcons(position?: number): void {
const gObj: IGrid = this.parent;
let header: Element;
const cols: SortDescriptorModel[] = this.sortSettings.columns;
const fieldNames: string[] = this.parent.getColumns().map((c: Column) => c.field);
for (let i: number = position ? position : 0,
len: number = !isNullOrUndefined(position) ? position + 1 : cols.length; i < len; i++) {
header = gObj.getColumnHeaderByField(cols[i].field);
if (isNullOrUndefined(header) || (gObj.allowGrouping && gObj.groupSettings.columns.indexOf(cols[i].field) > -1 &&
!header.querySelector('.e-sortfilterdiv'))) {
continue;
}
if (fieldNames.indexOf(cols[i].field) === -1) { continue; }
this.aria.setSort(<HTMLElement>header, 'none');
classList(
header.querySelector('.e-sortfilterdiv'), [], ['e-descending', 'e-icon-descending', 'e-ascending', 'e-icon-ascending']);
if (header.querySelector('.e-sortnumber')) {
header.querySelector('.e-headercelldiv').removeChild(header.querySelector('.e-sortnumber'));
}
}
}
private getSortColumnFromField(field: string): SortDescriptorModel {
for (let i: number = 0, len: number = this.sortSettings.columns.length; i < len; i++) {
if (this.sortSettings.columns[i].field === field) {
return this.sortSettings.columns[i];
}
}
return false as SortDescriptorModel;
}
private updateAriaAttr(): void {
const fieldNames: string[] = this.parent.getColumns().map((c: Column) => c.field);
for (const col of this.sortedColumns) {
if (fieldNames.indexOf(col) === -1) { continue; }
const header: Element = this.parent.getColumnHeaderByField(col);
this.aria.setSort(<HTMLElement>header, this.getSortColumnFromField(col).direction);
}
}
private refreshSortIcons(params: { args: { isFrozen: boolean } } = { args: { isFrozen: false } }): void {
if (!params.args.isFrozen) {
this.removeSortIcons();
this.isMultiSort = true;
this.removeSortIcons();
this.addSortIcons();
this.isMultiSort = false;
this.updateAriaAttr();
}
}
/**
* To show the responsive custom sort dialog
*
* @param {boolean} enable - specifes dialog open
* @returns {void}
* @hidden
*/
public showCustomSort(enable: boolean): void {
this.responsiveDialogRenderer.isCustomDialog = enable;
this.responsiveDialogRenderer.showResponsiveDialog();
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.