text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
namespace ts.reflection {
/**
* Entry point for type serialization. Chooses the right serialization for the given type, using
* the TypeFlags.
*/
export function writeType(type: Type, checker: TypeChecker, typeCounter: Counter, writer: Writer): Type[] {
writer.write(`${tempTypeVar} = ${localTypeVar}[${type.$info.localIndex}];`).writeLine();
const discoveredTypes: Type[] = [];
const members = type.symbol ? valuesOf<Symbol>(type.symbol.members) : [];
switch (type.flags & allTypeFlagsMask) {
case TypeFlags.StringLiteral:
debug.warn('Detected string literal type. Not supported yet.');
break;
case TypeFlags.TypeParameter:
writeTypeParameter();
break;
case TypeFlags.Union: // let x: T | U;
writeUnionType();
break;
case TypeFlags.Intersection: // let x: T & U;
writeIntersectionType();
break;
case TypeFlags.Never:
debug.warn('Detected never type. Not supported yet.');
break;
case TypeFlags.Object:
writeObjectType();
break;
default:
let name = type.symbol ? type.symbol.name : 'unknown';
debug.warn('exploreType found an unknown type:', name, 'with typeFlags:', type.flags);
}
return discoveredTypes;
function writeObjectType() {
let objectType = <ObjectType>type;
switch (objectType.objectFlags) {
case ObjectFlags.Class:
case ObjectFlags.Reference | ObjectFlags.Class:
writeClassType();
break;
case ObjectFlags.Interface:
case ObjectFlags.Reference | ObjectFlags.Interface:
writeInterfaceType();
break;
case ObjectFlags.Reference:
writeTypeReference();
break;
case ObjectFlags.Tuple: // let x: [string, number];
case ObjectFlags.Reference | ObjectFlags.Tuple:
debug.warn('Detected tuple type. Not supported yet.');
break;
case ObjectFlags.Anonymous:
writeAnonymousType();
break;
}
}
/**
* Class type serialization. Uses writeTypeDetails(), in common with interfaces.
* Writes serialization kind, implements and extends clause, static properties and methods.
*/
function writeClassType() {
writeTypeKind(SerializedTypeKind.Class);
writeTypeDetails();
writeHeritageClauseElements('implements', getClassImplementsNodes);
writeClassExtends();
writeStaticMembers();
}
/**
* Interface type serialization. Uses writeTypeDetails(), in common with classes.
* Writes serialization kind and extends clause
*/
function writeInterfaceType() {
writeTypeKind(SerializedTypeKind.Interface);
writeTypeDetails();
writeHeritageClauseElements('extends', getInterfaceBaseTypeNodes);
}
/**
* Writes all class/interface type details: name, type parameters, properties,
* methods, constructors, call signatures, index signatures.
*/
function writeTypeDetails() {
writeTypeName();
writeTypeParameters();
writeMembers();
writeConstructors();
writeCallSignatures();
writeIndexSignatures();
}
/**
* Writes properties and methods.
*/
function writeMembers() {
let filteredMembers = members.filter(symbol =>
(symbol.flags & SymbolFlags.Property) || (symbol.flags & SymbolFlags.Method));
if (filteredMembers.length > 0) {
writeTypeProperty('members').write(' = ').writeArrayStart();
for (let symbol of filteredMembers) {
writeMemberSymbol(symbol);
}
writer.writeArrayEnd().write(';').writeLine();
}
}
/**
* Writes static properties and methods.
*/
function writeStaticMembers() {
if (type.symbol.declarations && type.symbol.declarations.length > 0) {
let declaration = <ClassLikeDeclaration>type.symbol.declarations[0];
let statics = declaration.members.filter(member => getModifierFlags(member) & ModifierFlags.Static);
if (statics.length > 0) {
writeTypeProperty('statics').write(' = ').writeArrayStart();
for (let member of statics) {
let symbol = checker.getSymbolAtLocation(member.name);
writeMemberSymbol(symbol);
}
writer.writeArrayEnd().write(';').writeLine();
}
}
}
function writeMemberSymbol(symbol: Symbol) {
writer.writeObjectStart()
.write(`name: '${symbol.name}',`).writeLine()
.write('type: ')
if (symbol.flags & SymbolFlags.Property) {
writeReferenceToTypeForNode(symbol.valueDeclaration).write(',').writeLine();
} else if (symbol.flags & SymbolFlags.Method) {
writeMethodMember(symbol).write(',').writeLine();
}
if (symbol.flags & SymbolFlags.Optional) {
writer.write('optional: true,').writeLine();
}
writer.writeObjectEnd().write(`,`).writeLine();
}
/**
* Writes constructors.
*/
function writeConstructors() {
let filteredMembers = members.filter(symbol => symbol.flags === SymbolFlags.Constructor || (
symbol.flags === SymbolFlags.Signature &&
(symbol.declarations[0].kind === SyntaxKind.ConstructSignature ||
symbol.declarations[0].kind === SyntaxKind.ConstructorType)
));
if (filteredMembers.length > 0) {
writeTypeProperty('construct').write(' = ').writeArrayStart();
writeSignatures(filteredMembers);
writer.writeArrayEnd().write(';').writeLine();
}
}
/**
* Writes call signatures.
*/
function writeCallSignatures() {
let filteredMembers = members.filter(symbol =>
(symbol.flags & SymbolFlags.Signature) &&
(symbol.declarations[0].kind === SyntaxKind.CallSignature ||
symbol.declarations[0].kind === SyntaxKind.FunctionType));
if (filteredMembers.length > 0) {
writeTypeProperty('call').write(' = ').writeArrayStart();
writeSignatures(filteredMembers);
writer.writeArrayEnd().write(';').writeLine();
}
}
/**
* Writes index signatures.
*/
function writeIndexSignatures() {
let filteredMembers = members.filter(symbol =>
(symbol.flags & SymbolFlags.Signature) &&
symbol.declarations[0].kind === SyntaxKind.IndexSignature);
if (filteredMembers.length > 0) {
writeTypeProperty('index').write(' = ').writeArrayStart();
writeSignatures(filteredMembers);
writer.writeArrayEnd().write(';').writeLine();
}
}
/**
* Writes references to type parameters.
*/
function writeTypeParameters() {
let filteredMembers = members.filter(symbol => symbol.flags & SymbolFlags.TypeParameter);
if (filteredMembers.length > 0) {
writeTypeProperty('typeParameters').write(' = ').writeArrayStart(true);
for (let symbol of filteredMembers) {
writeReferenceToTypeForNode(symbol.declarations[0]).write(`, `);
}
writer.writeArrayEnd(true).write(';').writeLine();
}
}
/**
* Writes a type parameter, that can referenced by other types
*/
function writeTypeParameter() {
let typeParam = <TypeParameter>type;
writeTypeName();
writeTypeKind(SerializedTypeKind.Parameter);
if (typeParam.symbol.declarations) {
let declaration = <TypeParameterDeclaration>typeParam.symbol.declarations[0];
if (declaration.constraint) {
writeTypeProperty('constraint').write(` = `);
writeReferenceToTypeForNode(declaration.constraint).write(';').writeLine();
}
}
}
/**
* Writes a reference to the variable that holds metadata for the type of the given node.
*/
function writeReferenceToTypeForNode(node: Node) {
return writeReferenceToType(checker.getTypeAtLocation(node));
}
/**
* Writes a method of a class/interface.
*/
function writeMethodMember(symbol: Symbol) {
writer.writeObjectStart();
writer.write(`kind: 'function',`).writeLine()
.write(`name: '${symbol.name}', `).writeLine()
.write(`signatures: `).writeArrayStart();
writeSignatures([symbol]);
return writer.writeArrayEnd().writeObjectEnd();
}
/**
* Writes signatures.
*/
function writeSignatures(symbols: Symbol[]) {
let declarations: FunctionLikeDeclaration[];
let signature: Signature;
for (let symbol of symbols) {
declarations = <FunctionLikeDeclaration[]>symbol.declarations;
for (let declaration of declarations) {
signature = checker.getSignatureFromDeclaration(declaration);
writeSignature(signature, declaration);
writer.write(',').writeLine();
}
}
}
/**
* Writes signature details.
*/
function writeSignature(signature: Signature, declaration: FunctionLikeDeclaration) {
writer.writeObjectStart();
let hasRestParam = declaration.parameters.length > 0 &&
declaration.parameters[declaration.parameters.length - 1].dotDotDotToken;
let length = hasRestParam ? declaration.parameters.length - 1 : declaration.parameters.length;
let returnType = checker.getReturnTypeOfSignature(signature);
writer.write(`length: ${length},`).writeLine()
.write(`parameters: `).writeArrayStart(!declaration.parameters.length);
for (let parameter of declaration.parameters) {
writer.writeObjectStart(true)
.write(`name: '${(<Identifier>parameter.name).text}', type: `) //TODO: check this! name can be Identifier or BindingPattern (what is BindingPattern?)
writeReferenceToTypeForNode(parameter)
.writeObjectEnd(true).write(',').writeLine();
}
writer.writeArrayEnd(!declaration.parameters.length).write(',').writeLine();
if (signature.typeParameters && signature.typeParameters.length > 0) {
writer.write(`typeParameters: `).writeArrayStart(true);
for (let parameter of signature.typeParameters) {
writeReferenceToType(parameter).write(', ');
}
writer.writeArrayEnd(true).write(',').writeLine();
}
if (returnType) {
writer.write(`returns: `);
writeReferenceToType(returnType).write(', ').writeLine();
}
if (hasRestParam) {
writer.write(`rest: true`).writeLine();
}
writer.writeObjectEnd();
}
/**
* Writes class extends clause.
*/
function writeClassExtends() {
let baseClass = getClassExtendsHeritageClause();
if (baseClass) {
writeTypeProperty('extends').write(` = `);
writeReferenceToTypeForNode(baseClass).write(';').writeLine();
}
}
/**
* Utility function shared by class implements clause writer and interface extends clause writer.
*/
function writeHeritageClauseElements(propertyName: string, heritageClauseFilter: (d: ClassLikeDeclaration | InterfaceDeclaration) => NodeArray<TypeNode>) {
const heritageClausesTypes = getHeritageClauses(type, heritageClauseFilter);
if (heritageClausesTypes && heritageClausesTypes.length > 0) {
writeTypeProperty(propertyName).write(` = [`);
for (let clause of heritageClausesTypes) {
writeReferenceToType(clause).write(', ');
}
writer.write(`];`).writeLine();
}
}
function writeTypeName(): Writer {
return writeTypeProperty('name').write(` = '${type.$info.name}';`).writeLine();
}
function writeTypeKind(kind: string): Writer {
return writeTypeProperty('kind').write(` = '${kind}';`).writeLine();
}
function writeTypeProperty(propertyName: string): Writer {
return writer.write(`${tempTypeVar}.${propertyName}`);
}
function getHeritageClauses(type: Type, searchFn: (d: InterfaceDeclaration) => TypeNode[]): Type[] {
let clauses: Type[] = [];
let set: any = {};
let searchResults: TypeNode[];
for (let declaration of type.symbol.declarations) {
searchResults = searchFn(<InterfaceDeclaration>declaration);
if (searchResults && searchResults.length > 0) {
for (let result of searchResults) {
if (!set[result.id]) {
set[result.id] = true;
clauses.push(checker.getTypeAtLocation(result));
}
}
}
}
return clauses;
}
function getClassImplementsNodes(declaration: ClassLikeDeclaration) {
let result = getClassImplementsHeritageClauseElements(declaration) || <NodeArray<TypeNode>>[];
//When an interface with the same name of a class extends one (or more) base interface(s),
//these are included as extends heritage clauses.
var tmp: NodeArray<TypeNode>;
for (let declaration of type.symbol.declarations) {
tmp = getInterfaceBaseTypeNodes(<InterfaceDeclaration>declaration);
if (tmp) {
result = <NodeArray<TypeNode>>result.concat(tmp);
}
}
return result.length > 0 ? result : null;
}
function getClassExtendsHeritageClause(): TypeNode {
let result: TypeNode;
for (let declaration of type.symbol.declarations) {
result = getClassExtendsHeritageClauseElement(<ClassLikeDeclaration>declaration);
if (result) {
return (<ObjectType>checker.getTypeAtLocation(result)).objectFlags & ObjectFlags.Class ? result : null;
}
}
return null;
}
function writeTypeReference() {
let ref = <TypeReference>type;
if (isArrayType(type)) { //why this distinction? array should be nothing special... TBD
writeTypeKind(SerializedTypeKind.Array);
writeTypeProperty('elementType').write(' = ');
writeReferenceToType(ref.typeArguments[0]).write(';').writeLine();
} else {
writeTypeKind(SerializedTypeKind.Reference);
writeTypeProperty('type').write(' = ');
writeReferenceToType(ref.target).write(';').writeLine();
if (ref.typeArguments) {
writeTypeProperty(`typeParameters`).write(' = ').writeArrayStart(true);
for (let argument of ref.typeArguments) {
writeReferenceToType(argument).write(', ');
}
writer.writeArrayEnd(true).write(';').writeLine();
}
}
}
function writeUnionType() {
writeTypeKind(SerializedTypeKind.Union);
writeUnionOrIntersectionTypes();
}
function writeIntersectionType() {
writeTypeKind(SerializedTypeKind.Intersection);
writeUnionOrIntersectionTypes();
}
function writeUnionOrIntersectionTypes() {
let unionOrIntersection = <UnionOrIntersectionType>type;
writeTypeProperty('types').write(' = ').writeArrayStart(true);
for(let type of unionOrIntersection.types) {
writeReferenceToType(type).write(', ');
}
writer.writeArrayEnd(true).write(';').writeLine();
}
function writeAnonymousType() {
switch (type.symbol.flags) { //TODO: filter with bitmask
case ts.SymbolFlags.ObjectLiteral:
debug.warn('Detected object literal type. Not supported yet.');
//todo;
break;
case ts.SymbolFlags.Class:
writeClassExpression();
break;
case ts.SymbolFlags.TypeLiteral:
writeTypeLiteral();
break;
default:
debug.warn('Unknown anonymous type with symbolFlags:', type.symbol.flags);
}
}
function writeTypeLiteral() {
writeTypeKind(SerializedTypeKind.Alias);
writeTypeName();
writeConstructors();
writeMembers();
writeCallSignatures();
writeIndexSignatures();
}
function writeClassExpression() {
writeTypeKind(SerializedTypeKind.ClassExpression);
writeTypeProperty('type').write(' = ');
let targetType = checker.getDeclaredTypeOfSymbol(type.symbol);
writeReferenceToType(targetType).write(';').writeLine();
}
function writeReferenceToType(type: Type): Writer {
let intrinsicType = getIntrinsicType(type.flags);
if (intrinsicType) {
return writer.write(intrinsicType.varName);
}
if (!type.$info) {
//first time we see this node. Enqueue it for later inspection.
addReflectionInfo(type, typeCounter);
discoveredTypes.push(type);
}
return writer.write(`${localTypeVar}[${type.$info.localIndex}]`)
}
}
function isArrayType(type: ts.Type) {
let ref = <TypeReference>type;
return ref.target &&
ref.target.symbol &&
ref.target.symbol.name === 'Array' &&
ref.target.typeParameters &&
ref.target.typeParameters.length === 1;
}
} | the_stack |
import glob from 'fast-glob';
import fs from 'fs-extra';
import { isObject, Memoize, optimal, PackageStructure, Path, toArray } from '@boost/common';
import { createDebugger, Debugger } from '@boost/debug';
import { Artifact } from './Artifact';
import { CodeArtifact } from './CodeArtifact';
import {
DEFAULT_FORMATS,
FORMATS_BROWSER,
FORMATS_NATIVE,
FORMATS_NODE,
NODE_SUPPORTED_VERSIONS,
NPM_SUPPORTED_VERSIONS,
SUPPORT_PRIORITY,
} from './constants';
import { loadModule } from './helpers/loadModule';
import { Project } from './Project';
import { packemonBlueprint } from './schemas';
import {
BuildOptions,
FeatureFlags,
InputMap,
PackageConfig,
PackageExports,
PackemonPackage,
PackemonPackageConfig,
TSConfigStructure,
} from './types';
import { TypesArtifact } from './TypesArtifact';
export class Package {
readonly artifacts: Artifact[] = [];
readonly configs: PackageConfig[] = [];
readonly debug!: Debugger;
readonly packageJson: PackemonPackage;
readonly packageJsonPath: Path;
readonly path: Path;
readonly project: Project;
root: boolean = false;
constructor(project: Project, path: Path, contents: PackemonPackage) {
this.project = project;
this.path = path;
this.packageJsonPath = this.path.append('package.json');
this.packageJson = contents;
this.debug = createDebugger(['packemon', 'package', this.getSlug()]);
}
addArtifact(artifact: Artifact): Artifact {
this.artifacts.push(artifact);
artifact.startup();
return artifact;
}
async build(options: BuildOptions): Promise<void> {
this.debug('Building artifacts');
// Build artifacts in parallel
await Promise.all(
this.artifacts.map(async (artifact) => {
const start = Date.now();
try {
artifact.state = 'building';
await artifact.build(options);
artifact.state = 'passed';
} catch (error: unknown) {
artifact.state = 'failed';
throw error;
} finally {
artifact.buildResult.time = Date.now() - start;
}
}),
);
// Add package entry points based on artifacts
this.addEntryPoints();
// Add package `engines` based on artifacts
if (options.addEngines) {
this.addEngines();
}
// Add package `exports` based on artifacts
if (options.addExports) {
this.addExports();
}
// Sync `package.json` in case it was modified
await this.syncPackageJson();
}
async cleanup(): Promise<void> {
this.debug('Cleaning build artifacts');
await Promise.all(this.artifacts.map((artifact) => artifact.cleanup()));
}
getName(): string {
return this.packageJson.name;
}
@Memoize()
// eslint-disable-next-line complexity
getFeatureFlags(): FeatureFlags {
this.debug('Loading feature flags');
const flags: FeatureFlags =
this.root || !this.project.isWorkspacesEnabled()
? {}
: this.project.rootPackage.getFeatureFlags();
flags.workspaces = this.project.workspaces;
// React
if (this.project.rootPackage.hasDependency('react') || this.hasDependency('react')) {
flags.react = true;
this.debug(' - React');
}
// TypeScript
const tsConfig = this.tsconfigJson ?? this.project.rootPackage.tsconfigJson;
if (
this.project.rootPackage.hasDependency('typescript') ||
this.hasDependency('typescript') ||
tsConfig
) {
flags.typescript = true;
flags.decorators = Boolean(tsConfig?.options.experimentalDecorators);
flags.strict = Boolean(tsConfig?.options.strict);
this.debug(
' - TypeScript (%s, %s)',
flags.strict ? 'strict' : 'non-strict',
flags.decorators ? 'decorators' : 'non-decorators',
);
}
// Flow
const flowconfigPath = this.project.root.append('.flowconfig');
if (
this.project.rootPackage.hasDependency('flow-bin') ||
this.hasDependency('flow-bin') ||
flowconfigPath.exists()
) {
flags.flow = true;
this.debug(' - Flow');
}
return flags;
}
getSlug(): string {
return this.path.name(true);
}
@Memoize()
getSourceFiles(): string[] {
return glob.sync('src/**/*.{js,jsx,ts,tsx}', {
absolute: true,
cwd: this.path.path(),
onlyFiles: true,
});
}
hasDependency(name: string): boolean {
const pkg = this.packageJson;
return Boolean(
pkg.dependencies?.[name] ??
pkg.devDependencies?.[name] ??
pkg.peerDependencies?.[name] ??
pkg.optionalDependencies?.[name],
);
}
isComplete(): boolean {
return this.artifacts.every((artifact) => artifact.isComplete());
}
isRunning(): boolean {
return this.artifacts.some((artifact) => artifact.isRunning());
}
setConfigs(configs: PackemonPackageConfig[]) {
configs.forEach((cfg) => {
const config = optimal(cfg, packemonBlueprint, {
name: this.getName(),
});
toArray(config.platform).forEach((platform) => {
let { bundle } = config;
let formats = [...toArray(config.format)];
const isEmpty = formats.length === 0;
switch (platform) {
case 'native':
if (isEmpty) {
formats.push(...DEFAULT_FORMATS.native);
} else {
formats = formats.filter((format) => (FORMATS_NATIVE as string[]).includes(format));
}
break;
case 'node':
if (cfg.bundle === undefined) {
bundle = false;
}
if (isEmpty) {
formats.push(...DEFAULT_FORMATS.node);
} else {
formats = formats.filter((format) => (FORMATS_NODE as string[]).includes(format));
}
break;
case 'browser':
default:
if (isEmpty) {
formats.push(...DEFAULT_FORMATS.browser);
if (config.namespace) {
formats.push('umd');
}
} else {
formats = formats.filter((format) => (FORMATS_BROWSER as string[]).includes(format));
}
break;
}
this.configs.push({
bundle,
externals: toArray(config.externals),
formats,
inputs: config.inputs,
namespace: config.namespace,
platform,
support: config.support,
});
});
});
}
async syncPackageJson() {
await fs.writeJson(this.packageJsonPath.path(), this.packageJson, { spaces: 2 });
}
@Memoize()
get tsconfigJson(): TSConfigStructure | undefined {
const tsconfigJsonPath = this.path.append('tsconfig.json');
if (!tsconfigJsonPath.exists()) {
return undefined;
}
const ts = loadModule(
'typescript',
'TypeScript is required for config loading.',
) as typeof import('typescript');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { config, error } = ts.readConfigFile(tsconfigJsonPath.path(), (name) =>
fs.readFileSync(name, 'utf8'),
);
const host = {
getCanonicalFileName: (fileName: string) => fileName,
getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
getNewLine: () => ts.sys.newLine,
};
// istanbul ignore next
if (error) {
throw new Error(ts.formatDiagnostic(error, host));
}
const result = ts.parseJsonConfigFileContent(
config,
ts.sys,
this.path.path(),
{},
tsconfigJsonPath.path(),
);
// istanbul ignore next
if (result.errors.length > 0) {
throw new Error(ts.formatDiagnostics(result.errors, host));
}
return result;
}
protected addEngines() {
const artifact = (this.artifacts as CodeArtifact[])
.filter((art) => art instanceof CodeArtifact)
.filter((art) => art.platform === 'node')
.reduce<CodeArtifact | null>(
(oldest, art) =>
!oldest || SUPPORT_PRIORITY[art.support] < SUPPORT_PRIORITY[oldest.support]
? art
: oldest,
null,
);
if (!artifact) {
return;
}
this.debug('Adding `engines` to `package.json`');
const pkg = this.packageJson;
if (!pkg.engines) {
pkg.engines = {};
}
Object.assign(pkg.engines, {
node: `>=${NODE_SUPPORTED_VERSIONS[artifact.support]}`,
npm: toArray(NPM_SUPPORTED_VERSIONS[artifact.support])
.map((v) => `>=${v}`)
.join(' || '),
});
}
protected addEntryPoints() {
this.debug('Adding entry points to `package.json`');
let mainEntry = '';
let moduleEntry = '';
let browserEntry = '';
const files = new Set<string>(this.packageJson.files);
// eslint-disable-next-line complexity
this.artifacts.forEach((artifact) => {
// Build files
if (artifact instanceof CodeArtifact) {
// Generate `main`, `module`, and `browser` fields
if (artifact.inputs.index) {
if (!mainEntry || artifact.platform === 'node') {
mainEntry = artifact.findEntryPoint(['lib', 'cjs', 'mjs', 'esm'], 'index');
}
if (!moduleEntry) {
moduleEntry = artifact.findEntryPoint(['esm', 'mjs'], 'index');
}
// Only include when we share a lib with another platform
if (!browserEntry && artifact.platform === 'browser') {
browserEntry = artifact.findEntryPoint(
artifact.sharedLib ? ['lib', 'umd'] : ['umd'],
'index',
);
}
}
// Generate `bin` field
if (
artifact.inputs.bin &&
artifact.platform === 'node' &&
!isObject(this.packageJson.bin)
) {
this.packageJson.bin = artifact.findEntryPoint(['lib', 'cjs', 'mjs'], 'bin');
}
// Generate `files` list
artifact.builds.forEach(({ format }) => {
files.add(`${format}/**/*.{${artifact.getBuildOutput(format).ext},map}`);
});
files.add(`src/**/*.{${this.getSourceFileExts(artifact.inputs)}}`);
}
// Type declarations
if (artifact instanceof TypesArtifact) {
this.packageJson.types = artifact.findEntryPoint('index');
files.add('dts/**/*.d.ts');
}
});
if (mainEntry) {
this.packageJson.main = mainEntry;
if (mainEntry.includes('mjs/') || mainEntry.includes('esm/')) {
this.packageJson.type = 'module';
} else if (mainEntry.includes('cjs/')) {
this.packageJson.type = 'commonjs';
}
}
if (moduleEntry) {
this.packageJson.module = moduleEntry;
}
if (browserEntry && !isObject(this.packageJson.browser)) {
this.packageJson.browser = browserEntry;
}
this.packageJson.files = [...files].sort();
}
protected addExports() {
this.debug('Adding `exports` to `package.json`');
const exportMap: PackageExports = {
'./package.json': './package.json',
};
this.artifacts.forEach((artifact) => {
Object.entries(artifact.getPackageExports()).forEach(([basePath, conditions]) => {
const path = basePath.replace('/index', '');
if (!exportMap[path]) {
exportMap[path] = {};
} else if (typeof exportMap[path] === 'string') {
exportMap[path] = { default: exportMap[path] };
}
Object.assign(exportMap[path], conditions);
});
});
if (isObject(this.packageJson.exports)) {
Object.assign(this.packageJson.exports, exportMap);
} else {
this.packageJson.exports = exportMap as PackageStructure['exports'];
}
}
protected getSourceFileExts(inputs: InputMap): string[] {
const sourceExts = Object.values(inputs).map((inputFile) => new Path(inputFile).ext(true));
const exts = new Set(sourceExts);
// Include sibling file extensions
sourceExts.forEach((sourceExt) => {
switch (sourceExt) {
case 'js':
exts.add('jsx');
break;
case 'jsx':
case 'cjs':
exts.add('js');
break;
case 'ts':
exts.add('tsx');
break;
case 'tsx':
exts.add('ts');
break;
// no default
}
});
const list = [...exts].sort();
// Always be last
list.push('json');
return list;
}
} | the_stack |
import * as BlinkDiff from "blink-diff";
import * as PngJsImage from "pngjs-image";
import { ImageOptions } from "./image-options";
import { INsCapabilities } from "./interfaces/ns-capabilities";
import { IRectangle } from "./interfaces/rectangle";
import { LogImageType } from "./enums/log-image-type";
import { UIElement } from "./ui-element";
import { AppiumDriver } from "./appium-driver";
import { logError, checkImageLogType, resolvePath, copy, addExt, logWarn } from "./utils";
import { unlinkSync, existsSync, mkdirSync } from "fs";
import { basename, join } from "path";
import { isObject, isNumber } from "util";
import { logInfo } from "mobile-devices-controller/lib/utils";
export interface IImageCompareOptions {
imageName?: string;
timeOutSeconds?: number;
/**
* pixel
* percentage thresholds: 1 = 100%, 0.2 = 20%"
*/
tolerance?: number;
/**
* pixel
* percentage thresholds: 1 = 100%, 0.2 = 20%"
*/
toleranceType?: ImageOptions;
/**
* Wait milliseconds before capture creating image
* Default value is 5000
*/
waitBeforeCreatingInitialImageCapture?: number;
/**
* This property will preserve not to add be added _actual postfix on initial image capture
*/
donNotAppendActualSuffixOnIntialImageCapture?: boolean;
/**
* This property will ensure that the image name will not be manipulated with count postfix.
* This is very convenient in order to reuses image.
* Default value is false.
*/
keepOriginalImageName?: boolean;
/**
* Clip image before compare. Default value excludes status bar(both android and ios) and software buttons(android).
*/
cropRectangle?: IRectangle;
/**
* Default value is set to true which means that nativescript-dev-appium will save the image
* in original size and compare only the part which cropRectangle specifies.
* If false, the image size will be reduced and saved by the dimensions of cropRectangle.
*/
keepOriginalImageSize?: boolean;
/**
* Default value is set to false. nativescript-dev-appium will recalculate view port for iOS
* so that the top/y will start from the end of the status bar
* So far appium calculates it even more and some part of safe areas are missed
*/
keepAppiumViewportRect?: boolean;
/**
* Defines if an image is device-specific or only by the platform.
* Default value is true and the image will be saved in device-specific directory.
* If the value is set to false, the image will be saved under ios or android folder.
*/
isDeviceSpecific?: boolean;
/**
* Overwrite actual image if doesn't match. Default value is false.
*/
overwriteActualImage?: boolean;
}
export class ImageHelper {
private _blockOutAreas: IRectangle[];
private _imagesResults = new Map<string, boolean>();
private _options: IImageCompareOptions = {};
private _defaultToleranceType: ImageOptions = ImageOptions.percent;
private _defaultTolerance: number = 0;
private _defaultOptions: IImageCompareOptions = {
timeOutSeconds: 2,
tolerance: 0,
toleranceType: ImageOptions.pixel,
waitBeforeCreatingInitialImageCapture: 5000,
donNotAppendActualSuffixOnIntialImageCapture: false,
keepOriginalImageSize: true,
keepOriginalImageName: false,
isDeviceSpecific: true,
cropRectangle: {},
imageName: undefined,
overwriteActualImage: false,
};
constructor(private _args: INsCapabilities, private _driver: AppiumDriver) {
if (this._args.device.viewportRect) {
ImageHelper.fullClone(this._args.device.viewportRect, this._defaultOptions.cropRectangle)
}
if (!this._defaultOptions.cropRectangle
|| !isNumber(this._defaultOptions.cropRectangle.y) || this._args.appiumCaps.offsetPixels > 0) {
this._defaultOptions.cropRectangle = this._defaultOptions.cropRectangle || {};
this._defaultOptions.cropRectangle.y = this._args.appiumCaps.offsetPixels || this._args.device.config.offsetPixels || 0;
this._defaultOptions.cropRectangle.x = 0;
if (this._args.device.deviceScreenSize && this._args.device.deviceScreenSize.width && this._args.device.deviceScreenSize.height) {
this._defaultOptions.cropRectangle.height = this._args.device.deviceScreenSize.height - this._defaultOptions.cropRectangle.y;
this._defaultOptions.cropRectangle.width = this._args.device.deviceScreenSize.width - this._defaultOptions.cropRectangle.x;
}
}
ImageHelper.fullClone(this._defaultOptions, this._options);
logInfo(`Actual view port:`, this._options);
}
public static readonly pngFileExt = '.png';
public testName: string;
/**
* Defines when an image output should be created.
* This can be for different images, similar or different images, or all comparisons.
* (default: BlinkDiff.OUTPUT_ALL)
*/
public imageOutputLimit = ImageOptions.outputAll;
/**
* Max. distance colors in the 4 dimensional color-space without triggering a difference. (default: 20)
*/
public delta: number = 20;
get options() {
return this._options;
}
set options(options: IImageCompareOptions) {
this._options = this.extendOptions(options);
}
get blockOutAreas() {
return this._blockOutAreas;
}
set blockOutAreas(rectangles: IRectangle[]) {
this._blockOutAreas = rectangles;
}
get defaultToleranceType(): ImageOptions {
return this._defaultToleranceType;
}
set defaultToleranceType(toleranceType: ImageOptions) {
this._defaultToleranceType = toleranceType;
}
get defaultTolerance(): number {
return this._defaultTolerance;
}
set defaultTolerance(tolerance: number) {
this._defaultTolerance = tolerance;
}
public async compareScreen(options?: IImageCompareOptions) {
options = this.extendOptions(options);
options.imageName = this.increaseImageName(options.imageName || this.testName, options);
const result = await this.compare(options);
this._imagesResults.set(options.imageName, result);
return result;
}
public async compareElement(element: UIElement, options?: IImageCompareOptions) {
options = this.extendOptions(options);
options.imageName = this.increaseImageName(options.imageName || this.testName, options);
const cropRectangle = await element.getActualRectangle();
const result = await this.compareRectangle(cropRectangle, options);
return result;
}
public async compareRectangle(cropRectangle: IRectangle, options?: IImageCompareOptions) {
options = this.extendOptions(options);
options.imageName = this.increaseImageName(options.imageName || this.testName, options);
options.cropRectangle = cropRectangle;
const result = await this.compare(options);
this._imagesResults.set(options.imageName, result);
return result;
}
public hasImageComparisonPassed() {
let shouldFailTest = true;
console.log();
this._imagesResults.forEach((v, k, map) => {
if (!this._imagesResults.get(k)) {
shouldFailTest = false;
this._driver.testReporterLog(`Image comparison for image ${k} has failed!`);
logError(`Image comparison for image ${k} has failed`);
}
});
this.reset();
return shouldFailTest;
}
/**
* Reset image comparison results
*/
public reset() {
this._imagesResults.clear();
this.testName = undefined;
}
/**
* Set comparison option to default
*/
public resetDefaultOptions() {
ImageHelper.fullClone(this._defaultOptions, this._options);
}
public getExpectedImagePathByDevice(imageName: string) {
let pathExpectedImage = resolvePath(this._args.storageByDeviceName, imageName);
return pathExpectedImage;
}
public getExpectedImagePathByPlatform(imageName: string) {
let pathExpectedImage = resolvePath(this._args.storageByPlatform, imageName);
return pathExpectedImage;
}
public async compare(options: IImageCompareOptions) {
let imageName = addExt(options.imageName, ImageHelper.pngFileExt);
const storageLocal = options.isDeviceSpecific ? this._args.storageByDeviceName : this._args.storageByPlatform;
const pathExpectedImage = options.isDeviceSpecific ? this.getExpectedImagePathByDevice(imageName) : this.getExpectedImagePathByPlatform(imageName);
if (!existsSync(this._args.reportsPath)) {
mkdirSync(this._args.reportsPath);
}
const captureFirstImage = async () => {
const pathActualImage = resolvePath(storageLocal, (this.options.donNotAppendActualSuffixOnIntialImageCapture || this.options.overwriteActualImage) ? imageName : imageName.replace(".", "_actual."));
if (this.options.waitBeforeCreatingInitialImageCapture > 0) {
await this._driver.wait(this.options.waitBeforeCreatingInitialImageCapture);
}
await this._driver.saveScreenshot(pathActualImage);
if (!options.keepOriginalImageSize) {
await this.clipRectangleImage(options.cropRectangle, pathActualImage);
}
const pathActualImageToReportsFolder = resolvePath(this._args.reportsPath, basename(pathActualImage));
copy(pathActualImage, pathActualImageToReportsFolder, false);
if (this.options.donNotAppendActualSuffixOnIntialImageCapture || this.options.overwriteActualImage) {
logWarn(`New image ${basename(pathActualImage)} is saved to storage ${storageLocal}.`, pathExpectedImage);
} else if (this.options.donNotAppendActualSuffixOnIntialImageCapture === false && this.options.overwriteActualImage === false) {
logWarn("Remove the 'actual' suffix to continue using the image as expected one ", pathExpectedImage);
}
this._args.testReporterLog(basename(pathActualImage).replace(/\.\w{3,3}$/ig, ""));
this._args.testReporterLog(join(this._args.reportsPath, basename(pathActualImage)));
return false;
}
// First time capture
if (!existsSync(pathExpectedImage)) {
await captureFirstImage();
return false;
}
// Compare
let pathActualImage = await this._driver.saveScreenshot(resolvePath(this._args.reportsPath, imageName.replace(".", "_actual.")));
if (!options.keepOriginalImageSize) {
await this.clipRectangleImage(options.cropRectangle, pathActualImage);
}
const pathDiffImage = pathActualImage.replace("actual", "diff");
console.log(`\n Comparing ${pathExpectedImage}`);
// await this.prepareImageToCompare(pathActualImage, options.cropRectangle);
let result = await this.compareImages(options, pathActualImage, pathExpectedImage, pathDiffImage);
// Iterate
if (!result) {
const eventStartTime = Date.now().valueOf();
let counter = 1;
options.timeOutSeconds *= 1000;
let pathActualImageCounter = resolvePath(this._args.reportsPath, imageName.replace(".", "_actual."));
const shouldLogEveryImage = checkImageLogType(this._args.testReporter, LogImageType.everyImage);
while ((Date.now().valueOf() - eventStartTime) <= options.timeOutSeconds && !result) {
if (shouldLogEveryImage) {
pathActualImageCounter = resolvePath(this._args.reportsPath, imageName.replace(".", "_actual_" + counter + "."));
}
pathActualImage = await this._driver.saveScreenshot(pathActualImageCounter);
if (!options.keepOriginalImageSize) {
await this.clipRectangleImage(options.cropRectangle, pathActualImage);
}
// await this.prepareImageToCompare(pathActualImage, this.imageCropRect);
result = await this.compareImages(options, pathActualImage, pathExpectedImage, pathDiffImage);
if (!result && checkImageLogType(this._args.testReporter, LogImageType.everyImage)) {
this._args.testReporterLog(`Actual image: ${basename(pathActualImage).replace(/\.\w{3,3}$/ig, "")}`);
this._args.testReporterLog(join(this._args.reportsPath, basename(pathActualImage)));
}
counter++;
}
if (options.overwriteActualImage === true && !result) {
logError(`Overwrite image ${pathExpectedImage}, since overwriteActualImage option is set to true!`);
await captureFirstImage();
}
if (!result && !checkImageLogType(this._args.testReporter, LogImageType.everyImage)) {
this._args.testReporterLog(`${basename(pathDiffImage).replace(/\.\w{3,3}$/ig, "")}`);
this._args.testReporterLog(join(this._args.reportsPath, basename(pathDiffImage)));
this._args.testReporterLog(`Actual image: ${basename(pathActualImage).replace(/\.\w{3,3}$/ig, "")}`);
this._args.testReporterLog(join(this._args.reportsPath, basename(pathActualImage)));
}
} else {
if (existsSync(pathDiffImage)) {
unlinkSync(pathDiffImage);
}
if (existsSync(pathActualImage)) {
unlinkSync(pathActualImage);
}
}
return result;
}
public compareImages(options: IImageCompareOptions, actual: string, expected: string, output: string) {
const clipRect = {
x: options.cropRectangle.x,
y: options.cropRectangle.y,
width: options.cropRectangle.width,
height: options.cropRectangle.height
}
if (!options.keepOriginalImageSize) {
clipRect.x = 0;
clipRect.y = 0;
clipRect.width = undefined;
clipRect.height = undefined;
}
const diff = new BlinkDiff({
imageAPath: actual,
imageBPath: expected,
imageOutputPath: output,
imageOutputLimit: this.imageOutputLimit,
thresholdType: options.toleranceType,
threshold: options.tolerance,
delta: this.delta,
cropImageA: clipRect,
cropImageB: clipRect,
blockOut: this._blockOutAreas,
verbose: this._args.verbose,
});
if (options.toleranceType == ImageOptions.percent) {
if (options.tolerance >= 1) {
logError("Tolerance range is from 0 to 1 -> percentage thresholds: 1 = 100%, 0.2 = 20%");
}
console.log(`Using ${options.tolerance * 100}% tolerance`);
} else {
console.log(`Using ${options.tolerance}px tolerance`);
}
const result = this.runDiff(diff, output);
this._blockOutAreas = undefined;
return result;
}
public async clipRectangleImage(rect: IRectangle, path: string) {
let imageToClip: PngJsImage;
imageToClip = await this.readImage(path);
let shouldExit = false;
if (!isNumber(rect["x"])
|| !isNumber(rect["y"])
|| !isNumber(rect["width"])
|| !isNumber(rect["height"])) {
shouldExit = true;
}
if (shouldExit) {
logError(`Could not crop the image. Not enough data {x: ${rect["x"]}, y: ${rect["y"]}, width: ${rect["width"]}, height: ${rect["height"]}}`);
}
if (!shouldExit) {
imageToClip.clip(rect.x, rect.y, rect.width, rect.height);
} else {
logWarn("Image will not be cropped!")
return true;
}
return new Promise((resolve, reject) => {
try {
imageToClip.writeImage(path, (err) => {
if (err) {
return reject(err);
}
return resolve();
});
} catch (error) {
logError(error);
}
});
}
public readImage(path: string): Promise<any> {
return new Promise((resolve, reject) => {
PngJsImage.readImage(path, (err, image) => {
if (err) {
return reject(err);
}
return resolve(image);
});
})
}
private runDiff(diffOptions: BlinkDiff, diffImage: string) {
var that = this;
return new Promise<boolean>((resolve, reject) => {
diffOptions.run(function (error, result) {
if (error) {
throw error;
} else {
const resultCode = diffOptions.hasPassed(result.code);
if (resultCode) {
console.log('Screen compare passed! Found ' + result.differences + ' differences.');
return resolve(true);
} else {
const message = `Screen compare failed! Found ${result.differences} differences.\n`;
console.log(message);
if (Object.getOwnPropertyNames(that._args.testReporter).length > 0) {
that._args.testReporterLog(message);
if (that._args.testReporter.logImageTypes
&& that._args.testReporter.logImageTypes.indexOf(LogImageType.everyImage) > -1) {
that._args.testReporterLog(`${basename(diffImage)} - ${message}`);
that._args.testReporterLog(diffImage);
}
}
return resolve(false);
}
}
});
});
}
private increaseImageName(imageName: string, options: IImageCompareOptions) {
if (options.keepOriginalImageName) {
return imageName;
}
if (!imageName) {
logError(`Missing image name!`);
logError(`Consider to set
drive.imageHelper.testName
driver.imageHelper.options.imageName`);
throw new Error(`Missing image name!`)
}
if (this._imagesResults.size > 0) {
const images = new Array();
this._imagesResults.forEach((v, k, map) => {
if (k.includes(imageName)) {
images.push(k);
}
});
images.sort((a, b) => {
const aNumber = +/\d+$/.exec(a);
const bNumber = +/\d+$/.exec(b);
return bNumber - aNumber;
});
if (images.length > 0) {
const lastImage = images[0];
const number = /\d+$/.test(lastImage) ? +`${/\d+$/.exec(lastImage)}` + 1 : `2`;
imageName = `${imageName}_${number}`;
}
}
return imageName;
}
public extendOptions(options: IImageCompareOptions) {
options = options || {};
Object.getOwnPropertyNames(this.options).forEach(prop => {
if (options[prop] === undefined || options[prop] === null) {
if (isObject(this.options[prop])) {
options[prop] = {};
ImageHelper.fullClone(this.options[prop], options[prop]);
} else {
options[prop] = this.options[prop];
}
}
});
return options;
}
private static fullClone(src, target) {
Object.getOwnPropertyNames(src)
.forEach(prop => {
if (isObject(src[prop])) {
target[prop] = {};
ImageHelper.fullClone(src[prop], target[prop]);
} else {
if (target[prop] === undefined || target[prop] === null) {
target[prop] = src[prop];
}
}
});
}
} | the_stack |
import MathHelper from './MathHelper';
import ArrayHelper from './ArrayHelper';
import Vector2 from './Vector2';
// import Atom from './Atom';
/**
* A class representing a vertex.
*
* @property {Number} id The id of this vertex.
* @property {Atom} value The atom associated with this vertex.
* @property {Vector2} position The position of this vertex.
* @property {Vector2} previousPosition The position of the previous vertex.
* @property {Number|null} parentVertexId The id of the previous vertex.
* @property {Number[]} children The ids of the children of this vertex.
* @property {Number[]} spanningTreeChildren The ids of the children of this vertex as defined in the spanning tree defined by the SMILES.
* @property {Number[]} edges The ids of edges associated with this vertex.
* @property {Boolean} positioned A boolean indicating whether or not this vertex has been positioned.
* @property {Number} angle The angle of this vertex.
* @property {Number} dir The direction of this vertex.
* @property {Number} neighbourCount The number of neighbouring vertices.
* @property {Number[]} neighbours The vertex ids of neighbouring vertices.
* @property {String[]} neighbouringElements The element symbols associated with neighbouring vertices.
* @property {Boolean} forcePositioned A boolean indicating whether or not this vertex was positioned using a force-based approach.
*/
class Vertex {
public id: any;
public value: any;
public position: any;
public previousPosition: any;
public parentVertexId: any;
public children: any;
public spanningTreeChildren: any;
public edges: any;
public positioned: any;
public angle: any;
public dir: any;
public neighbourCount: any;
public neighbours: any;
public neighbouringElements: any;
public forcePositioned: any;
public hasDoubleBondWithO: boolean;
public isAtomVertex: boolean;
/**
* The constructor for the class Vertex.
*
* @param {Atom} value The value associated with this vertex.
* @param {Number} [x=0] The initial x coordinate of the positional vector of this vertex.
* @param {Number} [y=0] The initial y coordinate of the positional vector of this vertex.
*/
constructor(value, x = 0, y = 0) {
this.id = null;
this.value = value;
this.position = new Vector2(x ? x : 0, y ? y : 0);
this.previousPosition = new Vector2(0, 0);
this.parentVertexId = null;
this.children = Array();
this.spanningTreeChildren = Array();
this.edges = Array();
this.positioned = false;
this.angle = null;
this.dir = 1.0;
this.neighbourCount = 0;
this.neighbours = Array();
this.neighbouringElements = Array();
this.forcePositioned = false;
this.hasDoubleBondWithO = false;
this.isAtomVertex = false;
}
/**
* Set the 2D coordinates of the vertex.
*
* @param {Number} x The x component of the coordinates.
* @param {Number} y The y component of the coordinates.
*
*/
setPosition(x, y) {
this.position.x = x;
this.position.y = y;
}
/**
* Set the 2D coordinates of the vertex from a Vector2.
*
* @param {Vector2} v A 2D vector.
*
*/
setPositionFromVector(v) {
this.position.x = v.x;
this.position.y = v.y;
}
/**
* Add a child vertex id to this vertex.
* @param {Number} vertexId The id of a vertex to be added as a child to this vertex.
*/
addChild(vertexId) {
this.children.push(vertexId);
this.neighbours.push(vertexId);
this.neighbourCount++;
}
/**
* Add a child vertex id to this vertex as the second child of the neighbours array,
* except this vertex is the first vertex of the SMILE string, then it is added as the first.
* This is used to get the correct ordering of neighbours for parity calculations.
* If a hydrogen is implicitly attached to the chiral center, insert as the third child.
* @param {Number} vertexId The id of a vertex to be added as a child to this vertex.
* @param {Number} ringbondIndex The index of the ringbond.
*/
addRingbondChild(vertexId, ringbondIndex) {
this.children.push(vertexId);
if (this.value.bracket) {
let index = 1;
if (this.id === 0 && this.value.bracket.hcount === 0) {
index = 0;
}
if (this.value.bracket.hcount === 1 && ringbondIndex === 0) {
index = 2;
}
if (this.value.bracket.hcount === 1 && ringbondIndex === 1) {
if (this.neighbours.length < 3) {
index = 2;
} else {
index = 3;
}
}
if (this.value.bracket.hcount === null && ringbondIndex === 0) {
index = 1;
}
if (this.value.bracket.hcount === null && ringbondIndex === 1) {
if (this.neighbours.length < 3) {
index = 1;
} else {
index = 2;
}
}
this.neighbours.splice(index, 0, vertexId);
} else {
this.neighbours.push(vertexId);
}
this.neighbourCount++;
}
/**
* Set the vertex id of the parent.
*
* @param {Number} parentVertexId The parents vertex id.
*/
setParentVertexId(parentVertexId) {
this.neighbourCount++;
this.parentVertexId = parentVertexId;
this.neighbours.push(parentVertexId);
}
/**
* Returns true if this vertex is terminal (has no parent or child vertices), otherwise returns false. Always returns true if associated value has property hasAttachedPseudoElements set to true.
*
* @returns {Boolean} A boolean indicating whether or not this vertex is terminal.
*/
isTerminal() {
if (this.value.hasAttachedPseudoElements) {
return true;
}
return (this.parentVertexId === null && this.children.length < 2) || this.children.length === 0;
}
/**
* Clones this vertex and returns the clone.
*
* @returns {Vertex} A clone of this vertex.
*/
clone() {
let clone = new Vertex(this.value, this.position.x, this.position.y);
clone.id = this.id;
clone.previousPosition = new Vector2(this.previousPosition.x, this.previousPosition.y);
clone.parentVertexId = this.parentVertexId;
clone.children = ArrayHelper.clone(this.children);
clone.spanningTreeChildren = ArrayHelper.clone(this.spanningTreeChildren);
clone.edges = ArrayHelper.clone(this.edges);
clone.positioned = this.positioned;
clone.angle = this.angle;
clone.forcePositioned = this.forcePositioned;
return clone;
}
/**
* Returns true if this vertex and the supplied vertex both have the same id, else returns false.
*
* @param {Vertex} vertex The vertex to check.
* @returns {Boolean} A boolean indicating whether or not the two vertices have the same id.
*/
equals(vertex) {
return this.id === vertex.id;
}
/**
* Returns the angle of this vertexes positional vector. If a reference vector is supplied in relations to this vector, else in relations to the coordinate system.
*
* @param {Vector2} [referenceVector=null] - The reference vector.
* @param {Boolean} [returnAsDegrees=false] - If true, returns angle in degrees, else in radians.
* @returns {Number} The angle of this vertex.
*/
getAngle(referenceVector = null, returnAsDegrees = false) {
let u = null;
if (!referenceVector) {
u = Vector2.subtract(this.position, this.previousPosition);
} else {
u = Vector2.subtract(this.position, referenceVector);
}
if (returnAsDegrees) {
return MathHelper.toDeg(u.angle());
}
return u.angle();
}
/**
* Returns the suggested text direction when text is added at the position of this vertex.
*
* @param {Vertex[]} vertices The array of vertices for the current molecule.
* @returns {String} The suggested direction of the text.
*/
getTextDirection(vertices) {
let neighbours = this.getDrawnNeighbours(vertices);
let angles = Array();
for (let i = 0; i < neighbours.length; i++) {
angles.push(this.getAngle(vertices[neighbours[i]].position));
}
let textAngle = MathHelper.meanAngle(angles);
// Round to 0, 90, 180 or 270 degree
let halfPi = Math.PI / 2.0;
textAngle = Math.round(Math.round(textAngle / halfPi) * halfPi);
if (textAngle === 2) {
return 'down';
} else if (textAngle === -2) {
return 'up';
} else if (textAngle === 0 || textAngle === -0) {
return 'right'; // is checking for -0 necessary?
} else if (textAngle === 3 || textAngle === -3) {
return 'left';
} else {
return 'down'; // default to down
}
}
/**
* Returns an array of ids of neighbouring vertices.
*
* @param {Number} [vertexId=null] If a value is supplied, the vertex with this id is excluded from the returned indices.
* @returns {Number[]} An array containing the ids of neighbouring vertices.
*/
getNeighbours(vertexId = null) {
if (vertexId === null) {
return this.neighbours.slice();
}
let arr = Array();
for (let i = 0; i < this.neighbours.length; i++) {
if (this.neighbours[i] !== vertexId) {
arr.push(this.neighbours[i]);
}
}
return arr;
}
/**
* Returns an array of ids of neighbouring vertices that will be drawn (vertex.value.isDrawn === true).
*
* @param {Vertex[]} vertices An array containing the vertices associated with the current molecule.
* @returns {Number[]} An array containing the ids of neighbouring vertices that will be drawn.
*/
getDrawnNeighbours(vertices) {
let arr = Array();
for (let i = 0; i < this.neighbours.length; i++) {
if (vertices[this.neighbours[i]].value.isDrawn) {
arr.push(this.neighbours[i]);
}
}
return arr;
}
/**
* Returns the number of neighbours of this vertex.
*
* @returns {Number} The number of neighbours.
*/
getNeighbourCount() {
return this.neighbourCount;
}
/**
* Returns a list of ids of vertices neighbouring this one in the original spanning tree, excluding the ringbond connections.
*
* @param {Number} [vertexId=null] If supplied, the vertex with this id is excluded from the array returned.
* @returns {Number[]} An array containing the ids of the neighbouring vertices.
*/
getSpanningTreeNeighbours(vertexId = null) {
let neighbours = Array();
for (let i = 0; i < this.spanningTreeChildren.length; i++) {
if (vertexId === undefined || vertexId != this.spanningTreeChildren[i]) {
neighbours.push(this.spanningTreeChildren[i]);
}
}
if (this.parentVertexId != null) {
if (vertexId === undefined || vertexId != this.parentVertexId) {
neighbours.push(this.parentVertexId);
}
}
return neighbours;
}
/**
* Gets the next vertex in the ring in opposide direction to the supplied vertex id.
*
* @param {Vertex[]} vertices The array of vertices for the current molecule.
* @param {Number} ringId The id of the ring containing this vertex.
* @param {Number} previousVertexId The id of the previous vertex. The next vertex will be opposite from the vertex with this id as seen from this vertex.
* @returns {Number} The id of the next vertex in the ring.
*/
getNextInRing(vertices, ringId, previousVertexId) {
let neighbours = this.getNeighbours();
for (let i = 0; i < neighbours.length; i++) {
if (ArrayHelper.contains(vertices[neighbours[i]].value.rings, {
value: ringId
}) &&
neighbours[i] != previousVertexId) {
return neighbours[i];
}
}
return null;
}
}
export default Vertex; | the_stack |
import { HttpResponse } from 'fts-core'
import fileType = require('file-type')
import pMap = require('p-map')
import sharp = require('sharp')
import { getImage } from './get-image'
type ImageOperationType =
// Input
'metadata' | 'stats' | 'meta' | 'limitInputPixels' |
// Output
'withMetadata' | 'jpeg' | 'png' | 'webp' | 'tiff' | 'raw' |
// Resizing
'resize' | 'extend' | 'extract' | 'trim' |
// Compositing
'composite' |
// Image Manipulation
'rotate' | 'flip' | 'flop' | 'sharpen' | 'median' | 'blur' |
'flatten' | 'gamma' | 'negate' | 'normalise' | 'normalize' |
'convolve' | 'threshold' | 'boolean' | 'linear' | 'recomb' |
'modulate' |
// Color Manipulation
'tint' | 'greyscale' | 'grayscale' |
'toColourspace' | 'toColorspace' | 'toColourSpace' | 'toColorSpace' |
// Channel Manipulation
'removeAlpha' | 'ensureAlpha' | 'extractChannel' |
'bandBool' | 'bandbool'
interface ImageOperation {
op: ImageOperationType
}
interface ImageOperationLimitInputPixels extends ImageOperation {
limit: number | boolean
}
interface ImageOperationWithMetadata extends ImageOperation {
options?: sharp.WriteableMetadata
}
interface ImageOperationJpeg extends ImageOperation {
options?: sharp.JpegOptions
}
interface ImageOperationPng extends ImageOperation {
options?: sharp.PngOptions
}
interface ImageOperationWebp extends ImageOperation {
options?: sharp.WebpOptions
}
interface ImageOperationTiff extends ImageOperation {
options?: sharp.TiffOptions
}
interface ImageOperationResize extends ImageOperation {
options?: sharp.ResizeOptions
}
interface ImageOperationExtend extends ImageOperation {
options?: sharp.ExtendOptions
}
interface ImageOperationExtract extends ImageOperation {
region: sharp.Region
}
interface ImageOperationTrim extends ImageOperation {
threshold?: number
}
interface ImageOperationComposite extends ImageOperation {
images: sharp.OverlayOptions[]
}
interface ImageOperationRotate extends ImageOperation {
angle?: number
options?: sharp.RotateOptions
}
interface ImageOperationFlip extends ImageOperation {
flip?: boolean
}
interface ImageOperationFlop extends ImageOperation {
flop?: boolean
}
interface ImageOperationSharpen extends ImageOperation {
sigma?: number
flat?: number
jagged?: number
}
interface ImageOperationMedian extends ImageOperation {
size?: number
}
interface ImageOperationBlur extends ImageOperation {
sigma?: number
}
interface ImageOperationFlatten extends ImageOperation {
flatten?: boolean | sharp.FlattenOptions
}
interface ImageOperationGamma extends ImageOperation {
gamma?: number
}
interface ImageOperationNegate extends ImageOperation {
negate?: boolean
}
interface ImageOperationNormalize extends ImageOperation {
normalize?: boolean
}
interface ImageOperationConvolve extends ImageOperation {
kernel: sharp.Kernel
}
interface ImageOperationThreshold extends ImageOperation {
threshold?: number
options?: sharp.ThresholdOptions
}
interface ImageOperationBoolean extends ImageOperation {
operand: string
operator: string
options?: { raw: sharp.Raw }
}
interface ImageOperationLinear extends ImageOperation {
a?: number | null
b?: number
}
interface ImageOperationRecomb extends ImageOperation {
inputMatrix: sharp.Matrix3x3
}
interface ImageOperationModulate extends ImageOperation {
options?: { brightness?: number, saturation?: number, hue?: number }
}
interface ImageOperationTint extends ImageOperation {
rgb: string | sharp.Color
}
interface ImageOperationGreyscale extends ImageOperation {
greyscale?: boolean
}
interface ImageOperationToColorSpace extends ImageOperation {
colourspace?: string
colorspace?: string
colourSpace?: string
colorSpace?: string
}
interface ImageOperationRemoveAlpha extends ImageOperation {
}
interface ImageOperationEnsureAlpha extends ImageOperation {
}
interface ImageOperationExtractChannel extends ImageOperation {
channel: number | string
}
interface ImageOperationBandBool extends ImageOperation {
boolOp: string
}
type AnyImageOperation =
ImageOperation |
ImageOperationLimitInputPixels |
ImageOperationWithMetadata |
ImageOperationJpeg |
ImageOperationPng |
ImageOperationWebp |
ImageOperationTiff |
ImageOperationResize |
ImageOperationExtend |
ImageOperationExtract |
ImageOperationTrim |
ImageOperationComposite |
ImageOperationRotate |
ImageOperationFlip |
ImageOperationFlop |
ImageOperationSharpen |
ImageOperationMedian |
ImageOperationBlur |
ImageOperationFlatten |
ImageOperationGamma |
ImageOperationNegate |
ImageOperationNormalize |
ImageOperationConvolve |
ImageOperationThreshold |
ImageOperationBoolean |
ImageOperationLinear |
ImageOperationRecomb |
ImageOperationModulate |
ImageOperationTint |
ImageOperationGreyscale |
ImageOperationToColorSpace |
ImageOperationRemoveAlpha |
ImageOperationEnsureAlpha |
ImageOperationExtractChannel |
ImageOperationBandBool
function getInlineImage (input: string | Buffer | {create: sharp.Create}) {
if (typeof input === 'string') {
return getImage(input)
} else {
return input
}
}
export default async function process(
input?: string,
options?: sharp.SharpOptions,
ops?: AnyImageOperation[]
): Promise<HttpResponse> {
console.log({ input, ops, options })
let pipeline
if (input) {
const image = await getImage(input)
pipeline = sharp(image, options)
} else if (options && options.create) {
pipeline = sharp(options)
} else {
const err = new Error(`Must provide either an "input" url or "options.create" to create an image from scratch`)
// err.statusCode = 400
throw err
}
let pipelineIsImage = true
function ensurePipelineIsImage (op: ImageOperationType) {
if (!pipelineIsImage) {
const err = new Error(`Error processing operations at operation "${op}"`)
// err.statusCode = 400
throw err
}
}
if (ops) {
for (const imageOperation of ops) {
switch (imageOperation.op) {
// Input
case 'metadata':
case 'meta': {
ensurePipelineIsImage(imageOperation.op)
pipeline = pipeline.metadata()
pipelineIsImage = false
break
}
case 'stats': {
ensurePipelineIsImage(imageOperation.op)
pipeline = pipeline.stats()
pipelineIsImage = false
break
}
case 'limitInputPixels': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationLimitInputPixels)
pipeline = pipeline.limitInputPixels(op.limit)
break
}
// Output
case 'withMetadata': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationWithMetadata)
pipeline = pipeline.withMetadata(op.options)
break
}
case 'jpeg': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationJpeg)
pipeline = pipeline.jpeg(op.options)
break
}
case 'png': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationPng)
pipeline = pipeline.jpeg(op.options)
break
}
case 'webp': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationWebp)
pipeline = pipeline.webp(op.options)
break
}
case 'raw': {
ensurePipelineIsImage(imageOperation.op)
pipeline = pipeline.raw()
break
}
// Resizing
case 'resize': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationResize)
pipeline = pipeline.resize(op.options)
break
}
case 'extend': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationExtend)
pipeline = pipeline.extend(op.options)
break
}
case 'extract': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationExtract)
pipeline = pipeline.extract(op.region)
break
}
case 'trim': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationTrim)
pipeline = pipeline.trim(op.threshold)
break
}
// Compositing
case 'composite': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationComposite)
const images = await pMap((op.images || []), async (image) => ({
...image,
input: await getInlineImage(image.input)
}), {
concurrency: 3
})
pipeline = pipeline.composite(images)
break
}
// Image Manipulation
case 'rotate': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationRotate)
pipeline = pipeline.rotate(op.angle, op.options)
break
}
case 'flip': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationFlip)
pipeline = pipeline.flip(op.flip)
break
}
case 'flop': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationFlop)
pipeline = pipeline.flop(op.flop)
break
}
case 'sharpen': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationSharpen)
pipeline = pipeline.sharpen(op.sigma, op.flat, op.jagged)
break
}
case 'median': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationMedian)
pipeline = pipeline.median(op.size)
break
}
case 'blur': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationBlur)
pipeline = pipeline.blur(op.sigma)
break
}
case 'flatten': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationFlatten)
pipeline = pipeline.flatten(op.flatten)
break
}
case 'gamma': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationGamma)
pipeline = pipeline.gamma(op.gamma)
break
}
case 'negate': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationNegate)
pipeline = pipeline.negate(op.negate)
break
}
case 'normalise':
case 'normalize': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationNormalize)
pipeline = pipeline.normalize(op.normalize)
break
}
case 'convolve': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationConvolve)
pipeline = pipeline.convolve(op.kernel)
break
}
case 'threshold': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationThreshold)
pipeline = pipeline.threshold(op.threshold, op.options)
break
}
case 'boolean': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationBoolean)
pipeline = pipeline.boolean(op.operand, op.operator, op.options)
break
}
case 'linear': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationLinear)
pipeline = pipeline.linear(op.a, op.b)
break
}
case 'recomb': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationRecomb)
pipeline = pipeline.recomb(op.inputMatrix)
break
}
case 'modulate': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationModulate)
pipeline = pipeline.modulate(op.options)
break
}
// Color Manipulation
case 'tint': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationTint)
pipeline = pipeline.tint(op.rgb)
break
}
case 'grayscale':
case 'greyscale': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationGreyscale)
pipeline = pipeline.greyscale(op.greyscale)
break
}
case 'toColourSpace':
case 'toColourspace':
case 'toColorSpace':
case 'toColorspace': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationToColorSpace)
const colorSpace: string = op.colorspace || op.colorSpace || op.colourspace || op.colourSpace
pipeline = pipeline.toColorspace(colorSpace || undefined)
break
}
// Channel Manipulation
case 'removeAlpha': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationRemoveAlpha)
pipeline = pipeline.removeAlpha()
break
}
case 'ensureAlpha': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationEnsureAlpha)
pipeline = pipeline.ensureAlpha()
break
}
case 'extractChannel': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationExtractChannel)
pipeline = pipeline.extractChannel(op.channel)
break
}
case 'bandBool':
case 'bandbool': {
ensurePipelineIsImage(imageOperation.op)
const op = (imageOperation as ImageOperationBandBool)
pipeline = pipeline.bandbool(op.boolOp)
break
}
default: {
const err = new Error(`Unsupported image operation "${imageOperation.op}"`)
// err.statusCode = 400
throw err
}
}
}
}
let body
let contentType
if (pipelineIsImage) {
body = await pipeline.toBuffer()
const type = fileType(body)
if (!type) {
throw new Error('Unrecognized output mime type')
}
contentType = type.mime
} else {
body = await pipeline
console.log(body)
contentType = 'application/json'
}
return {
headers: { 'Content-Type': contentType },
statusCode: 200,
body
}
} | the_stack |
import { expect } from 'chai'
import $ from 'jquery'
import { RECORD_STORE_ADD } from '../../../src/extension/public/RecordStoreActions'
import ActionType from '../../../src/tracker/public/ActionType'
import OwnerManager from '../../../src/tracker/private/OwnerManager'
import trackJqueryApis from '../../../src/tracker/trackers/jquery/tracker'
import * as utils from './utils'
/* this test is based on dom tracker initialized in__init__.ts */
describe('jQuery API tracker', () => {
const receiver = new utils.RecordStoreMessageCatcher(window, RECORD_STORE_ADD)
before(() => {
trackJqueryApis($)
receiver.setup()
})
after(() => {
receiver.teardown()
})
beforeEach(() => {
receiver.reset()
})
describe('Attr action type', () => {
it('should track attr setter properly', () => {
const div = document.createElement('div')
$(div).attr('id', '1')
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Attr)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should not track attr getter', () => {
const div = document.createElement('div')
$(div).attr('id')
receiver.verifyNoMessage()
})
it('should track prop setter properly', () => {
const div = document.createElement('div')
$(div).prop('id', '1')
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Attr)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should not track prop getter', () => {
const div = document.createElement('div')
$(div).prop('id')
receiver.verifyNoMessage()
})
it('should track multiple targets of attr action properly', () => {
const div1 = document.createElement('div')
const div2 = document.createElement('div')
$(div1).add(div2).prop('id', '1')
const loc = utils.createSourceLocationWith(-2, 25)
// for div1
const data1 = utils.createActionData('1', ActionType.Attr)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(div1)
expect(ownerID1).to.equal(data1.trackid)
// for div2
const data2 = utils.createActionData('2', ActionType.Attr)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(div2)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContain([
{ loc, data: data1 },
{ loc, data: data2 },
])
})
})
describe('Behav action type', () => {
it('should have no error when no matched element', () => {
$(null).click()
expect(true).to.be.true
})
it('should track click with no listener', () => {
const div = document.createElement('div')
$(div).click()
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContainExactly({ loc, data })
})
it('should track click with native listener', () => {
const div = document.createElement('div')
div.addEventListener('click', () => {
div.style.color = 'red'
})
const loc1 = utils.createSourceLocationWith(-2, 24)
const data1 = utils.createActionData('1', ActionType.Style)
receiver.reset()
$(div).click()
const loc2 = utils.createSourceLocationWith(-2, 14)
const data2 = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(div.style)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID1).to.equal(data1.trackid)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContainExactly([
{ loc: loc1, data: data1 },
{ loc: loc2, data: data2 },
])
})
it('should track click with jquery listener', () => {
const div = document.createElement('div')
$(div).on('click', () => {
div.style.color = 'red'
})
const loc1 = utils.createSourceLocationWith(-2, 24)
const data1 = utils.createActionData('1', ActionType.Style)
receiver.reset()
$(div).click()
const loc2 = utils.createSourceLocationWith(-2, 14)
const data2 = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(div.style)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID1).to.equal(data1.trackid)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContainExactly([
{ loc: loc1, data: data1 },
{ loc: loc2, data: data2 },
])
})
function createFocusableDiv() {
const div = document.createElement('div')
// @NOTE: https://stackoverflow.com/questions/3656467/is-it-possible-to-focus-on-a-div-using-javascript-focus-function
// make div focusable (1) set tabIndex (2) attach to page
div.tabIndex = -1
document.body.appendChild(div)
receiver.reset()
return div
}
it('should track focus (which will use special trigger, same as blur) with no listener', () => {
const div = createFocusableDiv()
$(div).focus()
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContainExactly({ loc, data })
})
it('should track focus (which will use special trigger, same as blur) with native listener', () => {
const div = createFocusableDiv()
div.addEventListener('focus', () => {
div.style.color = 'red'
})
const loc1 = utils.createSourceLocationWith(-2, 24)
const data1 = utils.createActionData('1', ActionType.Style)
receiver.reset()
$(div).focus()
const loc2 = utils.createSourceLocationWith(-2, 14)
const data2 = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal('1')
receiver.verifyMessagesContainExactly([
{ loc: loc1, data: data1 },
{ loc: loc2, data: data2 }
])
})
it('should track focus (which will use special trigger, same as blur) with jquery listener', () => {
const div = createFocusableDiv()
$(div).on('focus', () => {
div.style.color = 'red'
})
const loc1 = utils.createSourceLocationWith(-2, 24)
const data1 = utils.createActionData('1', ActionType.Style)
receiver.reset()
$(div).focus()
const loc2 = utils.createSourceLocationWith(-2, 14)
const data2 = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal('1')
receiver.verifyMessagesContainExactly([
{ loc: loc1, data: data1 },
{ loc: loc2, data: data2 }
])
})
it('should track mouseenter (and those have no native trigger method like click()) and actions triggered by it properly', () => {
const div = document.createElement('div')
$(div).on('mouseenter', () => {
div.style.color = 'red'
})
const loc1 = utils.createSourceLocationWith(-2, 24)
const data1 = utils.createActionData('1', ActionType.Style)
receiver.reset()
$(div).mouseenter()
const loc2 = utils.createSourceLocationWith(-2, 14)
const data2 = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(div.style)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID1).to.equal(data1.trackid)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContainExactly([
{ loc: loc1, data: data1 },
{ loc: loc2, data: data2 },
])
})
it('should track trigger and actions triggered by it properly (add native event listener)', () => {
const div = document.createElement('div')
div.addEventListener('click', () => {
div.style.color = 'red'
})
const loc1 = utils.createSourceLocationWith(-2, 24)
const data1 = utils.createActionData('1', ActionType.Style)
receiver.reset()
$(div).trigger('click')
const loc2 = utils.createSourceLocationWith(-2, 14)
const data2 = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(div.style)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID1).to.equal(data1.trackid)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContainExactly([
{ loc: loc1, data: data1 },
{ loc: loc2, data: data2 }
])
})
it('should track trigger and actions triggered by it properly (add jquery event listener)', () => {
const div = document.createElement('div')
$(div).on('click', () => {
div.style.color = 'red'
})
const loc1 = utils.createSourceLocationWith(-2, 24)
const data1 = utils.createActionData('1', ActionType.Style)
receiver.reset()
$(div).trigger('click')
const loc2 = utils.createSourceLocationWith(-2, 14)
const data2 = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(div.style)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID1).to.equal(data1.trackid)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContainExactly([
{ loc: loc1, data: data1 },
{ loc: loc2, data: data2 }
])
})
it('should track triggerHandler and actions triggered by it properly', () => {
const div = document.createElement('div')
// @NOTE: triggerHandler only trigger event registered by jquery
$(div).on('click', () => {
div.style.color = 'red'
})
const loc1 = utils.createSourceLocationWith(-2, 24)
const data1 = utils.createActionData('1', ActionType.Style)
receiver.reset()
$(div).triggerHandler('click')
const loc2 = utils.createSourceLocationWith(-2, 14)
const data2 = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(div.style)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID1).to.equal(data1.trackid)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContainExactly([
{ loc: loc1, data: data1 },
{ loc: loc2, data: data2 }
])
})
describe('low level api: event.trigger', () => {
const ActionRecorder = require('../../../src/tracker/private/ActionRecorder').default
it('should not data event.trigger given event is fired by page interaction (e.g., focusin -> event.simulate -> event.trigger)', () => {
const div = document.createElement('div')
$.event.trigger('click', null, div)
expect(ActionRecorder.isRecording()).to.be.false
})
it('should not data anything during ajax executing', () => {
// @NOTE: [http://api.jquery.com/jquery.ajax/]
// use ajax to fetch javascript will load and execute immediately,
// thus we use html file for this test
return $.ajax({ method: 'GET', url: '/script.html' }).done(() => {
expect(ActionRecorder.isRecording()).to.be.false
receiver.verifyNoMessage()
})
})
})
})
describe('Event action type', () => {
it('should track ajax event properly', () => {
const div = document.createElement('div')
$(div).ajaxStart(() => { })
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Event)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track on (general event) properly', () => {
const div = document.createElement('div')
$(div).on('click', () => { })
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Event)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track click (explicit event) properly', () => {
const div = document.createElement('div')
$(div).click(() => { })
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Event)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track multiple targets of event action properly', () => {
const div1 = document.createElement('div')
const div2 = document.createElement('div')
$(div1).add(div2).on('click', () => { })
const loc = utils.createSourceLocationWith(-2, 25)
// for div1
const data1 = utils.createActionData('1', ActionType.Event)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(div1)
expect(ownerID1).to.equal(data1.trackid)
// for div2
const data2 = utils.createActionData('2', ActionType.Event)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(div2)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContain([
{ loc, data: data1 },
{ loc, data: data2 },
])
})
})
describe('Node action type', () => {
it('should track after properly', () => {
const parent = document.createElement('div')
const child = document.createElement('div')
const content = `<span>content</span>`
parent.appendChild(child)
receiver.reset()
// @NOTE: this data will be saved on parent
$(child).after(content)
const loc = utils.createSourceLocationWith(-2, 16)
const data = utils.createActionData('1', ActionType.Node)
const ownerID = OwnerManager.getTrackIDFromItsOwner(parent)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track append properly', () => {
const parent = document.createElement('div')
const child = document.createElement('div')
$(parent).append(child)
const loc = utils.createSourceLocationWith(-2, 17)
const data = utils.createActionData('1', ActionType.Node)
const ownerID = OwnerManager.getTrackIDFromItsOwner(parent)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track multiple targets of node action properly', () => {
const parent1 = document.createElement('div')
const parent2 = document.createElement('div')
const child = document.createElement('div')
$(parent1).add(parent2).append(child)
const loc = utils.createSourceLocationWith(-2, 31)
// for parent1
const data1 = utils.createActionData('1', ActionType.Node)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(parent1)
expect(ownerID1).to.equal(data1.trackid)
// for parent2
const data2 = utils.createActionData('2', ActionType.Node)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(parent2)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContain([
{ loc, data: data1 },
{ loc, data: data2 }
])
})
})
describe('Style action type', () => {
it('should track addClass properly', () => {
const div = document.createElement('div')
$(div).addClass('class')
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Style)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track css setter properly', () => {
const div = document.createElement('div')
$(div).css('background-color', 'red')
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Style)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should not track css getter', () => {
const div = document.createElement('div')
// @NOTE: jQuery will do initial process on dom while getting the first call of css getter
$(div).css('background-color')
receiver.reset()
$(div).css('background-color')
receiver.verifyNoMessage()
})
it('should track prop setter (class) properly', () => {
const div = document.createElement('div')
$(div).prop('class', 'class')
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Style)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should not track prop getter (class)', () => {
const div = document.createElement('div')
$(div).prop('class')
receiver.verifyNoMessage()
})
it('should track prop setter (style) properly', () => {
const div = document.createElement('div')
$(div).prop('style', 'background-color: red')
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Style)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should not track prop getter (style)', () => {
const div = document.createElement('div')
$(div).prop('style')
receiver.verifyNoMessage()
})
it('should track show properly', () => {
const div = document.createElement('div')
$(div).hide()
receiver.reset()
$(div).show()
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Style)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track hide properly', () => {
const div = document.createElement('div')
$(div).hide()
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Style)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track toggle properly', () => {
const div = document.createElement('div')
$(div).toggle()
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData('1', ActionType.Style)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track multiple targets of style action properly', () => {
const div1 = document.createElement('div')
const div2 = document.createElement('div')
$(div1).add(div2).addClass('class')
const loc = utils.createSourceLocationWith(-2, 25)
// for div1
const data1 = utils.createActionData('1', ActionType.Style)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(div1)
expect(ownerID1).to.equal(data1.trackid)
// for div2
const data2 = utils.createActionData('2', ActionType.Style)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(div2)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContain([
{ loc, data: data1 },
{ loc, data: data2 },
])
})
})
describe('Animation actions', () => {
it('should track only animate and exclude all details of its implementation code', (done) => {
const div = document.createElement('div')
$(div).animate({ 'top': '100px' }, 100, () => {
const loc = utils.createSourceLocationWith(-1, 14)
const data = utils.createActionData(
OwnerManager.getTrackIDFromItsOwner(div),
ActionType.Style
)
receiver.verifyMessagesContainExactly({ loc, data })
done()
})
})
it('should track only specific animation (e.g., fadeIn, fadeOut) and exclude all details of its implementation code', (done) => {
const div = document.createElement('div')
$(div).fadeOut(100, () => {
const loc = utils.createSourceLocationWith(-1, 14)
const data = utils.createActionData(
OwnerManager.getTrackIDFromItsOwner(div),
ActionType.Style
)
receiver.verifyMessagesContainExactly({ loc, data })
done()
})
})
it('should track other Style actions after animation finishes', (done) => {
const div = document.createElement('div')
$(div).slideUp(100, () => {
receiver.reset()
$(div).css('color', 'red')
const loc = utils.createSourceLocationWith(-2, 16)
const data = utils.createActionData(
OwnerManager.getTrackIDFromItsOwner(div),
ActionType.Style
)
receiver.verifyMessagesContainExactly({ loc, data })
done()
})
})
it('should track other Style actions properly given animation executes only one tick ', () => {
const div = document.createElement('div')
$(div).fadeOut(0)
receiver.reset()
$(div).css('color', 'red')
const loc = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData(
OwnerManager.getTrackIDFromItsOwner(div),
ActionType.Style
)
receiver.verifyMessagesContainExactly({ loc, data })
})
it('should track other Style actions during animation', (done) => {
const div = document.createElement('div')
$(div).fadeOut(100, () => { done() })
const loc1 = utils.createSourceLocationWith(-2, 14)
const data1 = utils.createActionData(
OwnerManager.getTrackIDFromItsOwner(div),
ActionType.Style
)
$(div).css('color', 'red')
const loc2 = utils.createSourceLocationWith(-2, 14)
const data2 = utils.createActionData(
OwnerManager.getTrackIDFromItsOwner(div),
ActionType.Style
)
receiver.verifyMessagesContainExactly([
{ loc: loc1, data: data1 },
{ loc: loc2, data: data2 }
])
})
it('should track delay animation properly', (done) => {
const div = document.createElement('div')
$(div).css('display', 'none')
receiver.reset()
$(div).delay(100).slideDown(100, () => {
const loc = utils.createSourceLocationWith(-1, 25)
const data = utils.createActionData(
OwnerManager.getTrackIDFromItsOwner(div),
ActionType.Style
)
receiver.verifyMessagesContainExactly({ loc, data })
done()
})
})
it('should track stop properly', (done) => {
const div = document.createElement('div')
$(div).fadeOut(1000)
$(div).stop()
$(div).fadeIn(100, () => {
const loc1 = utils.createSourceLocationWith(-3, 14)
const loc2 = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData(
OwnerManager.getTrackIDFromItsOwner(div),
ActionType.Style
)
receiver.verifyMessagesContainExactly([
{ loc: loc1, data },
{ loc: loc2, data },
])
done()
})
})
it('should not track unneeded infos with those animations that will tune overflow property when forced stop', (done) => {
const div = document.createElement('div')
$(div).slideUp(1000)
$(div).stop()
$(div).slideDown(100, () => {
const loc1 = utils.createSourceLocationWith(-3, 14)
const loc2 = utils.createSourceLocationWith(-2, 14)
const data = utils.createActionData(
OwnerManager.getTrackIDFromItsOwner(div),
ActionType.Style
)
receiver.verifyMessagesContainExactly([
{ loc: loc1, data },
{ loc: loc2, data },
])
done()
})
})
it('should track double animation properly', (done) => {
const div1 = document.createElement('div')
const div2 = document.createElement('div')
// for div1
$(div1).animate({ 'margin-top': '300px', 'opacity': 0 }, 100)
const loc1 = utils.createSourceLocationWith(-2, 15)
const data1 = utils.createActionData(
OwnerManager.getTrackIDFromItsOwner(div1),
ActionType.Style
)
receiver.verifyMessagesContainExactly({ loc: loc1, data: data1 })
receiver.reset()
// for div2
$(div2).animate({ 'top': -200 }, 100)
const loc2 = utils.createSourceLocationWith(-2, 15)
// @NOTE: setTimeout to wait for animation executing of div2.
// jquery will not execute second immediately, it will wait
// until next animate cycle and do animation after first one.
setTimeout(() => {
const data2 = utils.createActionData(
OwnerManager.getTrackIDFromItsOwner(div2),
ActionType.Style
)
receiver.verifyMessagesContainExactly({ loc: loc2, data: data2 })
done()
}, 10)
})
describe('queue actions', () => {
it('should track actions in queueed function', (done) => {
const div = document.createElement('div')
$(div).queue(() => {
div.style.color = 'red'
const loc = utils.createSourceLocationWith(-2, 26)
const data = utils.createActionData('1', ActionType.Style)
receiver.verifyMessagesContain({ loc, data })
$(div).dequeue()
done()
})
})
})
})
}) | the_stack |
export function drawCircle(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
r: number
): void {
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI, false);
ctx.closePath();
}
/**
* Draw a square.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - Half of the width and height of the square.
*/
export function drawSquare(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
r: number
): void {
ctx.beginPath();
ctx.rect(x - r, y - r, r * 2, r * 2);
ctx.closePath();
}
/**
* Draw an equilateral triangle standing on a side.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - Half of the length of the sides.
*
* @remarks
* http://en.wikipedia.org/wiki/Equilateral_triangle
*/
export function drawTriangle(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
r: number
): void {
ctx.beginPath();
// the change in radius and the offset is here to center the shape
r *= 1.15;
y += 0.275 * r;
const s = r * 2;
const s2 = s / 2;
const ir = (Math.sqrt(3) / 6) * s; // radius of inner circle
const h = Math.sqrt(s * s - s2 * s2); // height
ctx.moveTo(x, y - (h - ir));
ctx.lineTo(x + s2, y + ir);
ctx.lineTo(x - s2, y + ir);
ctx.lineTo(x, y - (h - ir));
ctx.closePath();
}
/**
* Draw an equilateral triangle standing on a vertex.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - Half of the length of the sides.
*
* @remarks
* http://en.wikipedia.org/wiki/Equilateral_triangle
*/
export function drawTriangleDown(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
r: number
): void {
ctx.beginPath();
// the change in radius and the offset is here to center the shape
r *= 1.15;
y -= 0.275 * r;
const s = r * 2;
const s2 = s / 2;
const ir = (Math.sqrt(3) / 6) * s; // radius of inner circle
const h = Math.sqrt(s * s - s2 * s2); // height
ctx.moveTo(x, y + (h - ir));
ctx.lineTo(x + s2, y - ir);
ctx.lineTo(x - s2, y - ir);
ctx.lineTo(x, y + (h - ir));
ctx.closePath();
}
/**
* Draw a star.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - The outer radius of the star.
*/
export function drawStar(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
r: number
): void {
// http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
ctx.beginPath();
// the change in radius and the offset is here to center the shape
r *= 0.82;
y += 0.1 * r;
for (let n = 0; n < 10; n++) {
const radius = n % 2 === 0 ? r * 1.3 : r * 0.5;
ctx.lineTo(
x + radius * Math.sin((n * 2 * Math.PI) / 10),
y - radius * Math.cos((n * 2 * Math.PI) / 10)
);
}
ctx.closePath();
}
/**
* Draw a diamond.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - Half of the width and height of the diamond.
*
* @remarks
* http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
*/
export function drawDiamond(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
r: number
): void {
ctx.beginPath();
ctx.lineTo(x, y + r);
ctx.lineTo(x + r, y);
ctx.lineTo(x, y - r);
ctx.lineTo(x - r, y);
ctx.closePath();
}
/**
* Draw a rectangle with rounded corners.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param r - The radius of the corners.
*
* @remarks
* http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
*/
export function drawRoundRect(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
w: number,
h: number,
r: number
): void {
const r2d = Math.PI / 180;
if (w - 2 * r < 0) {
r = w / 2;
} //ensure that the radius isn't too large for x
if (h - 2 * r < 0) {
r = h / 2;
} //ensure that the radius isn't too large for y
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.arc(x + w - r, y + r, r, r2d * 270, r2d * 360, false);
ctx.lineTo(x + w, y + h - r);
ctx.arc(x + w - r, y + h - r, r, 0, r2d * 90, false);
ctx.lineTo(x + r, y + h);
ctx.arc(x + r, y + h - r, r, r2d * 90, r2d * 180, false);
ctx.lineTo(x, y + r);
ctx.arc(x + r, y + r, r, r2d * 180, r2d * 270, false);
ctx.closePath();
}
/**
* Draw an ellipse.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param w - The width of the ellipse.
* @param h - The height of the ellipse.
*
* @remarks
* http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
*
* Postfix '_vis' added to discern it from standard method ellipse().
*/
export function drawEllipse(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
w: number,
h: number
): void {
const kappa = 0.5522848,
ox = (w / 2) * kappa, // control point offset horizontal
oy = (h / 2) * kappa, // control point offset vertical
xe = x + w, // x-end
ye = y + h, // y-end
xm = x + w / 2, // x-middle
ym = y + h / 2; // y-middle
ctx.beginPath();
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
ctx.closePath();
}
/**
* Draw an isometric cylinder.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param w - The width of the database.
* @param h - The height of the database.
*
* @remarks
* http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
*/
export function drawDatabase(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
w: number,
h: number
): void {
const f = 1 / 3;
const wEllipse = w;
const hEllipse = h * f;
const kappa = 0.5522848,
ox = (wEllipse / 2) * kappa, // control point offset horizontal
oy = (hEllipse / 2) * kappa, // control point offset vertical
xe = x + wEllipse, // x-end
ye = y + hEllipse, // y-end
xm = x + wEllipse / 2, // x-middle
ym = y + hEllipse / 2, // y-middle
ymb = y + (h - hEllipse / 2), // y-midlle, bottom ellipse
yeb = y + h; // y-end, bottom ellipse
ctx.beginPath();
ctx.moveTo(xe, ym);
ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
ctx.lineTo(xe, ymb);
ctx.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
ctx.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
ctx.lineTo(x, ym);
}
/**
* Draw a dashed line.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The start position on the x axis.
* @param y - The start position on the y axis.
* @param x2 - The end position on the x axis.
* @param y2 - The end position on the y axis.
* @param pattern - List of lengths starting with line and then alternating between space and line.
*
* @author David Jordan
* @remarks
* date 2012-08-08
* http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
*/
export function drawDashedLine(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
x2: number,
y2: number,
pattern: number[]
): void {
ctx.beginPath();
ctx.moveTo(x, y);
const patternLength = pattern.length;
const dx = x2 - x;
const dy = y2 - y;
const slope = dy / dx;
let distRemaining = Math.sqrt(dx * dx + dy * dy);
let patternIndex = 0;
let draw = true;
let xStep = 0;
let dashLength = +pattern[0];
while (distRemaining >= 0.1) {
dashLength = +pattern[patternIndex++ % patternLength];
if (dashLength > distRemaining) {
dashLength = distRemaining;
}
xStep = Math.sqrt((dashLength * dashLength) / (1 + slope * slope));
xStep = dx < 0 ? -xStep : xStep;
x += xStep;
y += slope * xStep;
if (draw === true) {
ctx.lineTo(x, y);
} else {
ctx.moveTo(x, y);
}
distRemaining -= dashLength;
draw = !draw;
}
}
/**
* Draw a hexagon.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - The radius of the hexagon.
*/
export function drawHexagon(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
r: number
): void {
ctx.beginPath();
const sides = 6;
const a = (Math.PI * 2) / sides;
ctx.moveTo(x + r, y);
for (let i = 1; i < sides; i++) {
ctx.lineTo(x + r * Math.cos(a * i), y + r * Math.sin(a * i));
}
ctx.closePath();
}
const shapeMap = {
circle: drawCircle,
dashedLine: drawDashedLine,
database: drawDatabase,
diamond: drawDiamond,
ellipse: drawEllipse,
ellipse_vis: drawEllipse,
hexagon: drawHexagon,
roundRect: drawRoundRect,
square: drawSquare,
star: drawStar,
triangle: drawTriangle,
triangleDown: drawTriangleDown,
};
/**
* Returns either custom or native drawing function base on supplied name.
*
* @param name - The name of the function. Either the name of a
* CanvasRenderingContext2D property or an export from shapes.ts without the
* draw prefix.
*
* @returns The function that can be used for rendering. In case of native
* CanvasRenderingContext2D function the API is normalized to
* `(ctx: CanvasRenderingContext2D, ...originalArgs) => void`.
*/
export function getShape(
name: keyof CanvasRenderingContext2D | keyof typeof shapeMap
): any {
if (Object.prototype.hasOwnProperty.call(shapeMap, name)) {
return (shapeMap as any)[name];
} else {
return function (ctx: CanvasRenderingContext2D, ...args: any[]): void {
(CanvasRenderingContext2D.prototype as any)[name].call(ctx, args);
};
}
} | the_stack |
import { ArrayType, CRuntime, Variable, VariableType } from "./rt";
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS205: Consider reworking code to avoid use of IIFEs
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const sampleGeneratorFunction = function* (): Generator<null, void, void> {
return yield null;
};
const sampleGenerator = sampleGeneratorFunction();
const isGenerator = (g: any) => {
return (g != null ? g.constructor : undefined) === sampleGenerator.constructor;
};
const isGeneratorFunction = (f: any) => {
return (f != null ? f.constructor : undefined) === sampleGeneratorFunction.constructor;
};
export class BaseInterpreter {
rt: CRuntime;
currentNode: any;
source: string;
constructor(rt: CRuntime) {
this.rt = rt;
}
}
function isIterable(obj: any) {
// checks for null and undefined
if (obj == null) {
return false;
}
return typeof obj[Symbol.iterator] === 'function';
}
export class Interpreter extends BaseInterpreter {
visitors: { [name: string]: (interp: Interpreter, s: any, param?: any) => any };
constructor(rt: CRuntime) {
super(rt);
this.visitors = {
*TranslationUnit(interp, s, param) {
({
rt
} = interp);
let i = 0;
while (i < s.ExternalDeclarations.length) {
const dec = s.ExternalDeclarations[i];
yield* interp.visit(interp, dec);
i++;
}
},
*DirectDeclarator(interp, s, param) {
({
rt
} = interp);
let {
basetype
} = param;
basetype = interp.buildRecursivePointerType(s.Pointer, basetype, 0);
if (s.right.length === 1) {
let varargs;
const right = s.right[0];
let ptl = null;
if (right.type === "DirectDeclarator_modifier_ParameterTypeList") {
ptl = right.ParameterTypeList;
({
varargs
} = ptl);
} else if ((right.type === "DirectDeclarator_modifier_IdentifierList") && (right.IdentifierList === null)) {
ptl = right.ParameterTypeList;
varargs = false;
}
if (ptl != null) {
const argTypes = [];
for (const _param of ptl.ParameterList) {
const _basetype = rt.simpleType(_param.DeclarationSpecifiers);
let _type;
if (_param.Declarator != null) {
const _pointer = _param.Declarator.Pointer;
_type = interp.buildRecursivePointerType(_pointer, _basetype, 0);
if ((_param.Declarator.right != null) && (_param.Declarator.right.length > 0)) {
const dimensions = [];
for (let j = 0; j < _param.Declarator.right.length; j++) {
let dim = _param.Declarator.right[j];
if (dim.type !== "DirectDeclarator_modifier_array") {
rt.raiseException("unacceptable array initialization", dim);
}
if (dim.Expression !== null) {
dim = rt.cast(rt.intTypeLiteral, (yield* interp.visit(interp, dim.Expression, param))).v;
} else if (j > 0) {
rt.raiseException("multidimensional array must have bounds for all dimensions except the first", dim);
} else {
dim = -1;
}
dimensions.push(dim);
}
_type = interp.arrayType(dimensions, _type);
}
} else {
_type = _basetype;
}
argTypes.push(_type);
}
basetype = rt.functionType(basetype, argTypes);
}
}
if ((s.right.length > 0) && (s.right[0].type === "DirectDeclarator_modifier_array")) {
const dimensions = [];
for (let j = 0; j < s.right.length; j++) {
let dim = s.right[j];
if (dim.type !== "DirectDeclarator_modifier_array") {
rt.raiseException("unacceptable array initialization", dim);
}
if (dim.Expression !== null) {
dim = rt.cast(rt.intTypeLiteral, (yield* interp.visit(interp, dim.Expression, param))).v;
} else if (j > 0) {
rt.raiseException("multidimensional array must have bounds for all dimensions except the first", dim);
} else {
dim = -1;
}
dimensions.push(dim);
}
basetype = interp.arrayType(dimensions, basetype);
}
if (s.left.type === "Identifier") {
return { type: basetype, name: s.left.Identifier };
} else {
const _basetype = param.basetype;
param.basetype = basetype;
const ret = yield* interp.visit(interp, s.left, param);
param.basetype = _basetype;
return ret;
}
},
*TypedefDeclaration(interp, s, param) {
({
rt
} = interp);
const basetype = rt.simpleType(s.DeclarationSpecifiers);
const _basetype = param.basetype;
param.basetype = basetype;
for (const declarator of s.Declarators) {
const { type, name } = yield* interp.visit(interp, declarator, param);
rt.registerTypedef(type, name);
}
param.basetype = _basetype;
},
*ParameterTypeList(interp, s, param) {
const argTypes = [];
const argNames = [];
const optionalArgs = [];
let i = 0;
while (i < s.ParameterList.length) {
const _param = s.ParameterList[i];
let _type;
let _init = null;
let _name = null;
if (param.insideDirectDeclarator_modifier_ParameterTypeList) {
const _basetype = rt.simpleType(_param.DeclarationSpecifiers);
_type = _basetype;
} else {
if (_param.Declarator == null) {
rt.raiseException("missing declarator for argument", _param);
}
_init = _param.Declarator.Initializers;
const _pointer = _param.Declarator.Declarator.Pointer;
const _basetype = rt.simpleType(_param.DeclarationSpecifiers);
_type = interp.buildRecursivePointerType(_pointer, _basetype, 0);
if (_param.Declarator.Declarator.left.type === "DirectDeclarator") {
const __basetype = param.basetype;
param.basetype = _basetype;
const { name, type } = yield* interp.visit(interp, _param.Declarator.Declarator.left, param);
param.basetype = __basetype;
_name = name;
} else {
_name = _param.Declarator.Declarator.left.Identifier;
}
if (_param.Declarator.Declarator.right.length > 0) {
if (_param.Declarator.Declarator.right[0].type === "DirectDeclarator_modifier_ParameterTypeList") {
const dim = _param.Declarator.Declarator.right[0];
param.insideDirectDeclarator_modifier_ParameterTypeList = true;
const {argTypes: _argTypes , argNames: _argNames, optionalArgs: _optionalArgs} = yield* interp.visit(interp, dim.ParameterTypeList, param);
param.insideDirectDeclarator_modifier_ParameterTypeList = false;
_type = rt.functionPointerType(_type, _argTypes);
} else {
const dimensions = [];
let j = 0;
while (j < _param.Declarator.Declarator.right.length) {
let dim = _param.Declarator.Declarator.right[j];
if (dim.type !== "DirectDeclarator_modifier_array") {
rt.raiseException("unacceptable array initialization", dim);
}
if (dim.Expression !== null) {
dim = rt.cast(rt.intTypeLiteral, (yield* interp.visit(interp, dim.Expression, param))).v;
} else if (j > 0) {
rt.raiseException("multidimensional array must have bounds for all dimensions except the first", dim);
} else {
dim = -1;
}
dimensions.push(dim);
j++;
}
_type = interp.arrayType(dimensions, _type);
}
}
}
if (_init != null) {
optionalArgs.push({
type: _type,
name: _name,
expression: _init.Expression
});
} else {
if (optionalArgs.length > 0) {
rt.raiseException("all default arguments must be at the end of arguments list", _param);
}
argTypes.push(_type);
argNames.push(_name);
}
i++;
}
return {argTypes , argNames, optionalArgs};
},
*FunctionDefinition(interp, s, param) {
({
rt
} = interp);
const {
scope
} = param;
const name = s.Declarator.left.Identifier;
let basetype = rt.simpleType(s.DeclarationSpecifiers);
const pointer = s.Declarator.Pointer;
basetype = interp.buildRecursivePointerType(pointer, basetype, 0);
let ptl;
let varargs;
if (s.Declarator.right.type === "DirectDeclarator_modifier_ParameterTypeList") {
ptl = s.Declarator.right.ParameterTypeList;
({
varargs
} = ptl);
} else if ((s.Declarator.right.type === "DirectDeclarator_modifier_IdentifierList") && (s.Declarator.right.IdentifierList === null)) {
ptl = { ParameterList: [] };
varargs = false;
} else {
rt.raiseException("unacceptable argument list", s.Declarator.right);
}
const {argTypes , argNames, optionalArgs} = yield* interp.visit(interp, ptl, param);
const stat = s.CompoundStatement;
rt.defFunc(scope, name, basetype, argTypes, argNames, stat, interp, optionalArgs);
},
*Declaration(interp, s, param) {
({
rt
} = interp);
const basetype = rt.simpleType(s.DeclarationSpecifiers);
for (const dec of s.InitDeclaratorList) {
let init = dec.Initializers;
if ((dec.Declarator.right.length > 0) && (dec.Declarator.right[0].type === "DirectDeclarator_modifier_array")) {
const dimensions = [];
for (let j = 0; j < dec.Declarator.right.length; j++) {
let dim = dec.Declarator.right[j];
if (dim.Expression !== null) {
dim = rt.cast(rt.intTypeLiteral, (yield* interp.visit(interp, dim.Expression, param))).v;
} else if (j > 0) {
rt.raiseException("multidimensional array must have bounds for all dimensions except the first", dim);
} else {
if (init.type === "Initializer_expr") {
const initializer: Variable = yield* interp.visit(interp, init, param);
if (rt.isCharType(basetype) && rt.isArrayType(initializer) && rt.isCharType(initializer.t.eleType)) {
// string init
dim = initializer.v.target.length;
init = {
type: "Initializer_array",
Initializers: initializer.v.target.map(e => ({
type: "Initializer_expr",
shorthand: e
}))
};
} else {
rt.raiseException("cannot initialize an array to " + rt.makeValString(initializer), init);
}
} else {
dim = init.Initializers.length;
}
}
dimensions.push(dim);
}
param.node = init;
init = yield* interp.arrayInit(dimensions, init, basetype, param);
delete param.node;
const _basetype = param.basetype;
param.basetype = basetype;
const { name, type } = yield* interp.visit(interp, dec.Declarator, param);
param.basetype = _basetype;
rt.defVar(name, init.t, init);
} else {
const _basetype = param.basetype;
param.basetype = basetype;
const { name, type } = yield* interp.visit(interp, dec.Declarator, param);
param.basetype = _basetype;
if ((init == null)) {
init = rt.defaultValue(type, true);
} else {
init = yield* interp.visit(interp, init.Expression);
}
rt.defVar(name, type, init);
}
}
},
*Initializer_expr(interp, s, param) {
({
rt
} = interp);
return yield* interp.visit(interp, s.Expression, param);
},
*Label_case(interp, s, param) {
({
rt
} = interp);
const ce = yield* interp.visit(interp, s.ConstantExpression);
if (param["switch"] === undefined) {
rt.raiseException("you cannot use case outside switch block");
}
if (param.scope === "SelectionStatement_switch_cs") {
return [
"switch",
rt.cast(ce.t, param["switch"]).v === ce.v
];
} else {
rt.raiseException("you can only use case directly in a switch block");
}
},
Label_default(interp, s, param) {
({
rt
} = interp);
if (param["switch"] === undefined) {
rt.raiseException("you cannot use default outside switch block");
}
if (param.scope === "SelectionStatement_switch_cs") {
return [
"switch",
true
];
} else {
rt.raiseException("you can only use default directly in a switch block");
}
},
*CompoundStatement(interp, s, param) {
let stmt;
({
rt
} = interp);
const stmts = s.Statements;
let r;
let i;
const _scope = param.scope;
if (param.scope === "SelectionStatement_switch") {
param.scope = "SelectionStatement_switch_cs";
rt.enterScope(param.scope);
let switchon = false;
i = 0;
while (i < stmts.length) {
stmt = stmts[i];
if ((stmt.type === "Label_case") || (stmt.type === "Label_default")) {
r = yield* interp.visit(interp, stmt, param);
if (r[1]) {
switchon = true;
}
} else if (switchon) {
r = yield* interp.visit(interp, stmt, param);
if (r instanceof Array) {
return r;
}
}
i++;
}
rt.exitScope(param.scope);
param.scope = _scope;
} else {
param.scope = "CompoundStatement";
rt.enterScope(param.scope);
for (stmt of stmts) {
r = yield* interp.visit(interp, stmt, param);
if (r instanceof Array) {
break;
}
}
rt.exitScope(param.scope);
param.scope = _scope;
return r;
}
},
*ExpressionStatement(interp, s, param) {
({
rt
} = interp);
if (s.Expression != null) {
yield* interp.visit(interp, s.Expression, param);
}
},
*SelectionStatement_if(interp, s, param) {
({
rt
} = interp);
const scope_bak = param.scope;
param.scope = "SelectionStatement_if";
rt.enterScope(param.scope);
const e = yield* interp.visit(interp, s.Expression, param);
let ret;
if (rt.cast(rt.boolTypeLiteral, e).v) {
ret = yield* interp.visit(interp, s.Statement, param);
} else if (s.ElseStatement) {
ret = yield* interp.visit(interp, s.ElseStatement, param);
}
rt.exitScope(param.scope);
param.scope = scope_bak;
return ret;
},
*SelectionStatement_switch(interp, s, param) {
({
rt
} = interp);
const scope_bak = param.scope;
param.scope = "SelectionStatement_switch";
rt.enterScope(param.scope);
const e = yield* interp.visit(interp, s.Expression, param);
const switch_bak = param["switch"];
param["switch"] = e;
const r = yield* interp.visit(interp, s.Statement, param);
param["switch"] = switch_bak;
let ret;
if (r instanceof Array) {
if (r[0] !== "break") {
ret = r;
}
}
rt.exitScope(param.scope);
param.scope = scope_bak;
return ret;
},
*IterationStatement_while(interp, s, param) {
let return_val;
({
rt
} = interp);
const scope_bak = param.scope;
param.scope = "IterationStatement_while";
rt.enterScope(param.scope);
while (true) {
if (s.Expression != null) {
let cond = yield* interp.visit(interp, s.Expression, param);
cond = rt.cast(rt.boolTypeLiteral, cond).v;
if (!cond) { break; }
}
const r = yield* interp.visit(interp, s.Statement, param);
if (r instanceof Array) {
let end_loop;
switch (r[0]) {
case "continue":
break;
case "break":
end_loop = true;
break;
case "return":
return_val = r;
end_loop = true;
break;
}
if (end_loop) { break; }
}
}
rt.exitScope(param.scope);
param.scope = scope_bak;
return return_val;
},
*IterationStatement_do(interp, s, param) {
let return_val;
({
rt
} = interp);
const scope_bak = param.scope;
param.scope = "IterationStatement_do";
rt.enterScope(param.scope);
while (true) {
const r = yield* interp.visit(interp, s.Statement, param);
if (r instanceof Array) {
let end_loop;
switch (r[0]) {
case "continue":
break;
case "break":
end_loop = true;
break;
case "return":
return_val = r;
end_loop = true;
break;
}
if (end_loop) { break; }
}
if (s.Expression != null) {
let cond = yield* interp.visit(interp, s.Expression, param);
cond = rt.cast(rt.boolTypeLiteral, cond).v;
if (!cond) { break; }
}
}
rt.exitScope(param.scope);
param.scope = scope_bak;
return return_val;
},
*IterationStatement_for(interp, s, param) {
let return_val;
({
rt
} = interp);
const scope_bak = param.scope;
param.scope = "IterationStatement_for";
rt.enterScope(param.scope);
if (s.Initializer) {
if (s.Initializer.type === "Declaration") {
yield* interp.visit(interp, s.Initializer, param);
} else {
yield* interp.visit(interp, s.Initializer, param);
}
}
while (true) {
if (s.Expression != null) {
let cond = yield* interp.visit(interp, s.Expression, param);
cond = rt.cast(rt.boolTypeLiteral, cond).v;
if (!cond) { break; }
}
const r = yield* interp.visit(interp, s.Statement, param);
if (r instanceof Array) {
let end_loop;
switch (r[0]) {
case "continue":
break;
case "break":
end_loop = true;
break;
case "return":
return_val = r;
end_loop = true;
break;
}
if (end_loop) { break; }
}
if (s.Loop) {
yield* interp.visit(interp, s.Loop, param);
}
}
rt.exitScope(param.scope);
param.scope = scope_bak;
return return_val;
},
JumpStatement_goto(interp, s, param) {
({
rt
} = interp);
rt.raiseException("not implemented");
},
JumpStatement_continue(interp, s, param) {
({
rt
} = interp);
return ["continue"];
},
JumpStatement_break(interp, s, param) {
({
rt
} = interp);
return ["break"];
},
*JumpStatement_return(interp, s, param) {
({
rt
} = interp);
if (s.Expression) {
const ret = yield* interp.visit(interp, s.Expression, param);
return [
"return",
ret
];
}
return ["return"];
},
IdentifierExpression(interp, s, param) {
({
rt
} = interp);
return rt.readVar(s.Identifier);
},
*ParenthesesExpression(interp, s, param) {
({
rt
} = interp);
return yield* interp.visit(interp, s.Expression, param);
},
*PostfixExpression_ArrayAccess(interp, s, param) {
({
rt
} = interp);
const ret = yield* interp.visit(interp, s.Expression, param);
const index = yield* interp.visit(interp, s.index, param);
const r = rt.getFunc(ret.t, rt.makeOperatorFuncName("[]"), [index.t])(rt, ret, index);
if (isGenerator(r)) {
return yield* r;
} else {
return r;
}
},
*PostfixExpression_MethodInvocation(interp, s, param) {
let bindThis;
({
rt
} = interp);
const ret = yield* interp.visit(interp, s.Expression, param);
// console.log "==================="
// console.log "s: " + JSON.stringify(s)
// console.log "==================="
const args: Variable[] = yield* (function* () {
const result = [];
for (const e of s.args) {
const thisArg = yield* interp.visit(interp, e, param);
// console.log "-------------------"
// console.log "e: " + JSON.stringify(e)
// console.log "-------------------"
result.push(thisArg);
}
return result;
}).call(this);
// console.log "==================="
// console.log "ret: " + JSON.stringify(ret)
// console.log "args: " + JSON.stringify(args)
// console.log "==================="
if (ret.v.bindThis != null) {
({
bindThis
} = ret.v);
} else {
bindThis = ret;
}
const r = rt.getFunc(ret.t, rt.makeOperatorFuncName("()"), args.map(e => e.t))(rt, ret, bindThis, ...args);
if (isGenerator(r)) {
return yield* r;
} else {
return r;
}
},
*PostfixExpression_MemberAccess(interp, s, param) {
({
rt
} = interp);
const ret = yield* interp.visit(interp, s.Expression, param);
return rt.getMember(ret, s.member);
},
*PostfixExpression_MemberPointerAccess(interp, s, param) {
let r;
({
rt
} = interp);
let ret = yield* interp.visit(interp, s.Expression, param);
if (rt.isPointerType(ret.t) && !rt.isFunctionType(ret.t)) {
const {
member
} = s;
ret = yield* rt.getFunc(ret.t, rt.makeOperatorFuncName("->"), [])(rt, ret);
return rt.getMember(ret, member);
} else {
const member = yield* interp.visit(interp, {
type: "IdentifierExpression",
Identifier: s.member
}, param);
ret = yield* rt.getFunc(ret.t, rt.makeOperatorFuncName("->"), [member.t])(rt, ret);
return rt.getMember(ret, member);
}
},
*PostfixExpression_PostIncrement(interp, s, param) {
({
rt
} = interp);
const ret = yield* interp.visit(interp, s.Expression, param);
const r = rt.getFunc(ret.t, rt.makeOperatorFuncName("++"), ["dummy"])(rt, ret, {
t: "dummy",
v: null
}
);
if (isGenerator(r)) {
return yield* r;
} else {
return r;
}
},
*PostfixExpression_PostDecrement(interp, s, param) {
({
rt
} = interp);
const ret = yield* interp.visit(interp, s.Expression, param);
const r = rt.getFunc(ret.t, rt.makeOperatorFuncName("--"), ["dummy"])(rt, ret, {
t: "dummy",
v: null
}
);
if (isGenerator(r)) {
return yield* r;
} else {
return r;
}
},
*UnaryExpression_PreIncrement(interp, s, param) {
({
rt
} = interp);
const ret = yield* interp.visit(interp, s.Expression, param);
const r = rt.getFunc(ret.t, rt.makeOperatorFuncName("++"), [])(rt, ret);
if (isGenerator(r)) {
return yield* r;
} else {
return r;
}
},
*UnaryExpression_PreDecrement(interp, s, param) {
({
rt
} = interp);
const ret = yield* interp.visit(interp, s.Expression, param);
const r = rt.getFunc(ret.t, rt.makeOperatorFuncName("--"), [])(rt, ret);
if (isGenerator(r)) {
return yield* r;
} else {
return r;
}
},
*UnaryExpression(interp, s, param) {
({
rt
} = interp);
const ret = yield* interp.visit(interp, s.Expression, param);
const r = rt.getFunc(ret.t, rt.makeOperatorFuncName(s.op), [])(rt, ret);
if (isGenerator(r)) {
return yield* r;
} else {
return r;
}
},
*UnaryExpression_Sizeof_Expr(interp, s, param) {
({
rt
} = interp);
const ret = yield* interp.visit(interp, s.Expression, param);
return rt.val(rt.intTypeLiteral, rt.getSize(ret));
},
*UnaryExpression_Sizeof_Type(interp, s, param) {
({
rt
} = interp);
const type = yield* interp.visit(interp, s.TypeName, param);
return rt.val(rt.intTypeLiteral, rt.getSizeByType(type));
},
*CastExpression(interp, s, param) {
({
rt
} = interp);
const ret = yield* interp.visit(interp, s.Expression, param);
const type = yield* interp.visit(interp, s.TypeName, param);
return rt.cast(type, ret);
},
TypeName(interp, s, param) {
({
rt
} = interp);
const typename = [];
for (const baseType of s.base) {
if (baseType !== "const") {
typename.push(baseType);
}
}
return rt.simpleType(typename);
},
*BinOpExpression(interp, s, param) {
({
rt
} = interp);
const {
op
} = s;
if (op === "&&") {
s.type = "LogicalANDExpression";
return yield* interp.visit(interp, s, param);
} else if (op === "||") {
s.type = "LogicalORExpression";
return yield* interp.visit(interp, s, param);
} else {
// console.log "==================="
// console.log "s.left: " + JSON.stringify(s.left)
// console.log "s.right: " + JSON.stringify(s.right)
// console.log "==================="
const left = yield* interp.visit(interp, s.left, param);
const right = yield* interp.visit(interp, s.right, param);
// console.log "==================="
// console.log "left: " + JSON.stringify(left)
// console.log "right: " + JSON.stringify(right)
// console.log "==================="
const r = rt.getFunc(left.t, rt.makeOperatorFuncName(op), [right.t])(rt, left, right);
if (isGenerator(r)) {
return yield* r;
} else {
return r;
}
}
},
*LogicalANDExpression(interp, s, param) {
let right;
({
rt
} = interp);
const left = yield* interp.visit(interp, s.left, param);
const lt = rt.types[rt.getTypeSignature(left.t)];
if ("&&" in lt) {
right = yield* interp.visit(interp, s.right, param);
const r = rt.getFunc(left.t, rt.makeOperatorFuncName("&&"), [right.t])(rt, left, right);
if (isGenerator(r)) {
return yield* r;
} else {
return r;
}
} else {
if (rt.cast(rt.boolTypeLiteral, left).v) {
return yield* interp.visit(interp, s.right, param);
} else {
return left;
}
}
},
*LogicalORExpression(interp, s, param) {
let right;
({
rt
} = interp);
const left = yield* interp.visit(interp, s.left, param);
const lt = rt.types[rt.getTypeSignature(left.t)];
if ("||" in lt) {
right = yield* interp.visit(interp, s.right, param);
const r = rt.getFunc(left.t, rt.makeOperatorFuncName("||"), [right.t])(rt, left, right);
if (isGenerator(r)) {
return yield* r;
} else {
return r;
}
} else {
if (rt.cast(rt.boolTypeLiteral, left).v) {
return left;
} else {
return yield* interp.visit(interp, s.right, param);
}
}
},
*ConditionalExpression(interp, s, param) {
({
rt
} = interp);
const cond = rt.cast(rt.boolTypeLiteral, (yield* interp.visit(interp, s.cond, param))).v;
if (cond) { return yield* interp.visit(interp, s.t, param); } else { return yield* interp.visit(interp, s.f, param); }
},
*ConstantExpression(interp, s, param) {
({
rt
} = interp);
return yield* interp.visit(interp, s.Expression, param);
},
*StringLiteralExpression(interp, s, param) {
return yield* interp.visit(interp, s.value, param);
},
StringLiteral(interp, s, param) {
({
rt
} = interp);
switch (s.prefix) {
case null:
let maxCode = -1;
let minCode = 1;
for (const i of s.value) {
const code = i.charCodeAt(0);
if (maxCode < code) { maxCode = code; }
if (minCode > code) { minCode = code; }
}
const {
limits
} = rt.config;
const typeName =
(maxCode <= limits["char"].max) && (minCode >= limits["char"].min) ?
"char"
:
"wchar_t";
return rt.makeCharArrayFromString(s.value, typeName);
case "L":
return rt.makeCharArrayFromString(s.value, "wchar_t");
case "u8":
return rt.makeCharArrayFromString(s.value, "char");
case "u":
return rt.makeCharArrayFromString(s.value, "char16_t");
case "U":
return rt.makeCharArrayFromString(s.value, "char32_t");
}
},
BooleanConstant(interp, s, param) {
({
rt
} = interp);
return rt.val(rt.boolTypeLiteral, s.value === "true" ? 1 : 0);
},
CharacterConstant(interp, s, param) {
({
rt
} = interp);
const a = s.Char;
if (a.length !== 1) {
rt.raiseException("a character constant must have and only have one character.");
}
return rt.val(rt.charTypeLiteral, a[0].charCodeAt(0));
},
*FloatConstant(interp, s, param) {
({
rt
} = interp);
const val = yield* interp.visit(interp, s.Expression, param);
return rt.val(rt.floatTypeLiteral, val.v);
},
DecimalConstant(interp, s, param) {
({
rt
} = interp);
return rt.val(rt.unsignedintTypeLiteral, parseInt(s.value, 10));
},
HexConstant(interp, s, param) {
({
rt
} = interp);
return rt.val(rt.unsignedintTypeLiteral, parseInt(s.value, 16));
},
BinaryConstant(interp, s, param) {
({
rt
} = interp);
return rt.val(rt.unsignedintTypeLiteral, parseInt(s.value, 2));
},
DecimalFloatConstant(interp, s, param) {
({
rt
} = interp);
return rt.val(rt.doubleTypeLiteral, parseFloat(s.value));
},
HexFloatConstant(interp, s, param) {
({
rt
} = interp);
return rt.val(rt.doubleTypeLiteral, parseInt(s.value, 16));
},
OctalConstant(interp, s, param) {
({
rt
} = interp);
return rt.val(rt.unsignedintTypeLiteral, parseInt(s.value, 8));
},
NamespaceDefinition(interp, s, param) {
({
rt
} = interp);
rt.raiseException("not implemented");
},
UsingDirective(interp, s, param) {
({
rt
} = interp);
const id = s.Identifier;
// rt.raiseException("not implemented");
},
UsingDeclaration(interp, s, param) {
({
rt
} = interp);
rt.raiseException("not implemented");
},
NamespaceAliasDefinition(interp, s, param) {
({
rt
} = interp);
rt.raiseException("not implemented");
},
unknown(interp, s, param) {
({
rt
} = interp);
rt.raiseException("unhandled syntax " + s.type);
}
};
}
*visit(interp: Interpreter, s: any, param?: any) {
let ret;
const {
rt
} = interp;
// console.log(`${s.sLine}: visiting ${s.type}`);
if ("type" in s) {
if (param === undefined) {
param = { scope: "global" };
}
const _node = this.currentNode;
this.currentNode = s;
if (s.type in this.visitors) {
const f = this.visitors[s.type];
if (isGeneratorFunction(f)) {
const x = f(interp, s, param);
if (x != null) {
if (isIterable(x)) {
ret = yield* x;
} else {
ret = yield x;
}
} else {
ret = yield null;
}
} else {
yield (ret = f(interp, s, param));
}
} else {
ret = this.visitors["unknown"](interp, s, param);
}
this.currentNode = _node;
} else {
this.currentNode = s;
this.rt.raiseException("untyped syntax structure");
}
return ret;
};
*run(tree: any, source: string, param?: any) {
this.rt.interp = this;
this.source = source;
return yield* this.visit(this, tree, param);
};
*arrayInit(dimensions: number[], init: any, type: VariableType, param: any): Generator<void, Variable, any> {
if (dimensions.length > 0) {
let val;
const curDim = dimensions[0];
if (init) {
if ((init.type === "Initializer_array") && (init.Initializers != null && curDim >= init.Initializers.length)) {
// last level, short hand init
if (init.Initializers.length === 0) {
const arr = new Array(curDim);
let i = 0;
while (i < curDim) {
arr[i] = {
type: "Initializer_expr",
shorthand: this.rt.defaultValue(type)
};
i++;
}
init.Initializers = arr;
} else if ((init.Initializers.length === 1) && this.rt.isIntegerType(type)) {
val = this.rt.cast(type, (yield* this.visit(this, init.Initializers[0].Expression, param)));
if ((val.v === -1) || (val.v === 0)) {
const arr = new Array(curDim);
let i = 0;
while (i < curDim) {
arr[i] = {
type: "Initializer_expr",
shorthand: this.rt.val(type, val.v)
};
i++;
}
init.Initializers = arr;
} else {
const arr = new Array(curDim);
arr[0] = this.rt.val(type, -1);
let i = 1;
while (i < curDim) {
arr[i] = {
type: "Initializer_expr",
shorthand: this.rt.defaultValue(type)
};
i++;
}
init.Initializers = arr;
}
} else {
const arr = new Array(curDim);
let i = 0;
while (i < init.Initializers.length) {
const _init = init.Initializers[i];
let initval;
if ("shorthand" in _init) {
initval = _init;
} else {
if (_init.type === "Initializer_expr") {
initval = {
type: "Initializer_expr",
shorthand: (yield* this.visit(this, _init.Expression, param))
};
} else if (_init.type === "Initializer_array") {
initval = {
type: "Initializer_expr",
shorthand: (yield* this.arrayInit(dimensions.slice(1), _init, type, param))
};
} else {
this.rt.raiseException("Not implemented initializer type: " + _init.type);
}
}
arr[i] = initval;
i++;
}
i = init.Initializers.length;
while (i < curDim) {
arr[i] = {
type: "Initializer_expr",
shorthand: this.rt.defaultValue(this.arrayType(dimensions.slice(1), type))
};
i++;
}
init.Initializers = arr;
}
} else if (init.type === "Initializer_expr") {
let initializer: Variable;
if ("shorthand" in init) {
initializer = init.shorthand;
} else {
initializer = yield* this.visit(this, init, param);
}
if (this.rt.isArrayType(initializer) && this.rt.isTypeEqualTo(type, initializer.t.eleType)) {
init = {
type: "Initializer_array",
Initializers: initializer.v.target.map(e => ({
type: "Initializer_expr",
shorthand: e
}))
};
} else {
this.rt.raiseException("cannot initialize an array to " + this.rt.makeValString(initializer), param.node);
}
} else {
this.rt.raiseException("dimensions do not agree, " + curDim + " != " + init.Initializers.length, param.node);
}
}
{
const arr: Variable[] = [];
const ret = this.rt.val(this.arrayType(dimensions, type), this.rt.makeArrayPointerValue(arr, 0), true);
let i = 0;
while (i < curDim) {
if (init && (i < init.Initializers.length)) {
arr[i] = yield* this.arrayInit(dimensions.slice(1), init.Initializers[i], type, param);
} else {
arr[i] = yield* this.arrayInit(dimensions.slice(1), null, type, param);
}
i++;
}
return ret;
}
} else {
if (init && (init.type !== "Initializer_expr")) {
this.rt.raiseException("dimensions do not agree, too few initializers", param.node);
}
let initval;
if (init) {
if ("shorthand" in init) {
initval = init.shorthand;
} else {
initval = yield* this.visit(this, init.Expression, param);
}
} else {
initval = this.rt.defaultValue(type);
}
const ret = this.rt.cast(this.arrayType(dimensions, type), initval);
ret.left = true;
return ret;
}
};
arrayType(dimensions: number[], type: any): ArrayType {
if (dimensions.length > 0) {
return this.rt.arrayPointerType(this.arrayType(dimensions.slice(1), type), dimensions[0]);
} else {
return type;
}
};
buildRecursivePointerType(pointer: any, basetype: VariableType, level: number): VariableType {
if (pointer && (pointer.length > level)) {
const type = this.rt.normalPointerType(basetype);
return this.buildRecursivePointerType(pointer, type, level + 1);
} else {
return basetype;
}
};
} | the_stack |
import os = require('os');
import path = require('path');
import underscore = require('underscore');
import asyncutil = require('../lib/base/asyncutil');
import cli = require('./cli')
import clipboard = require('./clipboard')
import consoleio = require('./console')
import key_agent = require('../lib/key_agent');
import nodefs = require('../lib/vfs/node');
import testLib = require('../lib/test')
import vfs_util = require('../lib/vfs/util');
import { delay } from '../lib/base/promise_util';
interface PromptReply {
match: RegExp
response: string
}
/** Fake terminal input/output implementation which
* returns canned input and stores 'output' for
* inspection in tests.
*/
class FakeIO implements consoleio.TermIO {
output: string[];
password: string;
passRequestCount: number;
replies: PromptReply[];
constructor() {
this.output = [];
this.passRequestCount = 0;
this.replies = [];
}
print(text: string): void {
this.output.push(text);
}
readLine(prompt: string): Promise<string> {
var reply = underscore.find(this.replies, (reply) => {
return prompt.match(reply.match) != null;
});
if (reply) {
return Promise.resolve(reply.response);
} else {
return Promise.reject<string>('No pattern matched the prompt: "' + prompt + '"');
}
}
readPassword(prompt: string): Promise<string> {
if (prompt.match('Master password')) {
++this.passRequestCount;
return Promise.resolve(this.password);
} else {
return this.readLine(prompt);
}
}
didPrint(pattern: RegExp): boolean {
var match = false;
this.output.forEach((line) => {
if (line.match(pattern)) {
match = true;
}
});
return match;
}
}
// fake key agent which mirrors the real agent in returning
// results asynchronously - whereas the default SimpleKeyAgent
// implementation updates keys synchronously
class FakeKeyAgent extends key_agent.SimpleKeyAgent {
private delay(): Promise<void> {
return delay<void>(null, 0);
}
addKey(id: string, key: string): Promise<void> {
return this.delay().then(() => {
return super.addKey(id, key);
});
}
listKeys(): Promise<string[]> {
return this.delay().then(() => {
return super.listKeys();
});
}
forgetKeys(): Promise<void> {
return this.delay().then(() => {
return super.forgetKeys();
});
}
decrypt(id: string, cipherText: string, params: key_agent.CryptoParams): Promise<string> {
return this.delay().then(() => {
return super.decrypt(id, cipherText, params);
});
}
encrypt(id: string, plainText: string, params: key_agent.CryptoParams): Promise<string> {
return this.delay().then(() => {
return super.encrypt(id, plainText, params);
});
}
}
// utility class for specifying responses to CLI
// prompts
class PromptMatcher {
private replies: PromptReply[];
private query: RegExp;
constructor(replies: PromptReply[], query: RegExp) {
this.replies = replies;
this.query = query;
}
with(response: string) {
this.replies.push({
match: this.query,
response: response
});
}
}
var TEST_VAULT_PATH = 'lib/test-data/test.agilekeychain';
function cloneVault(vaultPath: string): Promise<string> {
var fs = new nodefs.FileVFS('/');
var tempPath = path.join(<string>(<any>os).tmpdir(), 'test-vault');
return vfs_util.rmrf(fs, tempPath).then(() => {
return fs.stat(path.resolve(vaultPath));
}).then((srcFolder) => {
return vfs_util.cp(fs, srcFolder, tempPath);
}).then(() => {
return tempPath;
});
}
/** CLITest sets up an environment for a CLI test,
* including a cli.CLI instance with a fake console. clipboard
* and key agent.
*
* By default the test uses a shared read-only test vault.
* Use newVault() to create a copy of this if the test needs
* to modify items in the vault.
*/
class CLITest {
fakeTerm: FakeIO;
keyAgent: FakeKeyAgent;
fakeClipboard: clipboard.FakeClipboard;
private app: cli.CLI;
private assert: testLib.Assert;
private vaultPath: string;
constructor(assert: testLib.Assert) {
this.fakeClipboard = new clipboard.FakeClipboard();
this.fakeTerm = new FakeIO();
this.fakeTerm.password = 'logMEin';
this.keyAgent = new FakeKeyAgent();
this.app = new cli.CLI(this.fakeTerm, this.keyAgent, this.fakeClipboard);
this.assert = assert;
this.vaultPath = TEST_VAULT_PATH;
}
setVaultPath(path: string) {
this.vaultPath = path;
}
/** Create a new writable vault for testing. Subsequent run() calls
* will use this vault.
*/
newVault(): Promise<string> {
return cloneVault(TEST_VAULT_PATH).then((path) => {
this.vaultPath = path;
return path;
});
}
/** Run a CLI command, expecting it to exit successfully. */
run(...args: string[]): Promise<number> {
return this.runExpectingStatus.apply(this,(<any>[0]).concat(args));
}
/** Run a CLI command, expecting a given exit status */
runExpectingStatus(expectedStatus: number, ...args: string[]): Promise<number> {
var vaultArgs = ['--vault', this.vaultPath];
return this.app.exec(vaultArgs.concat(args)).then((status) => {
if (status != expectedStatus) {
console.log(args.join(' ') + ' FAILED');
console.log('>>> CLI OUTPUT');
console.log(this.fakeTerm.output.join('\n'));
console.log('<<<');
}
this.assert.equal(status, expectedStatus);
return status;
});
}
/** Create a matcher to set a canned reply to prompts from
* the CLI matching @p query
*/
replyTo(query: RegExp): PromptMatcher {
return new PromptMatcher(this.fakeTerm.replies, query);
}
}
testLib.addTest('list vault', (assert) => {
var env = new CLITest(assert);
return env.run('list')
.then(() => {
assert.ok(env.fakeTerm.didPrint(/Facebook.*Login/));
});
});
testLib.addTest('list vault with pattern', (assert) => {
var env = new CLITest(assert);
return env.run('list', '-p', 'nomatch')
.then(() => {
assert.ok(env.fakeTerm.didPrint(/0 matching item/));
return env.run('list', '-p', 'face');
})
.then(() => {
assert.ok(env.fakeTerm.didPrint(/1 matching item/));
assert.ok(env.fakeTerm.didPrint(/Facebook.*Login/));
});
});
testLib.addTest('wrong password', (assert) => {
var env = new CLITest(assert);
env.fakeTerm.password = 'wrong-password';
return env.runExpectingStatus(2, 'list')
.then(() => {
assert.ok(env.fakeTerm.didPrint(/Unlocking failed/));
});
});
testLib.addTest('show item', (assert) => {
var env = new CLITest(assert);
return env.run('show', 'facebook')
.then(() => {
assert.ok(env.fakeTerm.didPrint(/username.*john\.doe@gmail.com/));
assert.ok(env.fakeTerm.didPrint(/password.*Wwk-ZWc-T9MO/));
});
});
testLib.addTest('show overview', (assert) => {
var env = new CLITest(assert);
return env.run('show', '--format=overview', 'facebook')
.then(() => {
assert.ok(env.fakeTerm.didPrint(/Facebook.*Login/));
assert.ok(env.fakeTerm.didPrint(/ID: CA20BB325873446966ED1F4E641B5A36/));
});
});
testLib.addTest('show JSON', (assert) => {
var env = new CLITest(assert);
return env.run('show', '--format=json', 'facebook')
.then(() => {
assert.ok(env.fakeTerm.didPrint(/URLs/));
assert.ok(env.fakeTerm.didPrint(/"type": "T"/));
});
});
testLib.addTest('lock', (assert) => {
var env = new CLITest(assert);
env.fakeTerm.passRequestCount = 0;
return env.keyAgent.forgetKeys().then(() => {
return env.run('show', 'facebook')
}).then(() => {
assert.equal(env.fakeTerm.passRequestCount, 1);
assert.equal(env.keyAgent.keyCount(), 1);
return env.run('lock')
})
.then(() => {
assert.equal(env.keyAgent.keyCount(), 0);
return env.run('show', 'facebook')
})
.then(() => {
assert.equal(env.keyAgent.keyCount(), 1);
assert.equal(env.fakeTerm.passRequestCount, 2);
});
});
testLib.addTest('copy', (assert) => {
var env = new CLITest(assert);
return env.run('copy', 'facebook')
.then(() => {
assert.equal(env.fakeClipboard.data, 'Wwk-ZWc-T9MO');
return env.run('copy', 'facebook', 'user');
})
.then(() => {
assert.equal(env.fakeClipboard.data, 'john.doe@gmail.com');
return env.run('copy', 'facebook', 'web');
})
.then(() => {
assert.equal(env.fakeClipboard.data, 'facebook.com');
return env.runExpectingStatus(1, 'copy', 'facebook', 'no-such-field');
});
});
testLib.addTest('select matching item', (assert) => {
var env = new CLITest(assert);
env.replyTo(/Website/).with('facebook.com');
env.replyTo(/Username/).with('jane.smith@gmail.com');
env.replyTo(/Password/).with('jane');
env.replyTo(/Re-enter/).with('jane');
env.replyTo(/Select Item/).with('2');
return env.newVault().then(() => {
// add a second Facebook account to the vault
return env.run('add', 'login', 'Facebook (Jane)');
}).then(() => {
// copy an item from the vault. Since there are multiple items
// matching the pattern, the CLI will prompt to select one
return env.run('copy', 'facebook');
}).then(() => {
// check that the password for the right item was copied
assert.equal(env.fakeClipboard.data, 'jane');
});
});
testLib.addTest('add login', (assert) => {
var env = new CLITest(assert);
env.replyTo(/Website/).with('mydomain.com');
env.replyTo(/Username/).with('jim.smith@gmail.com');
env.replyTo(/Password/).with('testpass');
env.replyTo(/Re-enter/).with('testpass');
return env.newVault().then(() => {
return env.run('add', 'login', 'MyDomain')
}).then(() => {
return env.run('show', 'mydomain');
})
.then(() => {
assert.ok(env.fakeTerm.didPrint(/mydomain.com/));
assert.ok(env.fakeTerm.didPrint(/testpass/));
assert.ok(env.fakeTerm.didPrint(/jim\.smith@gmail\.com/));
});
});
testLib.addTest('add credit card', (assert) => {
var env = new CLITest(assert);
return env.newVault().then(() => {
return env.run('add', 'card', 'MasterCard');
}).then(() => {
return env.run('show', 'master');
}).then(() => {
assert.ok(env.fakeTerm.didPrint(/MasterCard \(Credit Card\)/));
});
});
testLib.addTest('trash/restore item', (assert) => {
var env = new CLITest(assert);
return env.newVault().then(() => {
return env.run('trash', 'facebook');
}).then(() => {
return env.run('show', 'facebook');
}).then(() => {
assert.ok(env.fakeTerm.didPrint(/In Trash: Yes/));
return env.run('restore', 'facebook');
}).then(() => {
env.fakeTerm.output = [];
return env.run('show', 'facebook');
}).then(() => {
assert.ok(!env.fakeTerm.didPrint(/In Trash/));
});
});
testLib.addTest('change password', (assert) => {
var env = new CLITest(assert);
env.replyTo(/Re-enter existing/).with('logMEin');
env.replyTo(/New password/).with('newpass');
env.replyTo(/Re-enter new/).with('newpass');
env.replyTo(/Hint for new/).with('the-hint');
return env.newVault().then(() => {
return env.run('set-password');
}).then(() => {
return env.run('lock');
}).then(() => {
env.fakeTerm.password = 'newpass';
return env.run('list');
});
});
testLib.addTest('item pattern formats', (assert) => {
var env = new CLITest(assert);
var patterns = ['facebook', 'FACEB', 'ca20', 'CA20'];
var tests: Array<() => Promise<any>> = [];
patterns.forEach((pattern, index) => {
tests.push(() => {
return env.run('show', pattern)
.then(() => {
assert.ok(env.fakeTerm.didPrint(/Facebook.*Login/));
return true;
});
});
});
return asyncutil.series(tests);
});
testLib.addTest('remove items', (assert) => {
var env = new CLITest(assert);
env.replyTo(/Do you really want to remove these 1 item\(s\)/).with('y');
return env.newVault().then(() => {
return env.run('remove', 'faceb');
}).then(() => {
return env.run('list');
}).then(() => {
assert.ok(env.fakeTerm.didPrint(/0 matching item\(s\)/));
});
});
testLib.addTest('generate password', (assert) => {
var env = new CLITest(assert);
return env.run('gen-password').then((status) => {
assert.ok(env.fakeTerm.didPrint(/[A-Za-z0-9]{3}-[A-Za-z0-9]{3}-[A-Za-z0-9]{4}/));
});
});
testLib.addTest('edit item - set field', (assert) => {
var env = new CLITest(assert);
env.replyTo(/New value for "username"/).with('newuser');
env.replyTo(/Password \(or/).with('newpass');
env.replyTo(/Re-enter/).with('newpass');
return env.newVault().then(() => {
return env.run('edit', 'faceb', 'set-field', 'pass');
}).then(() => {
return env.run('edit', 'faceb', 'set-field', 'user');
}).then(() => {
return env.run('show', 'faceb');
}).then(() => {
assert.ok(env.fakeTerm.didPrint(/username.*newuser/));
assert.ok(env.fakeTerm.didPrint(/password.*newpass/));
});
});
testLib.addTest('edit item - add section and field', (assert) => {
var env = new CLITest(assert);
return env.newVault().then(() => {
return env.run('edit', 'faceb', 'add-section', 'NewSection');
}).then(() => {
return env.run('edit', 'faceb', 'add-field', 'newsection', 'customfield', 'customvalue');
}).then(() => {
return env.run('show', 'faceb');
}).then(() => {
assert.ok(env.fakeTerm.didPrint(/NewSection/));
assert.ok(env.fakeTerm.didPrint(/customfield.*customvalue/));
});
});
testLib.addTest('edit item - remove field', (assert) => {
var env = new CLITest(assert);
return env.newVault().then(() => {
return env.run('edit', 'faceb', 'add-section', 'NewSection');
}).then(() => {
return env.run('edit', 'faceb', 'add-field', 'newsection', 'customfield', 'customvalue');
}).then(() => {
return env.run('edit', 'faceb', 'remove-field', 'customfield');
}).then(() => {
return env.run('show', 'faceb');
}).then(() => {
assert.ok(!env.fakeTerm.didPrint(/customfield/));
});
});
testLib.addTest('create new vault', (assert) => {
var env = new CLITest(assert);
env.replyTo(/New password/).with('vaultpass');
env.replyTo(/Re-enter new/).with('vaultpass');
env.replyTo(/Hint for new/).with('vault pass hint');
var newVaultPath = path.join(<string>(<any>os).tmpdir(), 'new-vault');
var fs = new nodefs.FileVFS('/');
return vfs_util.rmrf(fs, newVaultPath + '.agilekeychain').then(() => {
return env.run('new-vault', '--iterations', '100', newVaultPath);
}).then(() => {
assert.ok(env.fakeTerm.didPrint(/New vault created/));
// A '.agilekeychain' suffix is added to the end of the path if
// not specified on the command line
env.setVaultPath(newVaultPath + '.agilekeychain');
env.fakeTerm.password = 'vaultpass';
return env.run('list');
}).then(() => {
env.replyTo(/Website/).with('google.com');
env.replyTo(/Username/).with('john.doe@gmail.com');
env.replyTo(/Password/).with('-');
assert.ok(env.fakeTerm.didPrint(/0 matching/));
return env.run('add', 'login', 'google.com');
}).then(() => {
return env.run('show', 'google');
}).then(() => {
assert.ok(env.fakeTerm.didPrint(/john\.doe/));
});
});
testLib.addTest('create new vault with relative path', (assert) => {
var env = new CLITest(assert);
env.replyTo(/New password/).with('vaultpass');
env.replyTo(/Re-enter new/).with('vaultpass');
env.replyTo(/Hint for new/).with('vaultpass');
var relativePath = 'newvault';
return env.run('new-vault', '--iterations', '100', relativePath).then(() => {
assert.ok(env.fakeTerm.didPrint(/New vault created/));
var fs = new nodefs.FileVFS('/');
return vfs_util.rmrf(fs, path.resolve(relativePath + '.agilekeychain'));
});
});
testLib.addTest('repair items', (assert) => {
// This runs the 'repair' command in a vault where all
// items are valid. We should also check that it behaves
// as expected when there are items that do need to be
// repaired.
var env = new CLITest(assert);
return env.newVault().then(() => {
return env.run('repair')
}).then(() => {
assert.ok(env.fakeTerm.didPrint(/Checking 1 items/));
});
});
testLib.addTest('edit item - rename', (assert) => {
var env = new CLITest(assert);
return env.newVault().then(() => {
return env.run('edit', 'facebook', 'rename', 'newtitle');
}).then(() => {
return env.run('show', 'newtitle');
}).then(() => {
assert.ok(env.fakeTerm.didPrint(/username.*john\.doe@gmail.com/));
});
});
testLib.addTest('edit item - rename with empty title', (assert) => {
var env = new CLITest(assert);
return env.newVault().then(() => {
return env.runExpectingStatus(1, 'edit', 'facebook', 'rename', ' ');
}).then(() => {
assert.ok(env.fakeTerm.didPrint(/New item name must not be empty/));
});
});
testLib.start(); | the_stack |
import { assert } from 'chai';
import dotenv from 'dotenv';
import 'mocha';
import moment from 'moment';
import { getProviderWithFallback } from '@energyweb/utils-general';
import { Wallet, BigNumber } from 'ethers';
import { migrateIssuer, migratePrivateIssuer, migrateRegistry } from '../src/migrate';
import { CertificationRequest, IBlockchainProperties, Certificate } from '../src';
import { decodeData, encodeData } from '../src/blockchain-facade/CertificateUtils';
describe('Issuer', () => {
let blockchainProperties: IBlockchainProperties;
dotenv.config({
path: '.env.test'
});
const [web3Url] = process.env.WEB3.split(';');
const provider = getProviderWithFallback(web3Url);
const deviceOwnerPK = '0x622d56ab7f0e75ac133722cc065260a2792bf30ea3265415fe04f3a2dba7e1ac';
const deviceOwnerWallet = new Wallet(deviceOwnerPK, provider);
const issuerPK = '0x50397ee7580b44c966c3975f561efb7b58a54febedaa68a5dc482e52fb696ae7';
const issuerWallet = new Wallet(issuerPK, provider);
let timestamp = moment().subtract(10, 'year').unix();
const setActiveUser = (wallet: Wallet) => {
blockchainProperties.activeUser = wallet;
};
const createCertificationRequest = async (
fromTime?: number,
toTime?: number,
deviceId?: string,
forAddress?: string
) => {
setActiveUser(deviceOwnerWallet);
const generationFromTime = fromTime ?? timestamp;
// Simulate time moving forward 1 month
timestamp += 30 * 24 * 3600;
const generationToTime = toTime ?? timestamp;
const device = deviceId ?? '1';
const certificationRequest = await CertificationRequest.create(
generationFromTime,
generationToTime,
device,
blockchainProperties,
forAddress
);
return certificationRequest;
};
it('migrates Issuer and Registry', async () => {
const registry = await migrateRegistry(provider, issuerPK);
const issuer = await migrateIssuer(provider, issuerPK, registry.address);
const version = await issuer.version();
assert.equal(version, 'v0.1');
const registryAddress = await issuer.getRegistryAddress();
assert.equal(registryAddress, registry.address);
blockchainProperties = {
web3: provider,
activeUser: issuerWallet,
registry,
issuer
};
});
it('should be able to set private issuer contract', async () => {
const privateIssuer = await migratePrivateIssuer(
provider,
issuerPK,
blockchainProperties.issuer.address
);
await blockchainProperties.issuer.setPrivateIssuer(privateIssuer.address);
assert.equal(
await blockchainProperties.issuer.getPrivateIssuerAddress(),
privateIssuer.address
);
});
it('encodes and decodes data properly', async () => {
const generationStartTime = 1;
const generationEndTime = 2;
const deviceId = 'device123';
const metadata = '{ someMetaData: 123 }';
const encodedData = encodeData({
generationStartTime,
generationEndTime,
deviceId,
metadata
});
const decodedData = decodeData(encodedData);
assert.equal(generationStartTime, decodedData.generationStartTime);
assert.equal(generationEndTime, decodedData.generationEndTime);
assert.equal(deviceId, decodedData.deviceId);
assert.equal(metadata, decodedData.metadata);
});
it('gets all certification requests', async () => {
await createCertificationRequest();
await createCertificationRequest();
const allCertificationRequests = await CertificationRequest.getAll(blockchainProperties);
assert.equal(allCertificationRequests.length, 2);
});
it('user correctly requests issuance', async () => {
setActiveUser(deviceOwnerWallet);
const fromTime = timestamp;
// Simulate time moving forward 1 month
timestamp += 30 * 24 * 3600;
const toTime = timestamp;
const device = '1';
const certificationRequest = await createCertificationRequest(fromTime, toTime, device);
assert.isAbove(certificationRequest.id, -1);
assert.deepOwnInclude(certificationRequest, {
deviceId: device,
owner: deviceOwnerWallet.address,
fromTime,
toTime,
approved: false
} as Partial<CertificationRequest>);
});
it('issuer correctly approves issuance', async () => {
const volume = BigNumber.from(1e9);
let certificationRequest = await createCertificationRequest();
setActiveUser(issuerWallet);
const certificateId = await certificationRequest.approve(volume);
certificationRequest = await certificationRequest.sync();
assert.isTrue(certificationRequest.approved);
assert.isAbove(certificationRequest.issuedCertificateTokenId, 0);
const deviceOwnerBalance = await blockchainProperties.registry.balanceOf(
deviceOwnerWallet.address,
certificateId
);
assert.equal(deviceOwnerBalance.toString(), volume.toString());
});
it('user revokes a certificationRequest', async () => {
setActiveUser(deviceOwnerWallet);
let certificationRequest = await createCertificationRequest();
certificationRequest = await certificationRequest.sync();
assert.isFalse(certificationRequest.approved);
assert.isFalse(certificationRequest.revoked);
await certificationRequest.revoke();
certificationRequest = await certificationRequest.sync();
assert.isTrue(certificationRequest.revoked);
});
it('issuer should be able to mint more volume to an existing certificate', async () => {
setActiveUser(deviceOwnerWallet);
const volume = BigNumber.from(1e9);
let certificationRequest = await createCertificationRequest();
setActiveUser(issuerWallet);
certificationRequest = await certificationRequest.sync();
const certificateId = await certificationRequest.approve(volume);
assert.exists(certificationRequest.issuedCertificateTokenId);
let certificate = await new Certificate(certificateId, blockchainProperties).sync();
assert.equal(certificate.owners[deviceOwnerWallet.address], volume.toString());
const additionalVolumeToMint = BigNumber.from(1e9);
const mintTx = await certificate.mint(deviceOwnerWallet.address, additionalVolumeToMint);
await mintTx.wait();
certificate = await certificate.sync();
assert.equal(
certificate.owners[deviceOwnerWallet.address],
volume.add(additionalVolumeToMint).toString()
);
});
it('issuer should not be able to mint more volume to an existing certificate thats issued by a different issuer', async () => {
setActiveUser(deviceOwnerWallet);
const volume = BigNumber.from(1e9);
let certificationRequest = await createCertificationRequest();
setActiveUser(issuerWallet);
certificationRequest = await certificationRequest.sync();
const certificateId = await certificationRequest.approve(volume);
let certificate = await new Certificate(certificateId, blockchainProperties).sync();
const attackerIssuerContract = await migrateIssuer(
provider,
issuerPK,
blockchainProperties.registry.address
);
certificate.blockchainProperties = {
...certificate.blockchainProperties,
issuer: attackerIssuerContract
};
const additionalVolumeToMint = BigNumber.from(1e9);
let failed = false;
try {
const mintTx = await certificate.mint(
deviceOwnerWallet.address,
additionalVolumeToMint
);
await mintTx.wait();
} catch (error) {
failed = true;
}
assert.isTrue(failed);
});
it('issuer should be able to revoke a certificationRequest', async () => {
setActiveUser(issuerWallet);
let certificationRequest = await createCertificationRequest();
certificationRequest = await certificationRequest.sync();
assert.isFalse(certificationRequest.revoked);
await certificationRequest.revoke();
certificationRequest = await certificationRequest.sync();
assert.isTrue(certificationRequest.revoked);
});
it('user shouldnt be able to revoke an approved certificationRequest', async () => {
setActiveUser(deviceOwnerWallet);
const volume = BigNumber.from(1e9);
let certificationRequest = await createCertificationRequest();
setActiveUser(issuerWallet);
certificationRequest = await certificationRequest.sync();
await certificationRequest.approve(volume);
setActiveUser(deviceOwnerWallet);
certificationRequest = await certificationRequest.sync();
assert.isTrue(certificationRequest.approved);
assert.isFalse(certificationRequest.revoked);
let failed = false;
try {
await certificationRequest.revoke();
} catch (e) {
failed = true;
}
assert.isTrue(failed);
});
it('should request the same certificate after revoking one', async () => {
setActiveUser(deviceOwnerWallet);
const fromTime = timestamp;
// Simulate time moving forward 1 month
timestamp += 30 * 24 * 3600;
const toTime = timestamp;
const device = '1';
let certificationRequest = await createCertificationRequest(fromTime, toTime, device);
certificationRequest = await certificationRequest.sync();
await certificationRequest.revoke();
certificationRequest = await certificationRequest.sync();
const newCertificationRequest = await createCertificationRequest(fromTime, toTime, device);
assert.exists(newCertificationRequest);
});
it('should be able to request for other address', async () => {
setActiveUser(deviceOwnerWallet);
const fromTime = timestamp;
// Simulate time moving forward 1 month
timestamp += 30 * 24 * 3600;
const toTime = timestamp;
const device = '1';
const certificationRequest = await createCertificationRequest(
fromTime,
toTime,
device,
issuerWallet.address
);
assert.isOk(certificationRequest);
});
}); | the_stack |
import type Armature from '../armature/Armature'
import type Bone from '../armature/Bone';
import type Clip from './Clip';
import { vec3, quat } from 'gl-matrix';
import QuatUtil from '../maths/QuatUtil';
import Vec3Util from '../maths/Vec3Util';
import Animator from './Animator';
import Pose from '../armature/Pose';
import BoneMap, { BoneInfo, BoneChain } from '../armature/BoneMap';
//#endregion
//#region TYPES
class Source{
arm : Armature;
pose : Pose;
posHip = vec3.create();
constructor( arm: Armature ){
this.arm = arm;
this.pose = arm.newPose();
}
}
class BoneLink{
fromIndex : number;
fromName : string;
toIndex : number;
toName : string;
quatFromParent = quat.create(); // Cache the Bone's Parent WorldSpace Quat
quatDotCheck = quat.create(); // Cache the FROM TPOSE Bone's Worldspace Quaternion for DOT Checking
wquatFromTo = quat.create(); // Handles "FROM WS" -> "TO WS" Transformation
toWorldLocal = quat.create(); // Cache Result to handle "TO WS" -> "TO LS" Transformation
constructor( fIdx: number, fName:string, tIdx:number, tName:string ){
this.fromIndex = fIdx;
this.fromName = fName;
this.toIndex = tIdx
this.toName = tName;
}
bind( fromTPose: Pose, toTPose: Pose ): this{
const fBone : Bone = fromTPose.bones[ this.fromIndex ];
const tBone : Bone = toTPose.bones[ this.toIndex ];
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// What is the From Parent WorldSpace Transform can we use?
quat.copy( this.quatFromParent,
( fBone.pidx != -1 )?
fromTPose.bones[ fBone.pidx ].world.rot : // Bone's Parent
fromTPose.offset.rot // Pose Offset, most often its an identity value
);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Caching the parent Bone of the "To Bone" and inverting it
// This will make it easy to convert the final results back
// to the TO Bone's Local Space.
if( tBone.pidx != -1 )
quat.invert( this.toWorldLocal, toTPose.bones[ tBone.pidx ].world.rot );
else
quat.invert( this.toWorldLocal, toTPose.offset.rot );
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// This Transform is to handle Transforming the "From TPose Bone" to
// be equal to "To TPose Bone". Basiclly allow to shift
// the FROM worldspace to the TO worldspace.
//this.wquatFromTo
// .fromInvert( fBone.world.rot ) // What is the diff from FBone WorldSpace...
// .mul( tBone.world.rot ); // to TBone's WorldSpace
quat.invert( this.wquatFromTo, fBone.world.rot ); // What is the diff from FBone WorldSpace
quat.mul( this.wquatFromTo, this.wquatFromTo, tBone.world.rot ); // ...to TBone's WorldSpace
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//this.quatDotCheck.copy( fBone.world.rot );
quat.copy( this.quatDotCheck, fBone.world.rot );
return this;
}
}
//#endregion
class Retarget{
//#region MAIN
hipScale = 1; // Retarget Hip Position
anim = new Animator(); // Animate Clip
map : Map< string, BoneLink > = new Map(); // All the Linked Bones
from !: Source; // Armature for the Clip
to !: Source; // Armature to retarget animation for
//#endregion
//#region SETTERS
setClip( c:Clip ): this {
this.anim.setClip( c );
return this;
}
setClipArmature( arm: Armature ){
this.from = new Source( arm );
return this;
}
setClipPoseOffset( rot ?: quat, pos ?: vec3, scl ?: vec3 ): this{
const p = this.from.pose;
// Armature has a Transform on itself sometimes
// Apply it as the Offset Transform that gets preApplied to the root
//if( rot ) p.offset.rot.copy( rot );
//if( pos ) p.offset.pos.copy( pos );
//if( scl ) p.offset.scl.copy( scl );
if( rot ) quat.copy( p.offset.rot, rot );
if( pos ) vec3.copy( p.offset.pos, pos );
if( scl ) vec3.copy( p.offset.scl, scl );
return this;
}
setTargetArmature( arm: Armature ){
this.to = new Source( arm );
return this;
}
//#endregion
//#region GETTERS
getClipPose( doUpdate=false, incOffset=false ): Pose{
if( doUpdate ) this.from.pose.updateWorld( incOffset );
return this.from.pose;
}
getTargetPose( doUpdate=false, incOffset=false ): Pose{
if( doUpdate ) this.to.pose.updateWorld( incOffset );
return this.to.pose;
}
//#endregion
//#region METHODS
bind(): boolean{
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Compute a Common Bone Map to make it easy to compare
// and link together
const mapFrom = new BoneMap( this.from.arm );
const mapTo = new BoneMap( this.to.arm );
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Make sure the pose worldspace data is setup
// and using any offset that pre exists.
// Has to be done on bind because TPoses can be set
// after calling setTargetAramature / setClipArmature
this.from.pose.updateWorld( true );
this.to.pose.updateWorld( true );
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Loop the FROM map looking for any Matches in the TO map
let i : number,
fLen : number,
tLen : number,
len : number,
lnk : BoneLink,
k : string,
bFrom : BoneInfo | BoneChain,
bTo : BoneInfo | BoneChain | undefined;
for( [ k, bFrom ] of mapFrom.bones ){
//-------------------------------------------------
// Check if there is a Matching Bone
bTo = mapTo.bones.get( k );
if( !bTo ){ console.warn( 'Target missing bone :', k ); continue; }
//-------------------------------------------------
// Single Bones
if( bFrom instanceof BoneInfo && bTo instanceof BoneInfo ){
lnk = new BoneLink( bFrom.index, bFrom.name, bTo.index, bTo.name );
lnk.bind( this.from.pose, this.to.pose );
this.map.set( k, lnk );
//-------------------------------------------------
// Bone Chain
}else if( bFrom instanceof BoneChain && bTo instanceof BoneChain ){
fLen = bFrom.items.length;
tLen = bTo.items.length;
if( fLen == 1 && tLen == 1 ){
//++++++++++++++++++++++++++++++++++++++
// Chain of both are just a single bone
this.map.set( k, new BoneLink(
bFrom.items[0].index,
bFrom.items[0].name,
bTo.items[0].index,
bTo.items[0].name
).bind( this.from.pose, this.to.pose ) );
}else if( fLen >= 2 && tLen >=2 ){
//++++++++++++++++++++++++++++++++++++++
// Link the Chain ends first, then fill in the middle bits
// Match up the first bone on each chain.
this.map.set( k + "_0", new BoneLink(
bFrom.items[0].index,
bFrom.items[0].name,
bTo.items[0].index,
bTo.items[0].name
).bind( this.from.pose, this.to.pose ) );
// Match up the Last bone on each chain.
this.map.set( k + "_x", new BoneLink(
bFrom.items[ fLen-1 ].index,
bFrom.items[ fLen-1 ].name,
bTo.items[ tLen-1 ].index,
bTo.items[ tLen-1 ].name
).bind( this.from.pose, this.to.pose ) );
// Match any middle bits
for( i=1; i < Math.min( fLen-1, tLen-1 ); i++ ){
lnk = new BoneLink(
bFrom.items[i].index,
bFrom.items[i].name,
bTo.items[i].index,
bTo.items[i].name
);
lnk.bind( this.from.pose, this.to.pose );
this.map.set( k + "_" + i, lnk );
}
}else{
//++++++++++++++++++++++++++++++++++++++
// Try to match up the bones
len = Math.min( bFrom.items.length, bTo.items.length );
for( i=0; i < len; i++ ){
lnk = new BoneLink(
bFrom.items[i].index,
bFrom.items[i].name,
bTo.items[i].index,
bTo.items[i].name
);
lnk.bind( this.from.pose, this.to.pose );
this.map.set( k + "_" + i, lnk );
}
}
//-------------------------------------------------
// Match but the data is mismatch, one is a bone while the other is a chain.
}else{
console.warn( 'Bone Mapping is mix match of info and chain', k );
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Data to handle Hip Position Retargeting
const hip = this.map.get( 'hip' );
if( hip ){
const fBone = this.from.pose.bones[ hip.fromIndex ]; // TBone State
const tBone = this.to.pose.bones[ hip.toIndex ];
//this.from.posHip.copy( fBone.world.pos ).nearZero(); // Cache to Retargeting
//this.to.posHip.copy( tBone.world.pos ).nearZero();
Vec3Util.nearZero( this.from.posHip, fBone.world.pos ); // Cache for Retargeting
Vec3Util.nearZero( this.to.posHip, tBone.world.pos );
//this.hipScale = Math.abs( this.to.posHip.y / this.from.posHip.y ); // Retarget Scale FROM -> TO
this.hipScale = Math.abs( this.to.posHip[1] / this.from.posHip[1] ); // Retarget Scale FROM -> TO
}
return true;
}
animateNext( dt: number ) : this{
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Run Animation & Update the FROM Pose with the results
this.anim
.update( dt )
.applyPose( this.from.pose );
this.from.pose.updateWorld( true );
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
this.applyRetarget();
this.to.pose.updateWorld( true );
return this;
}
atKey( k: number ) : this{
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Set Animator to keyframe & update the FROM Pose with the results
this.anim
.atKey( k )
.applyPose( this.from.pose );
this.from.pose.updateWorld( true );
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
this.applyRetarget();
this.to.pose.updateWorld( true );
return this;
}
applyRetarget(){
const fPose = this.from.pose.bones;
const tPose = this.to.pose.bones;
const diff = quat.create();
const tmp = quat.create();
let fBone : Bone;
let tBone : Bone;
let bl : BoneLink;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Update the bone rotations
for( bl of this.map.values() ){
fBone = fPose[ bl.fromIndex ];
tBone = tPose[ bl.toIndex ];
//------------------------------------
// Move Bone's Animated LocalSpace into the TPose WorldSpace
// Using the Cached Quat when the TPoses where bound.
// The FromTo Rotation is based on the TPose, so the animated
// pose needs to live in that world, as if out of the whole pose
// this is the only bone has been modified.
//diff.fromMul( bl.quatFromParent, fBone.local.rot );
quat.mul( diff, bl.quatFromParent, fBone.local.rot );
//------------------------------------
// Do dot check to prevent artifacts when applyin to vertices
//if( Quat.dot( diff, bl.quatDotCheck ) < 0 ) diff.mul( tmp.fromNegate( bl.wquatFromTo ) );
//else diff.mul( bl.wquatFromTo );
if( quat.dot( diff, bl.quatDotCheck ) < 0 ){
QuatUtil.negate( tmp, bl.wquatFromTo );
quat.mul( diff, diff, tmp );
}else{
quat.mul( diff, diff, bl.wquatFromTo );
}
//diff.pmul( bl.toWorldLocal ); // Move to Local Space
quat.mul( diff, bl.toWorldLocal, diff ); // Move to Local Space
//tBone.local.rot.copy( diff ); // Save
quat.copy( tBone.local.rot, diff ); // Save
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Apply Bone Translations
const hip = this.map.get( 'hip' );
if( hip ){
const fBone = this.from.pose.bones[ hip.fromIndex ];
const tBone = this.to.pose.bones[ hip.toIndex ];
//const v = Vec3
// .sub( fBone.world.pos, this.from.posHip ) // Change Since TPose
// .scale( this.hipScale ) // Scale Diff to Target's Scale
// .add( this.to.posHip ) // Add Scaled Diff to Target's TPose Position
const v = vec3.create();
vec3.sub( v, fBone.world.pos, this.from.posHip ); // Change Since TPose
vec3.scale( v, v, this.hipScale ); // Scale Diff to Target's Scale
vec3.add( v, v, this.to.posHip ); // Add Scaled Diff to Target's TPose Position
//tBone.local.pos.copy( v ); // Save To Target
vec3.copy( tBone.local.pos, v );
}
}
//#endregion
}
export default Retarget; | the_stack |
const TSL2591_I2C_ADDRESS = 0x29 //I2C address of the TSL2591 (Page 28)
//See Page 13 for full register description of TSL2591
const TSL2591_REGISTER_COMMAND = 0xA0 // Select Command Register. CMD: Must write as 1 when addressing COMMAND register + TRANSACTION: 01 Normal Operation (1010 0000)
const TSL2591_REGISTER_COMMAND_SET_INT = 0xE4 // Interrupt set – forces an interrupt (11100100)
const TSL2591_REGISTER_COMMAND_CLEAR_ALS_INT = 0xE6 // Clears ALS interrupt (11100110)
const TSL2591_REGISTER_COMMAND_CLEAR_ALS_NO_PERS_INT = 0xE7 // Clears ALS and no persist ALS interrupt (11100111)
const TSL2591_REGISTER_COMMAND_CLEAR_NO_PERS_INT = 0xEA // Clears no persist ALS interrupt (11101010)
const TSL2591_REGISTER_ENABLE = 0x00 // The ENABLE register is used to power the device on/off, enable functions and interrupts..
const TSL2591_REGISTER_NPIEN_ENABLE = 0x80 // No Persist Interrupt Enable. When asserted NP Threshold conditions will generate an interrupt, bypassing the persist filter.
const TSL2591_REGISTER_SAI_ENABLE = 0x40 // Sleep after interrupt. When asserted, the device will power down at the end of an ALS cycle if an interrupt has been generated.
const TSL2591_REGISTER_AIEN_ENABLE = 0x10 // ALS Interrupt Enable. When asserted permits ALS interrupts to be generated, subject to the persist filter.
const TSL2591_REGISTER_AEN_ENABLE = 0x02 // ALS Enable. This field activates ALS function. Writing a one activates the ALS. Writing a zero disables the ALS.
const TSL2591_REGISTER_PON_ENABLE = 0x01 // Power ON. This field activates the internal oscillator to permit the timers and ADC channels to operate. Writing a one activates the oscillator. Writing a zero disables the oscillator.
const TSL2591_REGISTER_POFF_ENABLE = 0x00 // Power OFF. This field activates the internal oscillator to permit the timers and ADC channels to operate. Writing a one activates the oscillator. Writing a zero disables the oscillator.
const TSL2591_REGISTER_CONTROL = 0x01 // The CONTROL register is used to configure the ALS gain and integration time. In addition, a system reset is provided. Upon power up, the CONTROL register resets to 0x00.
const TSL2591_REGISTER_CONTROL_SRESET = 0x80 // System reset. When asserted, the device will reset equivalent to a power-on reset. SRESET is self-clearing.
const TSL2591_REGISTER_PID = 0x11 // The PID register provides an identification of the devices package. This register is a read-only register whose value never changes.
const TSL2591_REGISTER_ID = 0x12 // The ID register provides the device identification. This register is a read-only register whose value never changes.
const TSL2591_REGISTER_STATUS = 0x13 // The Status Register provides the internal status of the device. This register is read only.
const TSL2591_REGISTER_STATUS_NPINTR = 0x20 // No-persist Interrupt. Indicates that the device has encountered a no-persist interrupt condition.
const TSL2591_REGISTER_STATUS_AINT = 0x10 // ALS Interrupt. Indicates that the device is asserting an ALS interrupt.
const TSL2591_REGISTER_STATUS_AVALID = 0x01 // ALS Valid. Indicates that the ADC channels have completed an integration cycle since the AEN bit was asserted.
const TSL2591_REGISTER_C0DATAL = 0x14 // ALS CH0 data low byte
const TSL2591_REGISTER_C0DATAH = 0x15 // ALS CH0 data high byte
const TSL2591_REGISTER_C1DATAL = 0x16 // ALS CH1 data low byte
const TSL2591_REGISTER_C1DATAH = 0x17 // ALS CH1 data high byte
const TSL2591_REGISTER_AILTL = 0x04 // ALS low threshold lower byte
const TSL2591_REGISTER_AILTH = 0x05 // ALS low threshold upper byte
const TSL2591_REGISTER_AIHTL = 0x06 // ALS high threshold lower byte
const TSL2591_REGISTER_AIHTH = 0x07 // ALS high threshold upper byte
const TSL2591_REGISTER_NPAILTL = 0x08 // No Persist ALS low threshold lower byte
const TSL2591_REGISTER_NPAILTH = 0x09 // No Persist ALS low threshold upper byte
const TSL2591_REGISTER_NPAIHTL = 0x0A // No Persist ALS high threshold lower byte
const TSL2591_REGISTER_NPAIHTH = 0x0B // No Persist ALS high threshold upper byte
const TSL2591_REGISTER_PERSIST = 0x0B // The Interrupt persistence filter sets the number of consecutive out-of-range ALS cycles necessary to generate an interrupt. Out-of-range is determined by comparing C0DATA (0x14 and 0x15) to the interrupt threshold registers (0x04 - 0x07). Note that the no-persist ALS interrupt is not affected by the interrupt persistence filter. Upon power up, the interrupt persistence filter register resets to 0x00.
/* #region Enums for Modes, etc */
// ALS gain sets the gain of the internal integration amplifiers for both photodiode channels.
enum TSL2591_AGAIN {
AGAIN_LOW = 0x00, // Low gain mode
AGAIN_MEDIUM = 0x10, // Medium gain mode
AGAIN_HIGH = 0x20, // High gain mode
AGAIN_MAX = 0x30 // Maximum gain mode
}
// ALS time sets the internal ADC integration time for both photodiode channels.
enum TSL2591_ATIME {
ATIME_100_MS = 0x00, // 100 ms
ATIME_200_MS = 0x01, // 200 ms
ATIME_300_MS = 0x02, // 300 ms
ATIME_400_MS = 0x03, // 400 ms
ATIME_500_MS = 0x04, // 500 ms
ATIME_600_MS = 0x05 // 600 ms
}
/* #endregion */
namespace RegisterHelper {
/**
* Write register of the address location
*/
export function writeRegister(addr: number, reg: number, dat: number): void {
let _registerBuffer = pins.createBuffer(2);
_registerBuffer[0] = reg;
_registerBuffer[1] = dat;
pins.i2cWriteBuffer(addr, _registerBuffer);
}
/**
* Read a 8-byte register of the address location
*/
export function readRegister8(addr: number, reg: number): number {
pins.i2cWriteNumber(addr, reg, NumberFormat.UInt8BE);
return pins.i2cReadNumber(addr, NumberFormat.UInt8BE);
}
/**
* Read a (UInt16) 16-byte register of the address location
*/
export function readRegisterUInt16(addr: number, reg: number): number {
pins.i2cWriteNumber(addr, reg, NumberFormat.UInt8BE);
return pins.i2cReadNumber(addr, NumberFormat.UInt16LE);
}
/**
* Read a (Int16) 16-byte register of the address location
*/
export function readRegisterInt16(addr: number, reg: number): number {
pins.i2cWriteNumber(addr, reg, NumberFormat.UInt8BE);
return pins.i2cReadNumber(addr, NumberFormat.Int16LE);
}
}
namespace TSL2591 {
let TSL2591_I2C_ADDR = TSL2591_I2C_ADDRESS;
export let isConnected = false;
let atimeIntegrationValue: TSL2591_ATIME;
let gainSensorValue: TSL2591_AGAIN;
export function initSensor()
{
//REGISTER FORMAT: CMD | TRANSACTION | ADDRESS
//REGISTER READ: TSL2591_REGISTER_COMMAND (0x80) | TSL2591_REGISTER_COMMAND_NORMAL (0x20) | TSL2591_REGISTER_ID (0x12)
let device_id = RegisterHelper.readRegister8(TSL2591_I2C_ADDR, TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_ID)
//Check that device Identification = 0x50 (Page 19)
if (device_id != 0x50 ) {
isConnected = false;
}
else
isConnected = true;
}
export function setATIME(atime: TSL2591_ATIME)
{
atimeIntegrationValue = atime;
configureSensor(atimeIntegrationValue,gainSensorValue);
}
export function setGAIN(gain: TSL2591_AGAIN)
{
gainSensorValue = gain;
configureSensor(atimeIntegrationValue,gainSensorValue);
}
export function configureSensor(atime: TSL2591_ATIME,gain: TSL2591_AGAIN)
{
//Always make sure the sensor is connected. Useful for cases when this block is used but the sensor wasn't set randomly.
while (!isConnected)
{
initSensor();
}
atimeIntegrationValue = atime;
gainSensorValue = gain;
//Turn sensor on
enableSensor();
//REGISTER FORMAT: CMD | TRANSACTION | ADDRESS
//REGISTER VALUE: TSL2591_REGISTER_COMMAND (0x80) | TSL2591_REGISTER_CONTROL (0x01)
//REGISTER WRITE: atimeIntegrationValue | gainSensorValue
RegisterHelper.writeRegister(TSL2591_I2C_ADDR,TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_CONTROL, atimeIntegrationValue | gainSensorValue);
//Turn sensor off
disableSensor();
}
export function enableSensor()
{
//1 - First set the command bit to 1, to let the device be set
//2 - Next, turn it on, then enable ALS, enable ALS Interrupt, and enable No Persist Interrupt
if (isConnected)
//REGISTER FORMAT: CMD | TRANSACTION | ADDRESS
//REGISTER VALUE: TSL2591_REGISTER_COMMAND (0x80) | TSL2591_REGISTER_COMMAND_NORMAL (0x20) | TSL2591_REGISTER_ENABLE (0x00)
//REGISTER WRITE: TSL2591_REGISTER_PON_ENABLE (0x01) | TSL2591_REGISTER_AEN_ENABLE (0x02) | TSL2591_REGISTER_AIEN_ENABLE (0x10) | TSL2591_REGISTER_NPIEN_ENABLE (0x80)
RegisterHelper.writeRegister(TSL2591_I2C_ADDR,TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_ENABLE, TSL2591_REGISTER_PON_ENABLE | TSL2591_REGISTER_AEN_ENABLE | TSL2591_REGISTER_AIEN_ENABLE | TSL2591_REGISTER_NPIEN_ENABLE)
else
return;
}
export function disableSensor()
{
//1 - First set the command bit to 1, to let the device be set
//2 - Next, turn it off
if (isConnected)
//REGISTER FORMAT: CMD | TRANSACTION | ADDRESS
//REGISTER VALUE: TSL2591_REGISTER_COMMAND (0x80) | TSL2591_REGISTER_COMMAND_NORMAL (0x20) | TSL2591_REGISTER_ENABLE (0x00)
//REGISTER WRITE: TSL2591_REGISTER_POFF_ENABLE (0x00)
RegisterHelper.writeRegister(TSL2591_I2C_ADDR,TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_ENABLE, TSL2591_REGISTER_POFF_ENABLE)
else
return;
}
export function getRawLuminosity(): NumberFormat.UInt32LE
{
//Always make sure the sensor is connected. Useful for cases when this block is used but the sensor wasn't set randomly.
while (!isConnected)
{
initSensor();
}
//Turn sensor on
enableSensor();
//Wait for the ADC of the TSL2591 to complete before reading values
for (let x = 0; x <atimeIntegrationValue; x++) {
basic.pause(120);
}
let yChannel: NumberFormat.UInt32LE;
//REGISTER FORMAT: CMD | TRANSACTION | ADDRESS
//REGISTER READ: TSL2591_REGISTER_COMMAND (0x80) | TSL2591_REGISTER_COMMAND_NORMAL (0x20) | TSL2591_REGISTER_C1DATAL (0x16)
yChannel = RegisterHelper.readRegisterUInt16(TSL2591_I2C_ADDR,TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_C1DATAL);
yChannel <<= 16;
yChannel = RegisterHelper.readRegisterUInt16(TSL2591_I2C_ADDR,TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_C0DATAL);
//Turn sensor off
disableSensor();
return yChannel;
}
export function getFullSpectrum(): NumberFormat.UInt32LE
{
let fs = getRawLuminosity();
return (fs & 0xFFFF);
}
export function getInfraredSpectrum(): NumberFormat.UInt32LE
{
let is = getRawLuminosity();
return (is >> 16);
}
export function getVisibleSpectrum(): NumberFormat.UInt32LE
{
let vs = getRawLuminosity();
return ( (vs & 0xFFFF) - (vs >> 16));
}
export function start(atime: TSL2591_ATIME,gain: TSL2591_AGAIN)
{
while (!isConnected)
{
initSensor();
}
configureSensor(atimeIntegrationValue,gainSensorValue);
disableSensor();
}
}
TSL2591.start(TSL2591_ATIME.ATIME_100_MS,TSL2591_AGAIN.AGAIN_MEDIUM);
basic.forever(function () {
basic.pause(2000);
serial.writeLine(TSL2591.isConnected + "");
serial.writeLine(TSL2591.getRawLuminosity() + "");
}) | the_stack |
let /**
* Returns the string representation of an ASCII encoded four byte buffer.
* @param buffer - a four-byte buffer to translate
* @return the corresponding string
*/
parseType = function (buffer: Uint8Array): string {
let result = '';
result += String.fromCharCode(buffer[0]);
result += String.fromCharCode(buffer[1]);
result += String.fromCharCode(buffer[2]);
result += String.fromCharCode(buffer[3]);
return result;
},
parseMp4Date = function (seconds: number): Date {
return new Date(seconds * 1000 - 2082844800000);
},
parseSampleFlags = function (flags: Uint8Array) {
return {
isLeading: (flags[0] & 0x0c) >>> 2,
dependsOn: flags[0] & 0x03,
isDependedOn: (flags[1] & 0xc0) >>> 6,
hasRedundancy: (flags[1] & 0x30) >>> 4,
paddingValue: (flags[1] & 0x0e) >>> 1,
isNonSyncSample: flags[1] & 0x01,
degradationPriority: (flags[2] << 8) | flags[3]
};
},
nalParse = function (avcStream) {
let avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
result = [],
i,
length;
for (i = 0; i < avcStream.length; i += length) {
length = avcView.getUint32(i);
i += 4;
switch (avcStream[i] & 0x1f) {
case 0x01:
result.push('NDR');
break;
case 0x05:
result.push('IDR');
break;
case 0x06:
result.push('SEI');
break;
case 0x07:
result.push('SPS');
break;
case 0x08:
result.push('PPS');
break;
case 0x09:
result.push('AUD');
break;
default:
result.push(avcStream[i] & 0x1f);
break;
}
}
return result;
},
// registry of handlers for individual mp4 box types
parse = {
// codingname, not a first-class box type. stsd entries share the
// same format as real boxes so the parsing infrastructure can be
// shared
avc1: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
return {
dataReferenceIndex: view.getUint16(6),
width: view.getUint16(24),
height: view.getUint16(26),
horizresolution: view.getUint16(28) + view.getUint16(30) / 16,
vertresolution: view.getUint16(32) + view.getUint16(34) / 16,
frameCount: view.getUint16(40),
depth: view.getUint16(74),
config: mp4toJSON(data.subarray(78, data.byteLength))
};
},
avcC: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength),
result = {
configurationVersion: data[0],
avcProfileIndication: data[1],
profileCompatibility: data[2],
avcLevelIndication: data[3],
lengthSizeMinusOne: data[4] & 0x03,
sps: [],
pps: []
},
numOfSequenceParameterSets = data[5] & 0x1f,
numOfPictureParameterSets,
nalSize,
offset,
i;
// iterate past any SPSs
offset = 6;
for (i = 0; i < numOfSequenceParameterSets; i++) {
nalSize = view.getUint16(offset);
offset += 2;
result.sps.push(new Uint8Array(data.subarray(offset, offset + nalSize)));
offset += nalSize;
}
// iterate past any PPSs
numOfPictureParameterSets = data[offset];
offset++;
for (i = 0; i < numOfPictureParameterSets; i++) {
nalSize = view.getUint16(offset);
offset += 2;
result.pps.push(new Uint8Array(data.subarray(offset, offset + nalSize)));
offset += nalSize;
}
return result;
},
btrt: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
return {
bufferSizeDB: view.getUint32(0),
maxBitrate: view.getUint32(4),
avgBitrate: view.getUint32(8)
};
},
esds: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
return {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
esId: (data[6] << 8) | data[7],
streamPriority: data[8] & 0x1f,
decoderConfig: {
objectProfileIndication: data[11],
streamType: (data[12] >>> 2) & 0x3f,
bufferSize: (data[13] << 16) | (data[14] << 8) | data[15],
maxBitrate: (data[16] << 24) | (data[17] << 16) | (data[18] << 8) | data[19],
avgBitrate: (data[20] << 24) | (data[21] << 16) | (data[22] << 8) | data[23],
decoderConfigDescriptor: {
tag: data[24],
length: data[25],
// audioObjectType: (data[26] >>> 3) & 0x1f,
// samplingFrequencyIndex: ((data[26] & 0x07) << 1) |
// ((data[27] >>> 7) & 0x01),
// channelConfiguration: (data[27] >>> 3) & 0x0f,
// FIXME
audioObjectType: (data[35] >>> 3) & 0x1f,
samplingFrequencyIndex: ((data[35] & 0x07) << (8 + (data[36] & 0x80))) >> 7,
channelConfiguration: (data[36] & 0x78) >> 3
}
}
};
},
ftyp: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength),
result = {
majorBrand: parseType(data.subarray(0, 4)),
minorVersion: view.getUint32(4),
compatibleBrands: []
},
i = 8;
while (i < data.byteLength) {
result.compatibleBrands.push(parseType(data.subarray(i, i + 4)));
i += 4;
}
return result;
},
dinf: function (data) {
return {
boxes: mp4toJSON(data)
};
},
dref: function (data) {
return {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
dataReferences: mp4toJSON(data.subarray(8))
};
},
hdlr: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength),
result = {
version: view.getUint8(0),
flags: new Uint8Array(data.subarray(1, 4)),
handlerType: parseType(data.subarray(8, 12)),
name: ''
},
i = 8;
// parse out the name field
for (i = 24; i < data.byteLength; i++) {
if (data[i] === 0x00) {
// the name field is null-terminated
i++;
break;
}
result.name += String.fromCharCode(data[i]);
}
// decode UTF-8 to javascript's internal representation
// see http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
result.name = decodeURIComponent(decodeURIComponent(result.name));
return result;
},
// mdat: function(data) {
// return {
// byteLength: data.byteLength,
// nals: nalParse(data),
// realData: data
// };
// },
mdhd: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength),
i = 4,
language,
result = {
version: view.getUint8(0),
flags: new Uint8Array(data.subarray(1, 4)),
language: '',
creationTime: new Date(),
modificationTime: new Date(),
timescale: 0,
duration: 0
};
if (result.version === 1) {
i += 4;
result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
i += 8;
result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
i += 4;
result.timescale = view.getUint32(i);
i += 8;
result.duration = view.getUint32(i); // truncating top 4 bytes
} else {
result.creationTime = parseMp4Date(view.getUint32(i));
i += 4;
result.modificationTime = parseMp4Date(view.getUint32(i));
i += 4;
result.timescale = view.getUint32(i);
i += 4;
result.duration = view.getUint32(i);
}
i += 4;
// language is stored as an ISO-639-2/T code in an array of three 5-bit fields
// each field is the packed difference between its ASCII value and 0x60
language = view.getUint16(i);
result.language += String.fromCharCode((language >> 10) + 0x60);
result.language += String.fromCharCode(((language & 0x03c0) >> 5) + 0x60);
result.language += String.fromCharCode((language & 0x1f) + 0x60);
return result;
},
mdia: function (data) {
return {
boxes: mp4toJSON(data)
};
},
mfhd: function (data) {
return {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
sequenceNumber: (data[4] << 24) | (data[5] << 16) | (data[6] << 8) | data[7]
};
},
minf: function (data) {
return {
boxes: mp4toJSON(data)
};
},
// codingname, not a first-class box type. stsd entries share the
// same format as real boxes so the parsing infrastructure can be
// shared
mp4a: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength),
result = {
// 6 bytes reserved
dataReferenceIndex: view.getUint16(6),
// 4 + 4 bytes reserved
channelcount: view.getUint16(16),
samplesize: view.getUint16(18),
// 2 bytes pre_defined
// 2 bytes reserved
samplerate: view.getUint16(24) + view.getUint16(26) / 65536,
streamDescriptor: undefined
};
// if there are more bytes to process, assume this is an ISO/IEC
// 14496-14 MP4AudioSampleEntry and parse the ESDBox
if (data.byteLength > 28) {
result.streamDescriptor = mp4toJSON(data.subarray(28))[0];
}
return result;
},
moof: function (data) {
return {
boxes: mp4toJSON(data)
};
},
moov: function (data) {
return {
boxes: mp4toJSON(data)
};
},
mvex: function (data) {
return {
boxes: mp4toJSON(data)
};
},
mvhd: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength),
i = 4,
result = {
version: view.getUint8(0),
flags: new Uint8Array(data.subarray(1, 4)),
creationTime: new Date(),
modificationTime: new Date(),
timescale: 0,
duration: 0,
rate: 0,
volume: 0,
matrix: new Uint32Array(0),
nextTrackId: 0
};
if (result.version === 1) {
i += 4;
result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
i += 8;
result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
i += 4;
result.timescale = view.getUint32(i);
i += 8;
result.duration = view.getUint32(i); // truncating top 4 bytes
} else {
result.creationTime = parseMp4Date(view.getUint32(i));
i += 4;
result.modificationTime = parseMp4Date(view.getUint32(i));
i += 4;
result.timescale = view.getUint32(i);
i += 4;
result.duration = view.getUint32(i);
}
i += 4;
// convert fixed-point, base 16 back to a number
result.rate = view.getUint16(i) + view.getUint16(i + 2) / 16;
i += 4;
result.volume = view.getUint8(i) + view.getUint8(i + 1) / 8;
i += 2;
i += 2;
i += 2 * 4;
result.matrix = new Uint32Array(data.subarray(i, i + 9 * 4));
i += 9 * 4;
i += 6 * 4;
result.nextTrackId = view.getUint32(i);
return result;
},
pdin: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
return {
version: view.getUint8(0),
flags: new Uint8Array(data.subarray(1, 4)),
rate: view.getUint32(4),
initialDelay: view.getUint32(8)
};
},
sdtp: function (data) {
let result = {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
samples: []
},
i;
for (i = 4; i < data.byteLength; i++) {
result.samples.push({
dependsOn: (data[i] & 0x30) >> 4,
isDependedOn: (data[i] & 0x0c) >> 2,
hasRedundancy: data[i] & 0x03
});
}
return result;
},
sidx: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength),
result = {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
references: [],
referenceId: view.getUint32(4),
timescale: view.getUint32(8),
earliestPresentationTime: view.getUint32(12),
firstOffset: view.getUint32(16)
},
referenceCount = view.getUint16(22),
i;
for (i = 24; referenceCount; i += 12, referenceCount--) {
result.references.push({
referenceType: (data[i] & 0x80) >>> 7,
referencedSize: view.getUint32(i) & 0x7fffffff,
subsegmentDuration: view.getUint32(i + 4),
startsWithSap: !!(data[i + 8] & 0x80),
sapType: (data[i + 8] & 0x70) >>> 4,
sapDeltaTime: view.getUint32(i + 8) & 0x0fffffff
});
}
return result;
},
stbl: function (data) {
return {
boxes: mp4toJSON(data)
};
},
stco: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
let entryCount = view.getUint32(4);
let result = {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
entryCount: entryCount,
chunkOffsets: []
};
for (let i = 8; entryCount; i += 4, entryCount--) {
result.chunkOffsets.push(view.getUint32(i));
}
return result;
},
stsc: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength),
entryCount = view.getUint32(4),
result = {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
sampleToChunks: []
},
i;
for (i = 8; entryCount; i += 12, entryCount--) {
result.sampleToChunks.push({
firstChunk: view.getUint32(i),
samplesPerChunk: view.getUint32(i + 4),
sampleDescriptionIndex: view.getUint32(i + 8)
});
}
return result;
},
stsd: function (data) {
return {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
boxes: mp4toJSON(data.subarray(8))
};
},
stsz: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength),
result = {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
sampleSize: view.getUint32(4),
entries: []
},
i;
for (i = 12; i < data.byteLength; i += 4) {
result.entries.push(view.getUint32(i));
}
return result;
},
stts: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength),
result = {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
timeToSamples: []
},
entryCount = view.getUint32(4),
i;
for (i = 8; entryCount; i += 8, entryCount--) {
result.timeToSamples.push({
sampleCount: view.getUint32(i),
sampleDelta: view.getUint32(i + 4)
});
}
return result;
},
styp: function (data) {
return parse.ftyp(data);
},
tfdt: function (data) {
return {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
baseMediaDecodeTime: (data[4] << 24) | (data[5] << 16) | (data[6] << 8) | data[7]
};
},
tfhd: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength),
result: {
version: number;
flags: Uint8Array;
trackId: number;
baseDataOffset?: number;
sampleDescriptionIndex?: number;
defaultSampleDuration?: number;
defaultSampleSize?: number;
defaultSampleFlags?: number;
} = {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
trackId: view.getUint32(4)
},
baseDataOffsetPresent = result.flags[2] & 0x01,
sampleDescriptionIndexPresent = result.flags[2] & 0x02,
defaultSampleDurationPresent = result.flags[2] & 0x08,
defaultSampleSizePresent = result.flags[2] & 0x10,
defaultSampleFlagsPresent = result.flags[2] & 0x20,
i;
i = 8;
if (baseDataOffsetPresent) {
i += 4; // truncate top 4 bytes
result.baseDataOffset = view.getUint32(12);
i += 4;
}
if (sampleDescriptionIndexPresent) {
result.sampleDescriptionIndex = view.getUint32(i);
i += 4;
}
if (defaultSampleDurationPresent) {
result.defaultSampleDuration = view.getUint32(i);
i += 4;
}
if (defaultSampleSizePresent) {
result.defaultSampleSize = view.getUint32(i);
i += 4;
}
if (defaultSampleFlagsPresent) {
result.defaultSampleFlags = view.getUint32(i);
}
return result;
},
tkhd: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength),
i = 4,
result = {
version: view.getUint8(0),
flags: new Uint8Array(data.subarray(1, 4)),
creationTime: new Date(),
modificationTime: new Date(),
trackId: 0,
duration: 0,
layer: 0,
alternateGroup: 0,
volume: 0,
width: 0,
height: 0,
matrix: new Uint32Array(0)
};
if (result.version === 1) {
i += 4;
result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
i += 8;
result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
i += 4;
result.trackId = view.getUint32(i);
i += 4;
i += 8;
result.duration = view.getUint32(i); // truncating top 4 bytes
} else {
result.creationTime = parseMp4Date(view.getUint32(i));
i += 4;
result.modificationTime = parseMp4Date(view.getUint32(i));
i += 4;
result.trackId = view.getUint32(i);
i += 4;
i += 4;
result.duration = view.getUint32(i);
}
i += 4;
i += 2 * 4;
result.layer = view.getUint16(i);
i += 2;
result.alternateGroup = view.getUint16(i);
i += 2;
// convert fixed-point, base 16 back to a number
result.volume = view.getUint8(i) + view.getUint8(i + 1) / 8;
i += 2;
i += 2;
result.matrix = new Uint32Array(data.subarray(i, i + 9 * 4));
i += 9 * 4;
result.width = view.getUint16(i) + view.getUint16(i + 2) / 16;
i += 4;
result.height = view.getUint16(i) + view.getUint16(i + 2) / 16;
return result;
},
traf: function (data) {
return {
boxes: mp4toJSON(data)
};
},
trak: function (data) {
return {
boxes: mp4toJSON(data)
};
},
trex: function (data) {
let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
return {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
trackId: view.getUint32(4),
defaultSampleDescriptionIndex: view.getUint32(8),
defaultSampleDuration: view.getUint32(12),
defaultSampleSize: view.getUint32(16),
sampleDependsOn: data[20] & 0x03,
sampleIsDependedOn: (data[21] & 0xc0) >> 6,
sampleHasRedundancy: (data[21] & 0x30) >> 4,
samplePaddingValue: (data[21] & 0x0e) >> 1,
sampleIsDifferenceSample: !!(data[21] & 0x01),
sampleDegradationPriority: view.getUint16(22)
};
},
trun: function (data) {
let result: {
version: number;
flags: Uint8Array;
samples: Array<any>;
dataOffset?: number;
} = {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4)),
samples: []
},
view = new DataView(data.buffer, data.byteOffset, data.byteLength),
dataOffsetPresent = result.flags[2] & 0x01,
firstSampleFlagsPresent = result.flags[2] & 0x04,
sampleDurationPresent = result.flags[1] & 0x01,
sampleSizePresent = result.flags[1] & 0x02,
sampleFlagsPresent = result.flags[1] & 0x04,
sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
sampleCount = view.getUint32(4),
offset = 8,
sample;
if (dataOffsetPresent) {
result.dataOffset = view.getUint32(offset);
offset += 4;
}
if (firstSampleFlagsPresent && sampleCount) {
sample = {
flags: parseSampleFlags(data.subarray(offset, offset + 4))
};
offset += 4;
if (sampleDurationPresent) {
sample.duration = view.getUint32(offset);
offset += 4;
}
if (sampleSizePresent) {
sample.size = view.getUint32(offset);
offset += 4;
}
if (sampleCompositionTimeOffsetPresent) {
sample.compositionTimeOffset = view.getUint32(offset);
offset += 4;
}
result.samples.push(sample);
sampleCount--;
}
while (sampleCount--) {
sample = {};
if (sampleDurationPresent) {
sample.duration = view.getUint32(offset);
offset += 4;
}
if (sampleSizePresent) {
sample.size = view.getUint32(offset);
offset += 4;
}
if (sampleFlagsPresent) {
sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
offset += 4;
}
if (sampleCompositionTimeOffsetPresent) {
sample.compositionTimeOffset = view.getUint32(offset);
offset += 4;
}
result.samples.push(sample);
}
return result;
},
'url ': function (data) {
return {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4))
};
},
vmhd: function (data) {
//let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
return {
version: data[0],
flags: new Uint8Array(data.subarray(1, 4))
//graphicsmode: view.getUint16(4),
//opcolor: new Uint16Array([view.getUint16(6),
// view.getUint16(8),
// view.getUint16(10)])
};
}
};
/**
* Return a javascript array of box objects parsed from an ISO base media file.
* @param data - the binary data of the media to be inspected
* @return a javascript array of potentially nested box objects
*/
let mp4toJSON = function (data: Uint8Array): Array<any> {
let i = 0,
result = [],
view = new DataView(data.buffer, data.byteOffset, data.byteLength),
size,
type,
end,
box;
while (i < data.byteLength) {
// parse box data
(size = view.getUint32(i)), (type = parseType(data.subarray(i + 4, i + 8)));
end = size > 1 ? i + size : data.byteLength;
// parse type-specific data
box = (
parse[type] ||
function (data) {
return {
data: data
};
}
)(data.subarray(i + 8, end));
box.size = size;
box.type = type;
// store this box and move to the next
result.push(box);
i = end;
}
return result;
};
export const MP4Inspect = {
mp4toJSON: mp4toJSON
}; | the_stack |
import {
Component,
ElementRef,
IterableDiffers,
KeyValueDiffers,
ChangeDetectorRef,
SimpleChanges,
Input,
Renderer2,
OnInit,
OnChanges,
DoCheck
} from '@angular/core';
import { IgControlBase } from '../igcontrolbase/igcontrolbase';
@Component({
selector: 'ig-tree',
template: '<ng-content></ng-content>',
inputs: [
'widgetId',
'options',
'changeDetectionInterval',
'disabled',
'create',
'width',
'height',
'checkboxMode',
'singleBranchExpand',
'hotTracking',
'parentNodeImageUrl',
'parentNodeImageClass',
'parentNodeImageTooltip',
'leafNodeImageUrl',
'leafNodeImageClass',
'leafNodeImageTooltip',
'animationDuration',
'pathSeparator',
'dataSource',
'dataSourceUrl',
'dataSourceType',
'responseDataKey',
'responseDataType',
'requestType',
'responseContentType',
'initialExpandDepth',
'loadOnDemand',
'bindings',
'defaultNodeTarget',
'dragAndDrop',
'updateUrl',
'dragAndDropSettings'
],
outputs: ['dataBinding', 'dataBound', 'rendering', 'rendered', 'selectionChanging', 'selectionChanged', 'nodeCheckstateChanging', 'nodeCheckstateChanged', 'nodePopulating', 'nodePopulated', 'nodeCollapsing', 'nodeCollapsed', 'nodeExpanding', 'nodeExpanded', 'nodeClick', 'nodeDoubleClick', 'dragStart', 'drag', 'dragStop', 'nodeDropping', 'nodeDropped']
})
export class IgTreeComponent extends IgControlBase<IgTree> implements OnInit, OnChanges, DoCheck {
private _dataSource: any;
private _changes: any;
@Input()
public set dataSource(value: any) {
this._dataSource = value;
}
@Input()
public bindings: IgTreeBindings;
constructor(el: ElementRef, renderer: Renderer2, differs: IterableDiffers, kvalDiffers: KeyValueDiffers, cdr: ChangeDetectorRef) {
super(el, renderer, differs, kvalDiffers, cdr);
}
ngOnInit() {
if (!this.options.dataSource && this._dataSource) {
this.options.dataSource = this._dataSource;
}
super.ngOnInit();
}
public ngOnChanges(changes: SimpleChanges): void {
const ds = 'dataSource';
// const options = "options";
if (ds in changes) {
const value = changes[ds].currentValue;
if (!this._differ && value) {
try {
this._differ = this._differs.find(value).create();
this._changes = [];
this._dataSource.forEach(item => {
this._changes.push(this.kvalDiffers.find({}).create());
});
} catch (e) {
throw new Error('Only binding to arrays is supported.');
}
}
}
super.ngOnChanges(changes);
}
ngDoCheck() {
if (this._differ) {
const changes = this._differ.diff(this._dataSource);
// check if control is initialized
const elem = jQuery(this._el).data(this._widgetName);
if (changes && elem) {
this.dataSourceApplyChanges(changes);
}
if (this._changes && elem) {
// check recs
for (let i = 0; i < this._dataSource.length; i++) {
const item = this._dataSource[i];
const rowChanges = this._changes[i].diff(item);
if (rowChanges) {
rowChanges.forEachChangedItem((change: any) => {
this.updateItem(item, change.currentValue, change.key);
});
}
}
}
}
super.ngDoCheck();
}
addItem(item, index) {
this.dataBind();
this._changes.push(this.kvalDiffers.find({}).create());
}
deleteItem(item, index) {
this.dataBind();
this._changes.splice(index, 1);
}
dataSourceApplyChanges(changes) {
changes.forEachAddedItem(r => this.addItem(r.item, r.currentIndex));
changes.forEachRemovedItem(r => { this.deleteItem(r.item, r.previousIndex); });
}
updateItem(item, value, key) {
this.dataBind();
}
public markForCheck() {
super.markForCheck();
const bindings = this.bindings || this.options.bindings;
if (bindings && bindings.childDataProperty) {
this.dataBind();
}
}
/**
* Performs databinding on the igTree.
*/
/* istanbul ignore next */
public dataBind(): void { return; }
/**
* Toggles the checkstate of a node if checkboxMode is not set to off, otherwise does nothing.
*
* @param node Specifies the node element the checkbox of which would be toggled.
* @param event Indicates the browser event which triggered this action, if this is not an API call.
*/
/* istanbul ignore next */
public toggleCheckstate(node: object, event?: object): void { return; }
/**
* Toggles the collapse/expand state for the specified node.
*
* @param node Specifies the node element the checkbox of which would be toggled.
* @param event Indicates the browser event which triggered this action, if this is not an API call.
*/
/* istanbul ignore next */
public toggle(node: object, event?: object): void { return; }
/**
* Expands the tree down to the specified node and selects the node if specified.
*
* @param node Specifies the node element down to which the tree would be expanded.
* @param toSelect Specifies the whether to select the node after expanding to it.
*/
/* istanbul ignore next */
public expandToNode(node: object, toSelect?: boolean): void { return; }
/**
* Expands the specified node.
*
* @param node Specifies the node element to expand.
*/
/* istanbul ignore next */
public expand(node: object): void { return; }
/**
* Collapses the specified node.
*
* @param node Specifies the node element to collapse.
*/
/* istanbul ignore next */
public collapse(node: object): void { return; }
/**
* Retrieves the parent node element of the specified node element.
*
* @param node Specifies the jQuery selected node element to collapse.
*/
/* istanbul ignore next */
public parentNode(node: object): object { return; }
/**
* Retrieves the jQuery element of the node with the specified path.
*
* @param nodePath Specifies the path to the required node.
*/
/* istanbul ignore next */
public nodeByPath(nodePath: string): object { return; }
/**
* Retrieves the jQuery element of the node with the specified value.
*
* @param value Specifies the value of the required node.
*/
/* istanbul ignore next */
public nodesByValue(value: string): object { return; }
/**
* Retrieves all the node objects for the nodes that have their checkboxes checked.
*/
/* istanbul ignore next */
public checkedNodes(): any[] { return; }
/**
* Retrieves all the node objects for the nodes that have their checkboxes unchecked.
*/
/* istanbul ignore next */
public uncheckedNodes(): any[] { return; }
/**
* Retrieves all the node objects for the nodes that have their checkboxes partially checked.
*/
/* istanbul ignore next */
public partiallyCheckedNodes(): any[] { return; }
/**
* Selects a node.
*
* @param node Specifies the node element to be selected.
* @param event Indicates the browser event which triggered this action, if this is not an API call.
*/
/* istanbul ignore next */
public select(node: object, event?: object): void { return; }
/**
* Deselects the specified node.
*
* @param node Specifies the node element to be deselected.
*/
/* istanbul ignore next */
public deselect(node: object): void { return; }
/**
* Deselects all the selected nodes.
*/
/* istanbul ignore next */
public clearSelection(): void { return; }
/**
* Retrieves the node object for the selected node.
*/
/* istanbul ignore next */
public selectedNode(): object { return; }
/**
* Retrieves all node objects with the specified text (case sensitive).
*
* @param text The text to search for.
* @param parent The node element to start the search from. If not specified then search would start from the root of the tree.
*/
/* istanbul ignore next */
public findNodesByText(text: string, parent?: object): any[] { return; }
/**
* Retrieves all node objects for the immediate children of the specified parent with the specified text (case sensitive).
*
* @param text The text to search for.
* @param parent The node element the children of which would be searched.
*/
/* istanbul ignore next */
public findImmediateNodesByText(text: string, parent?: object): any[] { return; }
/**
* Retrieves the n-th jQuery node element child of the specified parent.
*
* @param index Specifies the index the node at which to be retrieved.
* @param parent The parent node element to start the search from.
*/
/* istanbul ignore next */
public nodeByIndex(index: number, parent?: object): object { return; }
/**
* Retrieves a node object for the specified node element.
*
* @param element Specifies the node element.
*/
/* istanbul ignore next */
public nodeFromElement(element: object): object { return; }
/**
* Retrieves a node object collection of the immediate children of the provided node element.
*
* @param parent Specifies the node element.
*/
/* istanbul ignore next */
public children(parent: object): any[] { return; }
/**
* Retrieves a node object collection of the immediate children of the node with the provided path.
*
* @param path Specifies the path of the node the children of which are to be retrieved.
*/
/* istanbul ignore next */
public childrenByPath(path: string): any[] { return; }
/**
* Returns true if the provided node element is selected and false otherwise.
*
* @param node Specifies the node element.
*/
/* istanbul ignore next */
public isSelected(node: object): boolean { return; }
/**
* Returns true if the provided node element is expanded and false otherwise.
*
* @param node Specifies the node element.
*/
/* istanbul ignore next */
public isExpanded(node: object): boolean { return; }
/**
* Returns true if the provided node element has its checkbox checkstate checked and false otherwise.
*
* @param node Specifies the node element.
*/
/* istanbul ignore next */
public isChecked(node: object): boolean { return; }
/**
* Returns the specified node checkstate.
*
* @param node Specifies the node element.
*/
/* istanbul ignore next */
public checkState(node: object): string { return; }
/**
* Adds a new array of nodes to the tree. New nodes are appended to the root or to a specified parent node, at a specified index.
*
* @param node Specifies the data used to create the new nodeс.
* @param parent Specifies the element of the parent node the nodes are to be appended to.
* @param nodeIndex Specifies the index at which the nodes to be inserted.
*/
/* istanbul ignore next */
public addNode(node: object, parent?: object, nodeIndex?: number): void { return; }
/**
* Removes the node with with the specified path and all of its children.
*
* @param path Specifies the path of the node to be removed.
*/
/* istanbul ignore next */
public removeAt(path: string): void { return; }
/**
* Removing all the nodes with the specified value.
*
* @param value Specifies the value of the nodes to be removed.
*/
/* istanbul ignore next */
public removeNodesByValue(value: string): void { return; }
/**
* Performs a UI update on the provided node element with the provided data.
*
* @param element Specifies the node to be updated.
* @param data Specifies the new data item the node would update according to.
*/
/* istanbul ignore next */
public applyChangesToNode(element: object, data: object): void { return; }
/**
* Returns the transaction log stack.
*/
/* istanbul ignore next */
public transactionLog(): any[] { return; }
/**
* Returns the data for the node with specified path.
*
* @param path Specifies the node path for which the data is returned.
*/
/* istanbul ignore next */
public nodeDataFor(path: string): object { return; }
/**
* Destructor for the igTree widget.
*/
/* istanbul ignore next */
public destroy(): void { return; }
} | the_stack |
import { auxiliaries } from 'webgl-operate';
const log = auxiliaries.log;
const logLevel = auxiliaries.LogLevel;
import {
Camera,
Canvas,
Color,
ColorScale,
Context,
DefaultFramebuffer,
FontFace,
Invalidate,
Label,
LabelRenderPass,
Position2DLabel,
Renderer,
Text,
Wizard,
} from 'webgl-operate';
import { Example } from './example';
/* spellchecker: enable */
// tslint:disable:max-classes-per-file
class ColorLerpRenderer extends Renderer {
protected _extensions = false;
protected _labelPass: LabelRenderPass;
protected _labelGenerated1: Position2DLabel;
protected _labelGenerated2: Position2DLabel;
protected _labelGenerated3: Position2DLabel;
protected _labelGenerated4: Position2DLabel;
protected _labelLinear1: Position2DLabel;
protected _labelLinear2: Position2DLabel;
protected _labelLinear3: Position2DLabel;
protected _labelLinear4: Position2DLabel;
protected _labelLinear5: Position2DLabel;
protected _labelLinear6: Position2DLabel;
protected _labelLinear7: Position2DLabel;
protected _labelLinear8: Position2DLabel;
protected _labelNearest1: Position2DLabel;
protected _labelNearest2: Position2DLabel;
protected _labelNearest3: Position2DLabel;
protected _labelNearest4: Position2DLabel;
protected _labelNearest5: Position2DLabel;
protected _labelNearest6: Position2DLabel;
protected _labelNearest7: Position2DLabel;
protected _labelNearest8: Position2DLabel;
protected _labelLAB: Position2DLabel;
protected _camera: Camera;
protected _defaultFBO: DefaultFramebuffer;
protected _fontFace: FontFace | undefined;
/**
* Initializes and sets up rendering passes, navigation, loads a font face and links shaders with program.
* @param context - valid context to create the object for.
* @param identifier - meaningful name for identification of this instance.
* @param mouseEventProvider - required for mouse interaction
* @returns - whether initialization was successful
*/
protected onInitialize(context: Context, callback: Invalidate,
/* mouseEventProvider: MouseEventProvider, */
/* keyEventProvider: KeyEventProvider, */
/* touchEventProvider: TouchEventProvider */): boolean {
/* Create framebuffers, textures, and render buffers. */
this._defaultFBO = new DefaultFramebuffer(this._context, 'DefaultFBO');
this._defaultFBO.initialize();
/* Create and configure test navigation. */
this._camera = new Camera();
/* Create and configure label pass. */
this._labelPass = new LabelRenderPass(context);
this._labelPass.initialize();
this._labelPass.camera = this._camera;
this._labelPass.target = this._defaultFBO;
this._labelPass.depthMask = false;
FontFace.fromFile('./data/opensans2048p160d16.fnt', context)
.then((fontFace) => {
for (const label of this._labelPass.labels) {
label.fontFace = fontFace;
}
this._fontFace = fontFace;
this.updateLabels();
this.finishLoading();
this.invalidate();
})
.catch((reason) => log(logLevel.Error, reason));
this.setupScene();
return true;
}
/**
* Uninitializes Buffers, Textures, and Program.
*/
protected onUninitialize(): void {
super.uninitialize();
this._defaultFBO.uninitialize();
this._labelPass.uninitialize();
}
/**
* This is invoked in order to check if rendering of a frame is required by means of implementation specific
* evaluation (e.g., lazy non continuous rendering). Regardless of the return value a new frame (preparation,
* frame, swap) might be invoked anyway, e.g., when update is forced or canvas or context properties have
* changed or the renderer was invalidated @see{@link invalidate}.
* @returns whether to redraw
*/
protected onUpdate(): boolean {
for (const label of this._labelPass.labels) {
if (label.altered || label.color.altered) {
return true;
}
}
return this._altered.any || this._camera.altered;
}
/**
* This is invoked in order to prepare rendering of one or more frames, regarding multi-frame rendering and
* camera-updates.
*/
protected onPrepare(): void {
if (this._altered.canvasSize) {
this._camera.aspect = this._canvasSize[0] / this._canvasSize[1];
this._camera.viewport = this._canvasSize;
this.updateLabels();
}
// This would render the clear color to be black?
// if (this._altered.clearColor) {
// this._defaultFBO.clearColor(this._clearColor);
// }
this._labelPass.update();
this._altered.reset();
this._camera.altered = false;
}
protected onDiscarded(): void {
this._altered.alter('canvasSize');
this._altered.alter('clearColor');
this._altered.alter('frameSize');
this._altered.alter('multiFrameNumber');
}
/**
* After (1) update and (2) preparation are invoked, a frame is invoked. Renders both 2D and 3D labels.
* @param frameNumber - for intermediate frames in accumulation rendering
*/
protected onFrame(frameNumber: number): void {
const gl = this._context.gl;
gl.viewport(0, 0, this._camera.viewport[0], this._camera.viewport[1]);
this._defaultFBO.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT, true, false);
this._labelPass.frame();
}
/**
* Sets up an example scene with 2D and 3D labels and sets the corresponding data on LabelGeometries. The
* FontFace is set on each label by the LabelRenderPass.
*/
protected setupScene(): void {
// test interpolation
this._labelLAB = new Position2DLabel(new Text(`| should be violet-ish |`), Label.Type.Static);
// generated color
this._labelGenerated1 = new Position2DLabel(new Text(`| generated 0 |`), Label.Type.Dynamic);
this._labelGenerated2 = new Position2DLabel(new Text(`| generated 1 |`), Label.Type.Dynamic);
this._labelGenerated3 = new Position2DLabel(new Text(`| generated 2 |`), Label.Type.Dynamic);
this._labelGenerated4 = new Position2DLabel(new Text(`| generated 3 |`), Label.Type.Dynamic);
// color scale linear
this._labelLinear1 = new Position2DLabel(new Text(`| linear 0 |`), Label.Type.Dynamic);
this._labelLinear2 = new Position2DLabel(new Text(`| linear 1 |`), Label.Type.Dynamic);
this._labelLinear3 = new Position2DLabel(new Text(`| linear 2 |`), Label.Type.Dynamic);
this._labelLinear4 = new Position2DLabel(new Text(`| linear 3 |`), Label.Type.Dynamic);
this._labelLinear5 = new Position2DLabel(new Text(`| linear 4 |`), Label.Type.Dynamic);
this._labelLinear6 = new Position2DLabel(new Text(`| linear 5 |`), Label.Type.Dynamic);
this._labelLinear7 = new Position2DLabel(new Text(`| linear 6 |`), Label.Type.Dynamic);
this._labelLinear8 = new Position2DLabel(new Text(`| linear 7 |`), Label.Type.Dynamic);
// color scale nearest
this._labelNearest1 = new Position2DLabel(new Text(`| nearest 0 |`), Label.Type.Dynamic);
this._labelNearest2 = new Position2DLabel(new Text(`| nearest 1 |`), Label.Type.Dynamic);
this._labelNearest3 = new Position2DLabel(new Text(`| nearest 2 |`), Label.Type.Dynamic);
this._labelNearest4 = new Position2DLabel(new Text(`| nearest 3 |`), Label.Type.Dynamic);
this._labelNearest5 = new Position2DLabel(new Text(`| nearest 4 |`), Label.Type.Dynamic);
this._labelNearest6 = new Position2DLabel(new Text(`| nearest 5 |`), Label.Type.Dynamic);
this._labelNearest7 = new Position2DLabel(new Text(`| nearest 6 |`), Label.Type.Dynamic);
this._labelNearest8 = new Position2DLabel(new Text(`| nearest 7 |`), Label.Type.Dynamic);
const generatedLabels = [
this._labelGenerated1, this._labelGenerated2, this._labelGenerated3, this._labelGenerated4];
const linearLabels = [
this._labelLinear1, this._labelLinear2, this._labelLinear3, this._labelLinear4, this._labelLinear5,
this._labelLinear6, this._labelLinear7, this._labelLinear8];
const nearestLabels = [
this._labelNearest1, this._labelNearest2, this._labelNearest3, this._labelNearest4, this._labelNearest5,
this._labelNearest6, this._labelNearest7, this._labelNearest8];
this._labelPass.labels = [this._labelLAB, ...generatedLabels, ...linearLabels, ...nearestLabels];
for (const label of this._labelPass.labels) {
label.fontSize = 17;
label.fontSizeUnit = Label.Unit.Pixel;
}
// const colors = [
// 255, 255, 255, 255,
// 254, 213, 0, 255,
// 254, 134, 0, 255,
// 230, 36, 38, 255,
// ];
const colors = [
255, 0, 0, 255,
0, 0, 255, 255,
];
// const colors = [
// 255, 255, 255, 255,
// 0, 0, 0, 255,
// ];
const stepCount = 4.0; // colors.length / 4.0;
const colorScale = ColorScale.fromArray(colors, ColorScale.ArrayType.RGBA, stepCount, [0, 1.0]);
for (const color of colorScale.colors) {
log(logLevel.Info, `generated color: ${color.rgba}`);
}
this._labelLAB.color = colorScale.lerp(0.5, Color.Space.LAB)!;
let i = 0;
for (const label of generatedLabels) {
i %= stepCount;
label.color.fromRGB(...colorScale.colors[i].rgba);
i++;
}
i = 0;
let l = nearestLabels.length;
colorScale.hint = ColorScale.InterpolationHint.Nearest;
for (const label of nearestLabels) {
const r = colorScale.lerp(i / l, Color.Space.LAB)!;
log(logLevel.Info, `lerp (nearest): ${i} ${i / l} ${r.rgba}`);
label.color = r;
i++;
}
i = 0;
l = linearLabels.length;
colorScale.hint = ColorScale.InterpolationHint.Linear;
for (const label of linearLabels) {
const r = colorScale.lerp(i / l, Color.Space.LAB)!;
log(logLevel.Info, `lerp (linear): ${i} ${i / l} ${r.rgba}`);
label.color = r;
i++;
}
}
protected updateLabels(): void {
this.updateLabelsGenerated();
this.updateLabelsLinear();
this.updateLabelsNearest();
}
protected updateLabelsGenerated(): void {
if (!this._labelGenerated1.valid) {
return;
}
const step = this._canvasSize[1] / 3.5;
const top = 1.5 * step;
const width = this._canvasSize[0] - 32.0 /* margin */ * Label.devicePixelRatio();
this._labelGenerated1.position = [-width * 0.5, top - 0.0 * step];
this._labelGenerated2.position = [-width * 0.5, top - 1.0 * step];
this._labelGenerated3.position = [-width * 0.5, top - 2.0 * step];
this._labelGenerated4.position = [-width * 0.5, top - 3.0 * step];
}
protected updateLabelsLinear(): void {
if (!this._labelLinear1.valid) {
return;
}
const step = this._canvasSize[1] / 8.0;
const top = 3.5 * step;
const width = this._canvasSize[0] - 32.0 /* margin */ * Label.devicePixelRatio();
this._labelLinear1.position = [-width * 0.1, top - 0.0 * step];
this._labelLinear2.position = [-width * 0.1, top - 1.0 * step];
this._labelLinear3.position = [-width * 0.1, top - 2.0 * step];
this._labelLinear4.position = [-width * 0.1, top - 3.0 * step];
this._labelLinear5.position = [-width * 0.1, top - 4.0 * step];
this._labelLinear6.position = [-width * 0.1, top - 5.0 * step];
this._labelLinear7.position = [-width * 0.1, top - 6.0 * step];
this._labelLinear8.position = [-width * 0.1, top - 7.0 * step];
}
protected updateLabelsNearest(): void {
if (!this._labelNearest1.valid) {
return;
}
const step = this._canvasSize[1] / 8.0;
const top = 3.5 * step;
const width = this._canvasSize[0] - 32.0 /* margin */ * Label.devicePixelRatio();
this._labelNearest1.position = [-width * 0.3, top - 0.0 * step];
this._labelNearest2.position = [-width * 0.3, top - 1.0 * step];
this._labelNearest3.position = [-width * 0.3, top - 2.0 * step];
this._labelNearest4.position = [-width * 0.3, top - 3.0 * step];
this._labelNearest5.position = [-width * 0.3, top - 4.0 * step];
this._labelNearest6.position = [-width * 0.3, top - 5.0 * step];
this._labelNearest7.position = [-width * 0.3, top - 6.0 * step];
this._labelNearest8.position = [-width * 0.3, top - 7.0 * step];
}
}
export class ColorLerpExample extends Example {
private _canvas: Canvas;
private _renderer: ColorLerpRenderer;
onInitialize(element: HTMLCanvasElement | string): boolean {
this._canvas = new Canvas(element, { antialias: false });
this._canvas.controller.multiFrameNumber = 1;
this._canvas.framePrecision = Wizard.Precision.byte;
this._canvas.frameScale = [1.0, 1.0];
this._canvas.clearColor = new Color();
this._renderer = new ColorLerpRenderer();
this._canvas.renderer = this._renderer;
return true;
}
onUninitialize(): void {
this._canvas.dispose();
(this._renderer as Renderer).uninitialize();
}
get canvas(): Canvas {
return this._canvas;
}
get renderer(): ColorLerpRenderer {
return this._renderer;
}
} | the_stack |
import { randomBytes } from 'crypto';
import test from 'ava';
import * as elliptic from 'elliptic';
import * as fc from 'fast-check';
import * as secp256k1Node from 'secp256k1';
import {
getEmbeddedSecp256k1Binary,
instantiateSecp256k1,
instantiateSecp256k1Bytes,
Secp256k1,
} from '../lib';
// test vectors (from `zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong`, m/0 and m/1):
// prettier-ignore
const keyTweakVal = new Uint8Array([0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]);
// prettier-ignore
const messageHash = new Uint8Array([0xda, 0xde, 0x12, 0xe0, 0x6a, 0x5b, 0xbf, 0x5e, 0x11, 0x16, 0xf9, 0xbc, 0x44, 0x99, 0x8b, 0x87, 0x68, 0x13, 0xe9, 0x48, 0xe1, 0x07, 0x07, 0xdc, 0xb4, 0x80, 0x08, 0xa1, 0xda, 0xf3, 0x51, 0x2d]);
// prettier-ignore
const privkey = new Uint8Array([0xf8, 0x5d, 0x4b, 0xd8, 0xa0, 0x3c, 0xa1, 0x06, 0xc9, 0xde, 0xb4, 0x7b, 0x79, 0x18, 0x03, 0xda, 0xc7, 0xf0, 0x33, 0x38, 0x09, 0xe3, 0xf1, 0xdd, 0x04, 0xd1, 0x82, 0xe0, 0xab, 0xa6, 0xe5, 0x53]);
// prettier-ignore
const secp256k1OrderN = new Uint8Array([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41]);
// prettier-ignore
const pubkeyUncompressed = new Uint8Array([0x04, 0x76, 0xea, 0x9e, 0x36, 0xa7, 0x5d, 0x2e, 0xcf, 0x9c, 0x93, 0xa0, 0xbe, 0x76, 0x88, 0x5e, 0x36, 0xf8, 0x22, 0x52, 0x9d, 0xb2, 0x2a, 0xcf, 0xdc, 0x76, 0x1c, 0x9b, 0x5b, 0x45, 0x44, 0xf5, 0xc5, 0x6d, 0xd5, 0x3b, 0x07, 0xc7, 0xa9, 0x83, 0xbb, 0x2d, 0xdd, 0x71, 0x55, 0x1f, 0x06, 0x33, 0x19, 0x4a, 0x2f, 0xe3, 0x30, 0xf9, 0x0a, 0xaf, 0x67, 0x5d, 0xde, 0x25, 0xb1, 0x37, 0xef, 0xd2, 0x85]);
// prettier-ignore
const pubkeyCompressed = new Uint8Array([0x03, 0x76, 0xea, 0x9e, 0x36, 0xa7, 0x5d, 0x2e, 0xcf, 0x9c, 0x93, 0xa0, 0xbe, 0x76, 0x88, 0x5e, 0x36, 0xf8, 0x22, 0x52, 0x9d, 0xb2, 0x2a, 0xcf, 0xdc, 0x76, 0x1c, 0x9b, 0x5b, 0x45, 0x44, 0xf5, 0xc5]);
// prettier-ignore
const invalidPubkeyCompressed = new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
// prettier-ignore
const privkeyTweakedAdd = new Uint8Array([0xf9, 0x5e, 0x4c, 0xd9, 0xa1, 0x3d, 0xa2, 0x07, 0xca, 0xdf, 0xb5, 0x7c, 0x7a, 0x19, 0x04, 0xdb, 0xc8, 0xf1, 0x34, 0x39, 0x0a, 0xe4, 0xf2, 0xde, 0x05, 0xd2, 0x83, 0xe1, 0xac, 0xa7, 0xe6, 0x54]);
// prettier-ignore
const pubkeyTweakedAddUncompressed = new Uint8Array([0x04, 0x6f, 0x1d, 0xf3, 0x4a, 0x81, 0xdf, 0x8c, 0xec, 0x18, 0x33, 0x34, 0xce, 0xb2, 0x56, 0x49, 0x9e, 0xc6, 0xe7, 0x57, 0x04, 0x57, 0x57, 0x6a, 0x92, 0x37, 0x1b, 0x74, 0x75, 0xc3, 0x4f, 0x2c, 0x19, 0xa8, 0xed, 0xd5, 0xc4, 0x29, 0x44, 0x80, 0xc1, 0xb0, 0xb3, 0x3c, 0xc8, 0xa4, 0xfd, 0x0a, 0x5c, 0x53, 0xc3, 0xd8, 0x9b, 0xd7, 0x93, 0xa7, 0x1f, 0x78, 0x03, 0x5c, 0x74, 0x00, 0xab, 0x34, 0xfc]);
// prettier-ignore
const pubkeyTweakedAddCompressed = new Uint8Array([0x02, 0x6f, 0x1d, 0xf3, 0x4a, 0x81, 0xdf, 0x8c, 0xec, 0x18, 0x33, 0x34, 0xce, 0xb2, 0x56, 0x49, 0x9e, 0xc6, 0xe7, 0x57, 0x04, 0x57, 0x57, 0x6a, 0x92, 0x37, 0x1b, 0x74, 0x75, 0xc3, 0x4f, 0x2c, 0x19]);
// prettier-ignore
const privkeyTweakedMul = new Uint8Array([0x29, 0x9f, 0x6a, 0x4d, 0xe3, 0xa0, 0xfd, 0x06, 0x8c, 0x80, 0x31, 0xef, 0xd6, 0xcf, 0x3a, 0xc6, 0xb8, 0x89, 0x02, 0x5e, 0x65, 0xd2, 0xe6, 0x2d, 0x8e, 0xb9, 0xd6, 0x88, 0x2a, 0xc2, 0x1a, 0x4a]);
// prettier-ignore
const pubkeyTweakedMulUncompressed = new Uint8Array([0x04, 0xb7, 0x98, 0x58, 0x0c, 0x33, 0x8c, 0x02, 0xed, 0xc3, 0x8a, 0xd9, 0xb6, 0x19, 0x7d, 0x4c, 0x56, 0x64, 0xe6, 0xaa, 0x85, 0x49, 0x10, 0xad, 0xa7, 0x5d, 0xc6, 0x10, 0x14, 0x2b, 0x5a, 0x7a, 0x38, 0xb5, 0x0f, 0xb1, 0x55, 0x6c, 0x03, 0x3d, 0x7f, 0xb2, 0x24, 0x21, 0x69, 0x01, 0xc2, 0x86, 0x05, 0x26, 0xad, 0xeb, 0x74, 0xa8, 0x50, 0xf2, 0x9a, 0x50, 0x8f, 0x7a, 0xb3, 0x0b, 0x66, 0x20, 0x74]);
// prettier-ignore
const pubkeyTweakedMulCompressed = new Uint8Array([0x02, 0xb7, 0x98, 0x58, 0x0c, 0x33, 0x8c, 0x02, 0xed, 0xc3, 0x8a, 0xd9, 0xb6, 0x19, 0x7d, 0x4c, 0x56, 0x64, 0xe6, 0xaa, 0x85, 0x49, 0x10, 0xad, 0xa7, 0x5d, 0xc6, 0x10, 0x14, 0x2b, 0x5a, 0x7a, 0x38]);
// prettier-ignore
const sigDER = new Uint8Array([0x30, 0x45, 0x02, 0x21, 0x00, 0xab, 0x4c, 0x6d, 0x9b, 0xa5, 0x1d, 0xa8, 0x30, 0x72, 0x61, 0x5c, 0x33, 0xa9, 0x88, 0x7b, 0x75, 0x64, 0x78, 0xe6, 0xf9, 0xde, 0x38, 0x10, 0x85, 0xf5, 0x18, 0x3c, 0x97, 0x60, 0x3f, 0xc6, 0xff, 0x02, 0x20, 0x29, 0x72, 0x21, 0x88, 0xbd, 0x93, 0x7f, 0x54, 0xc8, 0x61, 0x58, 0x2c, 0xa6, 0xfc, 0x68, 0x5b, 0x8d, 0xa2, 0xb4, 0x0d, 0x05, 0xf0, 0x6b, 0x36, 0x83, 0x74, 0xd3, 0x5e, 0x4a, 0xf2, 0xb7, 0x64]);
// prettier-ignore
const sigDERHighS = new Uint8Array([0x30, 0x46, 0x02, 0x21, 0x00, 0xab, 0x4c, 0x6d, 0x9b, 0xa5, 0x1d, 0xa8, 0x30, 0x72, 0x61, 0x5c, 0x33, 0xa9, 0x88, 0x7b, 0x75, 0x64, 0x78, 0xe6, 0xf9, 0xde, 0x38, 0x10, 0x85, 0xf5, 0x18, 0x3c, 0x97, 0x60, 0x3f, 0xc6, 0xff, 0x02, 0x21, 0x00, 0xd6, 0x8d, 0xde, 0x77, 0x42, 0x6c, 0x80, 0xab, 0x37, 0x9e, 0xa7, 0xd3, 0x59, 0x03, 0x97, 0xa3, 0x2d, 0x0c, 0x28, 0xd9, 0xa9, 0x58, 0x35, 0x05, 0x3c, 0x5d, 0x8b, 0x2e, 0x85, 0x43, 0x89, 0xdd]);
// prettier-ignore
const sigCompact = new Uint8Array([0xab, 0x4c, 0x6d, 0x9b, 0xa5, 0x1d, 0xa8, 0x30, 0x72, 0x61, 0x5c, 0x33, 0xa9, 0x88, 0x7b, 0x75, 0x64, 0x78, 0xe6, 0xf9, 0xde, 0x38, 0x10, 0x85, 0xf5, 0x18, 0x3c, 0x97, 0x60, 0x3f, 0xc6, 0xff, 0x29, 0x72, 0x21, 0x88, 0xbd, 0x93, 0x7f, 0x54, 0xc8, 0x61, 0x58, 0x2c, 0xa6, 0xfc, 0x68, 0x5b, 0x8d, 0xa2, 0xb4, 0x0d, 0x05, 0xf0, 0x6b, 0x36, 0x83, 0x74, 0xd3, 0x5e, 0x4a, 0xf2, 0xb7, 0x64]);
// prettier-ignore
const sigCompactHighS = new Uint8Array([0xab, 0x4c, 0x6d, 0x9b, 0xa5, 0x1d, 0xa8, 0x30, 0x72, 0x61, 0x5c, 0x33, 0xa9, 0x88, 0x7b, 0x75, 0x64, 0x78, 0xe6, 0xf9, 0xde, 0x38, 0x10, 0x85, 0xf5, 0x18, 0x3c, 0x97, 0x60, 0x3f, 0xc6, 0xff, 0xd6, 0x8d, 0xde, 0x77, 0x42, 0x6c, 0x80, 0xab, 0x37, 0x9e, 0xa7, 0xd3, 0x59, 0x03, 0x97, 0xa3, 0x2d, 0x0c, 0x28, 0xd9, 0xa9, 0x58, 0x35, 0x05, 0x3c, 0x5d, 0x8b, 0x2e, 0x85, 0x43, 0x89, 0xdd]);
// prettier-ignore
const schnorrMsgHash = new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
// prettier-ignore
const sigSchnorr = new Uint8Array([0xb5, 0x10, 0x41, 0x58, 0x7d, 0xa9, 0x46, 0xeb, 0x67, 0x9c, 0xb3, 0x93, 0x6e, 0x1d, 0xbe, 0x5b, 0xf1, 0xd0, 0xd8, 0xac, 0xff, 0x37, 0x8d, 0xc9, 0xc6, 0xc2, 0x0a, 0x32, 0x9f, 0xb0, 0x1b, 0x79, 0xad, 0x65, 0x54, 0x65, 0xf2, 0x26, 0xa0, 0x28, 0x7b, 0x2d, 0xcf, 0x0e, 0x74, 0x6b, 0xc4, 0x55, 0xa9, 0x40, 0xfe, 0x01, 0xbc, 0xd8, 0x0f, 0xa9, 0xb6, 0x63, 0x3e, 0xcb, 0xe0, 0xc7, 0x04, 0x33]);
const sigRecovery = 1;
// libauth setup
const secp256k1Promise = instantiateSecp256k1();
const binary = getEmbeddedSecp256k1Binary();
// elliptic setup & helpers
const ec = new elliptic.ec('secp256k1'); // eslint-disable-line new-cap
const setupElliptic = (privateKey: Uint8Array) => {
const key = ec.keyFromPrivate(privateKey);
const pubUncompressed = new Uint8Array(
key.getPublic().encode('array', false)
);
const pubCompressed = new Uint8Array(key.getPublic().encodeCompressed());
return {
key,
pubCompressed,
pubUncompressed,
};
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const ellipticSignMessageDER = (key: any, message: Uint8Array) =>
new Uint8Array(key.sign(message).toDER());
const ellipticCheckSignature = (
sig: Uint8Array,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
key: any,
message: Uint8Array
): boolean => key.verify(message, sig);
// fast-check helpers
const fcUint8Array = (minLength: number, maxLength: number) =>
fc
.array(fc.integer(0, 255), minLength, maxLength)
.map((a) => Uint8Array.from(a));
const fcUint8Array32 = () => fcUint8Array(32, 32);
const fcValidPrivateKey = (secp256k1: Secp256k1) =>
fcUint8Array32().filter((generated) =>
secp256k1.validatePrivateKey(generated)
);
test('[crypto] instantiateSecp256k1 with binary', async (t) => {
const secp256k1 = await instantiateSecp256k1Bytes(binary);
t.true(
secp256k1.verifySignatureDERLowS(sigDER, pubkeyCompressed, messageHash)
);
});
test('[crypto] instantiateSecp256k1 with randomization', async (t) => {
const secp256k1 = await instantiateSecp256k1(randomBytes(32));
t.true(
secp256k1.verifySignatureDERLowS(sigDER, pubkeyUncompressed, messageHash)
);
});
test('[crypto] secp256k1.addTweakPrivateKey', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.addTweakPrivateKey(privkey, keyTweakVal),
privkeyTweakedAdd
);
t.throws(() => secp256k1.addTweakPrivateKey(privkey, Buffer.alloc(32, 255)));
});
test('[fast-check] [crypto] secp256k1.addTweakPrivateKey', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
t.deepEqual(
secp256k1.addTweakPrivateKey(privateKey, keyTweakVal),
new Uint8Array(
secp256k1Node.privateKeyTweakAdd(privateKey, keyTweakVal)
)
);
}
);
t.notThrows(() => fc.assert(equivalentToSecp256k1Node));
/*
* the elliptic library doesn't implement public or private key tweaking.
* perhaps future tests can do the math in JavaScript and compare with that.
*/
});
test('[crypto] secp256k1.addTweakPublicKeyCompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.addTweakPublicKeyCompressed(pubkeyCompressed, keyTweakVal),
pubkeyTweakedAddCompressed
);
t.throws(() => {
secp256k1.addTweakPublicKeyCompressed(new Uint8Array(65), keyTweakVal);
});
t.throws(() => {
secp256k1.addTweakPublicKeyCompressed(
pubkeyCompressed,
Buffer.alloc(32, 255)
);
});
});
test('[fast-check] [crypto] secp256k1.addTweakPublicKeyCompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
const pubkeyC = secp256k1.derivePublicKeyCompressed(privateKey);
t.deepEqual(
secp256k1.addTweakPublicKeyCompressed(pubkeyC, keyTweakVal),
new Uint8Array(
secp256k1Node.publicKeyTweakAdd(pubkeyC, keyTweakVal, true)
)
);
}
);
t.notThrows(() => fc.assert(equivalentToSecp256k1Node));
/*
* the elliptic library doesn't implement public or private key tweaking.
* perhaps future tests can do the math in JavaScript and compare with that.
*/
});
test('[crypto] secp256k1.addTweakPublicKeyUncompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.addTweakPublicKeyUncompressed(pubkeyUncompressed, keyTweakVal),
pubkeyTweakedAddUncompressed
);
t.throws(() => {
secp256k1.addTweakPublicKeyUncompressed(new Uint8Array(65), keyTweakVal);
});
t.throws(() => {
secp256k1.addTweakPublicKeyUncompressed(
pubkeyCompressed,
Buffer.alloc(32, 255)
);
});
});
test('[fast-check] [crypto] secp256k1.addTweakPublicKeyUncompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
const pubkeyU = secp256k1.derivePublicKeyUncompressed(privateKey);
t.deepEqual(
secp256k1.addTweakPublicKeyUncompressed(pubkeyU, keyTweakVal),
new Uint8Array(
secp256k1Node.publicKeyTweakAdd(pubkeyU, keyTweakVal, false)
)
);
}
);
t.notThrows(() => fc.assert(equivalentToSecp256k1Node));
/*
* the elliptic library doesn't implement public or private key tweaking.
* perhaps future tests can do the math in JavaScript and compare with that.
*/
});
test('[crypto] secp256k1.compressPublicKey', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.compressPublicKey(pubkeyUncompressed),
pubkeyCompressed
);
t.throws(() => secp256k1.compressPublicKey(new Uint8Array(65)));
});
test('[fast-check] [crypto] secp256k1.compressPublicKey', async (t) => {
const secp256k1 = await secp256k1Promise;
const reversesUncompress = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
const pubkeyC = secp256k1.derivePublicKeyCompressed(privateKey);
t.deepEqual(
pubkeyC,
secp256k1.compressPublicKey(secp256k1.uncompressPublicKey(pubkeyC))
);
}
);
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
const pubkeyU = secp256k1.derivePublicKeyUncompressed(privateKey);
t.deepEqual(
secp256k1.compressPublicKey(pubkeyU),
new Uint8Array(secp256k1Node.publicKeyConvert(pubkeyU, true))
);
}
);
const equivalentToElliptic = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
const pubkeyU = secp256k1.derivePublicKeyUncompressed(privateKey);
t.deepEqual(
secp256k1.compressPublicKey(pubkeyU),
new Uint8Array(ec.keyFromPublic(pubkeyU).getPublic().encodeCompressed())
);
}
);
t.notThrows(() => {
fc.assert(reversesUncompress);
fc.assert(equivalentToSecp256k1Node);
fc.assert(equivalentToElliptic);
});
});
test('[crypto] secp256k1.derivePublicKeyCompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(secp256k1.derivePublicKeyCompressed(privkey), pubkeyCompressed);
t.throws(() => secp256k1.derivePublicKeyCompressed(secp256k1OrderN));
});
test('[fast-check] [crypto] secp256k1.derivePublicKeyCompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
const isEquivalentToDeriveUncompressedThenCompress = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
const pubkeyU = secp256k1.derivePublicKeyUncompressed(privateKey);
const pubkeyC = secp256k1.derivePublicKeyCompressed(privateKey);
t.deepEqual(pubkeyC, secp256k1.compressPublicKey(pubkeyU));
}
);
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
t.deepEqual(
secp256k1.derivePublicKeyCompressed(privateKey),
new Uint8Array(secp256k1Node.publicKeyCreate(privateKey, true))
);
}
);
const equivalentToElliptic = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
t.deepEqual(
secp256k1.derivePublicKeyCompressed(privateKey),
setupElliptic(privateKey).pubCompressed
);
}
);
t.notThrows(() => {
fc.assert(isEquivalentToDeriveUncompressedThenCompress);
fc.assert(equivalentToSecp256k1Node);
fc.assert(equivalentToElliptic);
});
});
test('[crypto] secp256k1.derivePublicKeyUncompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.derivePublicKeyUncompressed(privkey),
pubkeyUncompressed
);
t.throws(() => secp256k1.derivePublicKeyUncompressed(secp256k1OrderN));
});
test('[fast-check] [crypto] secp256k1.derivePublicKeyUncompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
const isEquivalentToDeriveCompressedThenUncompress = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
const pubkeyC = secp256k1.derivePublicKeyCompressed(privateKey);
const pubkeyU = secp256k1.derivePublicKeyUncompressed(privateKey);
t.deepEqual(pubkeyU, secp256k1.uncompressPublicKey(pubkeyC));
}
);
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
t.deepEqual(
secp256k1.derivePublicKeyUncompressed(privateKey),
new Uint8Array(secp256k1Node.publicKeyCreate(privateKey, false))
);
}
);
const equivalentToElliptic = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
t.deepEqual(
secp256k1.derivePublicKeyUncompressed(privateKey),
setupElliptic(privateKey).pubUncompressed
);
}
);
t.notThrows(() => {
fc.assert(isEquivalentToDeriveCompressedThenUncompress);
fc.assert(equivalentToSecp256k1Node);
fc.assert(equivalentToElliptic);
});
});
test('[crypto] secp256k1.malleateSignatureDER', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(secp256k1.malleateSignatureDER(sigDER), sigDERHighS);
});
test('[fast-check] [crypto] secp256k1.malleateSignatureDER', async (t) => {
const secp256k1 = await secp256k1Promise;
const malleationIsJustNegation = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, message) => {
const { key } = setupElliptic(privateKey);
const pubkey = secp256k1.derivePublicKeyCompressed(privateKey);
const sig = secp256k1.signMessageHashDER(privateKey, message);
t.true(secp256k1.verifySignatureDERLowS(sig, pubkey, message));
t.true(ellipticCheckSignature(sig, key, message));
const malleated = secp256k1.malleateSignatureDER(sig);
t.true(secp256k1.verifySignatureDER(malleated, pubkey, message));
t.true(ellipticCheckSignature(malleated, key, message));
t.false(secp256k1.verifySignatureDERLowS(malleated, pubkey, message));
t.deepEqual(sig, secp256k1.malleateSignatureDER(malleated));
}
);
t.notThrows(() => {
fc.assert(malleationIsJustNegation);
});
});
test('[crypto] secp256k1.malleateSignatureCompact', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(secp256k1.malleateSignatureCompact(sigCompact), sigCompactHighS);
});
test('[fast-check] [crypto] secp256k1.malleateSignatureCompact', async (t) => {
const secp256k1 = await secp256k1Promise;
const malleationIsJustNegation = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, message) => {
const pubkey = secp256k1.derivePublicKeyCompressed(privateKey);
const sig = secp256k1.signMessageHashCompact(privateKey, message);
t.true(secp256k1.verifySignatureCompactLowS(sig, pubkey, message));
t.true(secp256k1Node.ecdsaVerify(sig, message, pubkey));
const malleated = secp256k1.malleateSignatureCompact(sig);
t.true(secp256k1.verifySignatureCompact(malleated, pubkey, message));
t.false(secp256k1.verifySignatureCompactLowS(malleated, pubkey, message));
t.false(secp256k1Node.ecdsaVerify(malleated, message, pubkey));
const malleatedMalleated = secp256k1.malleateSignatureCompact(malleated);
t.true(secp256k1Node.ecdsaVerify(malleatedMalleated, message, pubkey));
t.true(
secp256k1.verifySignatureCompactLowS(
malleatedMalleated,
pubkey,
message
)
);
t.deepEqual(sig, malleatedMalleated);
}
);
t.notThrows(() => {
fc.assert(malleationIsJustNegation);
});
});
test('[crypto] secp256k1.mulTweakPrivateKey', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.mulTweakPrivateKey(privkey, keyTweakVal),
privkeyTweakedMul
);
t.throws(() => secp256k1.mulTweakPrivateKey(privkey, Buffer.alloc(32, 255)));
});
test('[fast-check] [crypto] secp256k1.mulTweakPrivateKey', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
t.deepEqual(
secp256k1.mulTweakPrivateKey(privateKey, keyTweakVal),
new Uint8Array(
secp256k1Node.privateKeyTweakMul(privateKey, keyTweakVal)
)
);
}
);
t.notThrows(() => fc.assert(equivalentToSecp256k1Node));
/*
* the elliptic library doesn't implement public or private key tweaking.
* perhaps future tests can do the math in JavaScript and compare with that.
*/
});
test('[crypto] secp256k1.mulTweakPublicKeyCompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.mulTweakPublicKeyCompressed(pubkeyCompressed, keyTweakVal),
pubkeyTweakedMulCompressed
);
t.throws(() => {
secp256k1.mulTweakPublicKeyCompressed(new Uint8Array(65), keyTweakVal);
});
t.throws(() => {
secp256k1.mulTweakPublicKeyCompressed(
pubkeyCompressed,
Buffer.alloc(32, 255)
);
});
});
test('[fast-check] [crypto] secp256k1.mulTweakPublicKeyCompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
const pubkeyC = secp256k1.derivePublicKeyCompressed(privateKey);
t.deepEqual(
secp256k1.mulTweakPublicKeyCompressed(pubkeyC, keyTweakVal),
new Uint8Array(
secp256k1Node.publicKeyTweakMul(pubkeyC, keyTweakVal, true)
)
);
}
);
t.notThrows(() => fc.assert(equivalentToSecp256k1Node));
/*
* the elliptic library doesn't implement public or private key tweaking.
* perhaps future tests can do the math in JavaScript and compare with that.
*/
});
test('[crypto] secp256k1.mulTweakPublicKeyUncompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.mulTweakPublicKeyUncompressed(pubkeyUncompressed, keyTweakVal),
pubkeyTweakedMulUncompressed
);
t.throws(() => {
secp256k1.mulTweakPublicKeyUncompressed(new Uint8Array(65), keyTweakVal);
});
t.throws(() => {
secp256k1.mulTweakPublicKeyUncompressed(
pubkeyCompressed,
Buffer.alloc(32, 255)
);
});
});
test('[fast-check] [crypto] secp256k1.mulTweakPublicKeyUncompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
const pubkeyU = secp256k1.derivePublicKeyUncompressed(privateKey);
t.deepEqual(
secp256k1.mulTweakPublicKeyUncompressed(pubkeyU, keyTweakVal),
new Uint8Array(
secp256k1Node.publicKeyTweakMul(pubkeyU, keyTweakVal, false)
)
);
}
);
t.notThrows(() => fc.assert(equivalentToSecp256k1Node));
/*
* the elliptic library doesn't implement public or private key tweaking.
* perhaps future tests can do the math in JavaScript and compare with that.
*/
});
test('[crypto] secp256k1.normalizeSignatureCompact', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(secp256k1.normalizeSignatureCompact(sigCompactHighS), sigCompact);
});
test('[fast-check] [crypto] secp256k1.normalizeSignatureCompact', async (t) => {
const secp256k1 = await secp256k1Promise;
const malleateThenNormalizeEqualsInitial = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
const sig = secp256k1.signMessageHashCompact(privateKey, hash);
t.deepEqual(
sig,
secp256k1.normalizeSignatureCompact(
secp256k1.malleateSignatureCompact(sig)
)
);
}
);
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
const sig = secp256k1.signMessageHashCompact(privateKey, hash);
const malleated = secp256k1.malleateSignatureCompact(sig);
t.deepEqual(
secp256k1.normalizeSignatureCompact(malleated),
new Uint8Array(secp256k1Node.signatureNormalize(malleated))
);
}
);
t.notThrows(() => {
fc.assert(malleateThenNormalizeEqualsInitial);
fc.assert(equivalentToSecp256k1Node);
});
});
test('[crypto] secp256k1.normalizeSignatureDER', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(secp256k1.normalizeSignatureDER(sigDERHighS), sigDER);
});
test('[fast-check] [crypto] secp256k1.normalizeSignatureDER', async (t) => {
const secp256k1 = await secp256k1Promise;
const malleateThenNormalizeEqualsInitial = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
const sig = secp256k1.signMessageHashDER(privateKey, hash);
t.deepEqual(
sig,
secp256k1.normalizeSignatureDER(secp256k1.malleateSignatureDER(sig))
);
}
);
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
const sig = secp256k1.signMessageHashDER(privateKey, hash);
const malleated = secp256k1.malleateSignatureDER(sig);
t.deepEqual(
secp256k1.normalizeSignatureDER(malleated),
new Uint8Array(
secp256k1Node.signatureExport(
secp256k1Node.signatureNormalize(
secp256k1Node.signatureImport(malleated)
)
)
)
);
}
);
t.notThrows(() => {
fc.assert(malleateThenNormalizeEqualsInitial);
fc.assert(equivalentToSecp256k1Node);
});
});
test('[crypto] secp256k1.recoverPublicKeyCompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.recoverPublicKeyCompressed(sigCompact, sigRecovery, messageHash),
pubkeyCompressed
);
t.throws(() =>
secp256k1.recoverPublicKeyCompressed(
new Uint8Array(64).fill(255),
sigRecovery,
messageHash
)
);
const failRecover = 2;
t.throws(() =>
secp256k1.recoverPublicKeyCompressed(sigCompact, failRecover, messageHash)
);
});
test('[fast-check] [crypto] secp256k1.recoverPublicKeyCompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
const recoverableStuff = secp256k1.signMessageHashRecoverableCompact(
privateKey,
hash
);
t.deepEqual(
secp256k1.recoverPublicKeyCompressed(
recoverableStuff.signature,
recoverableStuff.recoveryId,
hash
),
new Uint8Array(
secp256k1Node.ecdsaRecover(
recoverableStuff.signature,
recoverableStuff.recoveryId,
hash,
true
)
)
);
}
);
t.notThrows(() => fc.assert(equivalentToSecp256k1Node));
});
test('[crypto] secp256k1.recoverPublicKeyUncompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.recoverPublicKeyUncompressed(
sigCompact,
sigRecovery,
messageHash
),
pubkeyUncompressed
);
});
test('[fast-check] [crypto] secp256k1.recoverPublicKeyUncompressed', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
const recoverableStuff = secp256k1.signMessageHashRecoverableCompact(
privateKey,
hash
);
t.deepEqual(
secp256k1.recoverPublicKeyUncompressed(
recoverableStuff.signature,
recoverableStuff.recoveryId,
hash
),
new Uint8Array(
secp256k1Node.ecdsaRecover(
recoverableStuff.signature,
recoverableStuff.recoveryId,
hash,
false
)
)
);
}
);
t.notThrows(() => fc.assert(equivalentToSecp256k1Node));
});
test('[crypto] secp256k1.signMessageHashCompact', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.signMessageHashCompact(privkey, messageHash),
sigCompact
);
t.notDeepEqual(
secp256k1.signMessageHashCompact(privkey, Uint8Array.of()),
sigCompact
);
t.throws(() =>
secp256k1.signMessageHashCompact(secp256k1OrderN, messageHash)
);
});
test('[fast-check] [crypto] secp256k1.signMessageHashCompact', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
t.deepEqual(
secp256k1.signMessageHashCompact(privateKey, hash),
new Uint8Array(secp256k1Node.ecdsaSign(hash, privateKey).signature)
);
}
);
const equivalentToElliptic = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
const { key } = setupElliptic(privateKey);
t.deepEqual(
secp256k1.signMessageHashCompact(privateKey, hash),
secp256k1.signatureDERToCompact(
secp256k1.normalizeSignatureDER(ellipticSignMessageDER(key, hash))
)
);
}
);
t.notThrows(() => {
fc.assert(equivalentToSecp256k1Node);
fc.assert(equivalentToElliptic);
});
});
test('[crypto] secp256k1.signMessageHashDER', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(secp256k1.signMessageHashDER(privkey, messageHash), sigDER);
t.notDeepEqual(
secp256k1.signMessageHashDER(privkey, Uint8Array.of()),
sigDER
);
t.throws(() => secp256k1.signMessageHashDER(secp256k1OrderN, messageHash));
});
test('[fast-check] [crypto] secp256k1.signMessageHashDER', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
t.deepEqual(
secp256k1.signMessageHashDER(privateKey, hash),
new Uint8Array(
secp256k1Node.signatureExport(
secp256k1Node.ecdsaSign(hash, privateKey).signature
)
)
);
}
);
const equivalentToElliptic = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
const { key } = setupElliptic(privateKey);
t.deepEqual(
secp256k1.signMessageHashDER(privateKey, hash),
secp256k1.normalizeSignatureDER(ellipticSignMessageDER(key, hash))
);
}
);
t.notThrows(() => {
fc.assert(equivalentToSecp256k1Node);
fc.assert(equivalentToElliptic);
});
});
test('[crypto] secp256k1.signMessageHashRecoverableCompact', async (t) => {
const secp256k1 = await secp256k1Promise;
const recoverableStuff = secp256k1.signMessageHashRecoverableCompact(
privkey,
messageHash
);
t.is(recoverableStuff.recoveryId, sigRecovery);
t.deepEqual(recoverableStuff.signature, sigCompact);
t.throws(() =>
secp256k1.signMessageHashRecoverableCompact(secp256k1OrderN, messageHash)
);
});
test('[fast-check] [crypto] secp256k1.signMessageHashRecoverableCompact', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
const nodeRecoverableStuff = secp256k1Node.ecdsaSign(hash, privateKey);
t.deepEqual(
secp256k1.signMessageHashRecoverableCompact(privateKey, hash),
{
recoveryId: nodeRecoverableStuff.recid,
signature: new Uint8Array(nodeRecoverableStuff.signature),
}
);
}
);
t.notThrows(() => fc.assert(equivalentToSecp256k1Node));
});
test('[crypto] secp256k1.signatureCompactToDER', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(secp256k1.signatureCompactToDER(sigCompact), sigDER);
});
test('[fast-check] [crypto] secp256k1.signatureCompactToDER', async (t) => {
const secp256k1 = await secp256k1Promise;
const reversesCompress = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
const pubkeyU = secp256k1.derivePublicKeyUncompressed(privateKey);
t.deepEqual(
pubkeyU,
secp256k1.uncompressPublicKey(secp256k1.compressPublicKey(pubkeyU))
);
}
);
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
const sig = secp256k1.signMessageHashCompact(privateKey, hash);
t.deepEqual(
new Uint8Array(secp256k1Node.signatureExport(sig)),
secp256k1.signatureCompactToDER(sig)
);
}
);
t.notThrows(() => {
fc.assert(reversesCompress);
fc.assert(equivalentToSecp256k1Node);
});
});
test('[crypto] secp256k1.signatureDERToCompact', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(secp256k1.signatureDERToCompact(sigDER), sigCompact);
const sigDERWithBrokenEncoding = sigDER.slice().fill(0, 0, 1);
t.throws(() => {
secp256k1.signatureDERToCompact(sigDERWithBrokenEncoding);
});
});
test('[fast-check] [crypto] secp256k1.signatureDERToCompact', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
(privateKey, hash) => {
const sig = secp256k1.signMessageHashDER(privateKey, hash);
t.deepEqual(
new Uint8Array(secp256k1Node.signatureImport(sig)),
secp256k1.signatureDERToCompact(sig)
);
}
);
t.notThrows(() => {
fc.assert(equivalentToSecp256k1Node);
});
});
test('[crypto] secp256k1.uncompressPublicKey', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.uncompressPublicKey(pubkeyCompressed),
pubkeyUncompressed
);
t.throws(() => secp256k1.uncompressPublicKey(new Uint8Array(33)));
});
test('[fast-check] [crypto] secp256k1.uncompressPublicKey', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
(privateKey) => {
const pubkeyC = secp256k1.derivePublicKeyCompressed(privateKey);
t.deepEqual(
new Uint8Array(secp256k1Node.publicKeyConvert(pubkeyC, false)),
secp256k1.uncompressPublicKey(pubkeyC)
);
}
);
t.notThrows(() => {
fc.assert(equivalentToSecp256k1Node);
});
});
test('[crypto] secp256k1.validatePrivateKey', async (t) => {
const secp256k1 = await secp256k1Promise;
t.true(secp256k1.validatePrivateKey(privkey));
t.false(secp256k1.validatePrivateKey(secp256k1OrderN));
});
test('[fast-check] [crypto] secp256k1.validatePrivateKey', async (t) => {
const secp256k1 = await secp256k1Promise;
// eslint-disable-next-line functional/immutable-data
const almostInvalid = Array(15).fill(255);
// invalid >= 0xFFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFE BAAE DCE6 AF48 A03B BFD2 5E8C D036 4140
const theRest = 32 - almostInvalid.length;
const equivalentToSecp256k1Node = fc.property(
fc
.array(fc.integer(0, 255), theRest, theRest)
.map((random) => Uint8Array.from([...almostInvalid, ...random])),
(privateKey) =>
secp256k1.validatePrivateKey(privateKey) ===
secp256k1Node.privateKeyVerify(privateKey)
);
t.notThrows(() => {
fc.assert(equivalentToSecp256k1Node);
});
});
test('[crypto] secp256k1.validatePublicKey', async (t) => {
const secp256k1 = await secp256k1Promise;
t.true(secp256k1.validatePublicKey(pubkeyUncompressed));
t.true(secp256k1.validatePublicKey(pubkeyCompressed));
t.false(secp256k1.validatePublicKey(invalidPubkeyCompressed));
});
test.todo('[fast-check] [crypto] secp256k1.validatePublicKey');
test('[crypto] secp256k1.verifySignatureCompact', async (t) => {
const secp256k1 = await secp256k1Promise;
t.true(
secp256k1.verifySignatureCompact(
sigCompactHighS,
pubkeyCompressed,
messageHash
)
);
t.false(
secp256k1.verifySignatureCompact(
sigCompactHighS,
pubkeyCompressed,
Uint8Array.of()
)
);
t.true(
secp256k1.verifySignatureCompact(
sigCompactHighS,
pubkeyCompressed,
messageHash
)
);
t.false(
secp256k1.verifySignatureCompact(
Uint8Array.of(),
pubkeyCompressed,
messageHash
)
);
});
test('[fast-check] [crypto] secp256k1.verifySignatureCompact', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
fc.boolean(),
fc.boolean(),
(privateKey, message, compressed, invalidate) => {
const pubUncompressed = secp256k1Node.publicKeyCreate(privateKey, false);
const pubCompressed = secp256k1Node.publicKeyCreate(privateKey, true);
const sig = secp256k1Node.ecdsaSign(message, privateKey).signature;
const testSig = invalidate ? sig.fill(0, 6, 7) : sig;
const pub = compressed ? pubCompressed : pubUncompressed;
const malleated = secp256k1.malleateSignatureCompact(testSig);
return (
secp256k1Node.ecdsaVerify(testSig, message, pub) ===
secp256k1.verifySignatureCompact(malleated, pub, message)
);
}
);
const equivalentToElliptic = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
fc.boolean(),
fc.boolean(),
(privateKey, message, compressed, invalidate) => {
const { key, pubUncompressed, pubCompressed } = setupElliptic(privateKey);
const sig = ellipticSignMessageDER(key, message);
const testSig = invalidate ? sig.fill(0, 6, 20) : sig;
const pub = compressed ? pubCompressed : pubUncompressed;
const compactSig = secp256k1.signatureDERToCompact(testSig);
return (
ellipticCheckSignature(testSig, key, message) ===
secp256k1.verifySignatureCompact(compactSig, pub, message)
);
}
);
t.notThrows(() => {
fc.assert(equivalentToSecp256k1Node);
fc.assert(equivalentToElliptic);
});
});
test('[crypto] secp256k1.verifySignatureCompactLowS', async (t) => {
const secp256k1 = await secp256k1Promise;
t.true(
secp256k1.verifySignatureCompactLowS(
sigCompact,
pubkeyCompressed,
messageHash
)
);
t.false(
secp256k1.verifySignatureCompactLowS(
Uint8Array.of(),
pubkeyCompressed,
messageHash
)
);
t.true(
secp256k1.verifySignatureCompactLowS(
sigCompact,
pubkeyCompressed,
messageHash
)
);
t.false(
secp256k1.verifySignatureCompactLowS(
sigCompact,
pubkeyCompressed,
Uint8Array.of()
)
);
});
test('[fast-check] [crypto] secp256k1.verifySignatureCompactLowS', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
fc.boolean(),
fc.boolean(),
(privateKey, message, compressed, invalidate) => {
const pubUncompressed = secp256k1Node.publicKeyCreate(privateKey, false);
const pubCompressed = secp256k1Node.publicKeyCreate(privateKey, true);
const sig = secp256k1Node.ecdsaSign(message, privateKey).signature;
const testSig = invalidate ? sig.fill(0, 6, 7) : sig;
const pub = compressed ? pubCompressed : pubUncompressed;
return (
secp256k1Node.ecdsaVerify(testSig, message, pub) ===
secp256k1.verifySignatureCompactLowS(testSig, pub, message)
);
}
);
const equivalentToElliptic = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
fc.boolean(),
fc.boolean(),
(privateKey, message, compressed, invalidate) => {
const { key, pubUncompressed, pubCompressed } = setupElliptic(privateKey);
const sig = secp256k1.normalizeSignatureDER(
ellipticSignMessageDER(key, message)
);
const testSig = invalidate ? sig.fill(0, 6, 20) : sig;
const pub = compressed ? pubCompressed : pubUncompressed;
const compactSig = secp256k1.signatureDERToCompact(testSig);
return (
ellipticCheckSignature(testSig, key, message) ===
secp256k1.verifySignatureCompactLowS(compactSig, pub, message)
);
}
);
t.notThrows(() => {
fc.assert(equivalentToSecp256k1Node);
fc.assert(equivalentToElliptic);
});
});
test('[crypto] secp256k1.verifySignatureDER', async (t) => {
const secp256k1 = await secp256k1Promise;
t.true(
secp256k1.verifySignatureDER(sigDERHighS, pubkeyCompressed, messageHash)
);
t.false(
secp256k1.verifySignatureDER(Uint8Array.of(), pubkeyCompressed, messageHash)
);
t.true(
secp256k1.verifySignatureDER(sigDERHighS, pubkeyCompressed, messageHash)
);
t.false(
secp256k1.verifySignatureDER(sigDERHighS, pubkeyCompressed, Uint8Array.of())
);
});
test('[crypto] secp256k1.verifySignatureDERLowS', async (t) => {
const secp256k1 = await secp256k1Promise;
t.true(
secp256k1.verifySignatureDERLowS(sigDER, pubkeyCompressed, messageHash)
);
t.false(
secp256k1.verifySignatureDERLowS(
Uint8Array.of(),
pubkeyCompressed,
messageHash
)
);
t.true(
secp256k1.verifySignatureDERLowS(sigDER, pubkeyCompressed, messageHash)
);
t.false(
secp256k1.verifySignatureDERLowS(sigDER, pubkeyCompressed, Uint8Array.of())
);
const pubkeyWithBrokenEncoding = pubkeyCompressed.slice().fill(0, 0, 1);
t.false(
secp256k1.verifySignatureDERLowS(
sigDER,
pubkeyWithBrokenEncoding,
messageHash
)
);
const sigDERWithBrokenEncoding = sigDER.slice().fill(0, 0, 1);
t.false(
secp256k1.verifySignatureDERLowS(
sigDERWithBrokenEncoding,
pubkeyCompressed,
messageHash
)
);
const sigDERWithBadSignature = sigDER.slice().fill(0, 6, 7);
t.false(
secp256k1.verifySignatureDERLowS(
sigDERWithBadSignature,
pubkeyCompressed,
messageHash
)
);
});
test('[fast-check] [crypto] secp256k1.verifySignatureDERLowS', async (t) => {
const secp256k1 = await secp256k1Promise;
const equivalentToSecp256k1Node = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
fc.boolean(),
fc.boolean(),
(privateKey, message, compressed, invalidate) => {
const pubUncompressed = secp256k1Node.publicKeyCreate(privateKey, false);
const pubCompressed = secp256k1Node.publicKeyCreate(privateKey, true);
const original = secp256k1Node.ecdsaSign(message, privateKey).signature;
const sig = secp256k1Node.signatureExport(original);
const testSig = invalidate ? sig.fill(0, 6, 7) : sig;
const pub = compressed ? pubCompressed : pubUncompressed;
const imported = secp256k1Node.signatureImport(testSig);
return (
secp256k1Node.ecdsaVerify(imported, message, pub) ===
secp256k1.verifySignatureDERLowS(testSig, pub, message)
);
}
);
const equivalentToElliptic = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
fc.boolean(),
fc.boolean(),
(privateKey, message, compressed, invalidate) => {
const { key, pubUncompressed, pubCompressed } = setupElliptic(privateKey);
const sig = ellipticSignMessageDER(key, message);
const testSig = invalidate ? sig.fill(0, 6, 7) : sig;
const pub = compressed ? pubCompressed : pubUncompressed;
return (
ellipticCheckSignature(testSig, key, message) ===
secp256k1.verifySignatureDERLowS(
secp256k1.normalizeSignatureDER(testSig),
pub,
message
)
);
}
);
t.notThrows(() => {
fc.assert(equivalentToSecp256k1Node);
fc.assert(equivalentToElliptic);
});
});
test('[crypto] secp256k1.signMessageHashSchnorr', async (t) => {
const secp256k1 = await secp256k1Promise;
t.deepEqual(
secp256k1.signMessageHashSchnorr(privkey, schnorrMsgHash),
sigSchnorr
);
t.throws(() =>
secp256k1.signMessageHashSchnorr(secp256k1OrderN, schnorrMsgHash)
);
});
test('[fast-check] [crypto] secp256k1.signMessageHashSchnorr', async (t) => {
const secp256k1 = await secp256k1Promise;
const createsValidSignatures = fc.property(
fcValidPrivateKey(secp256k1),
fcUint8Array32(),
fc.boolean(),
(privateKey, hash, invalidate) => {
const publicKey = secp256k1.derivePublicKeyCompressed(privateKey);
const signature = secp256k1.signMessageHashSchnorr(privateKey, hash);
t.is(
secp256k1.verifySignatureSchnorr(
invalidate ? signature : signature.fill(0),
publicKey,
hash
),
invalidate
);
}
);
t.notThrows(() => {
fc.assert(createsValidSignatures);
});
});
test('[crypto] secp256k1.verifySignatureSchnorr', async (t) => {
const secp256k1 = await secp256k1Promise;
t.true(
secp256k1.verifySignatureSchnorr(
sigSchnorr,
pubkeyCompressed,
schnorrMsgHash
)
);
t.false(
secp256k1.verifySignatureSchnorr(
Uint8Array.of(),
pubkeyCompressed,
schnorrMsgHash
)
);
const pubkeyWithBrokenEncoding = pubkeyCompressed.slice().fill(0, 0, 1);
t.false(
secp256k1.verifySignatureSchnorr(
sigSchnorr,
pubkeyWithBrokenEncoding,
schnorrMsgHash
)
);
const sigSchnorrWithBadSignature = sigSchnorr.slice().fill(0, 6, 7);
t.false(
secp256k1.verifySignatureSchnorr(
sigSchnorrWithBadSignature,
pubkeyCompressed,
schnorrMsgHash
)
);
// test vectors from Bitcoin ABC libsecp256k1
/* Test vector 1 */
// prettier-ignore
const pk1 = Uint8Array.from([0x02, 0x79, 0xbe, 0x66, 0x7e, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xce, 0x87, 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xce, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, 0x17, 0x98]);
// prettier-ignore
const msg1 = Uint8Array.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
// prettier-ignore
const sig1 = Uint8Array.from([0x78, 0x7a, 0x84, 0x8e, 0x71, 0x04, 0x3d, 0x28, 0x0c, 0x50, 0x47, 0x0e, 0x8e, 0x15, 0x32, 0xb2, 0xdd, 0x5d, 0x20, 0xee, 0x91, 0x2a, 0x45, 0xdb, 0xdd, 0x2b, 0xd1, 0xdf, 0xbf, 0x18, 0x7e, 0xf6, 0x70, 0x31, 0xa9, 0x88, 0x31, 0x85, 0x9d, 0xc3, 0x4d, 0xff, 0xee, 0xdd, 0xa8, 0x68, 0x31, 0x84, 0x2c, 0xcd, 0x00, 0x79, 0xe1, 0xf9, 0x2a, 0xf1, 0x77, 0xf7, 0xf2, 0x2c, 0xc1, 0xdc, 0xed, 0x05]);
t.is(secp256k1.verifySignatureSchnorr(sig1, pk1, msg1), true);
/* Test vector 2 */
// prettier-ignore
const pk2 = Uint8Array.from([0x02, 0xdf, 0xf1, 0xd7, 0x7f, 0x2a, 0x67, 0x1c, 0x5f, 0x36, 0x18, 0x37, 0x26, 0xdb, 0x23, 0x41, 0xbe, 0x58, 0xfe, 0xae, 0x1d, 0xa2, 0xde, 0xce, 0xd8, 0x43, 0x24, 0x0f, 0x7b, 0x50, 0x2b, 0xa6, 0x59]);
// prettier-ignore
const msg2 = Uint8Array.from([0x24, 0x3f, 0x6a, 0x88, 0x85, 0xa3, 0x08, 0xd3, 0x13, 0x19, 0x8a, 0x2e, 0x03, 0x70, 0x73, 0x44, 0xa4, 0x09, 0x38, 0x22, 0x29, 0x9f, 0x31, 0xd0, 0x08, 0x2e, 0xfa, 0x98, 0xec, 0x4e, 0x6c, 0x89]);
// prettier-ignore
const sig2 = Uint8Array.from([0x2a, 0x29, 0x8d, 0xac, 0xae, 0x57, 0x39, 0x5a, 0x15, 0xd0, 0x79, 0x5d, 0xdb, 0xfd, 0x1d, 0xcb, 0x56, 0x4d, 0xa8, 0x2b, 0x0f, 0x26, 0x9b, 0xc7, 0x0a, 0x74, 0xf8, 0x22, 0x04, 0x29, 0xba, 0x1d, 0x1e, 0x51, 0xa2, 0x2c, 0xce, 0xc3, 0x55, 0x99, 0xb8, 0xf2, 0x66, 0x91, 0x22, 0x81, 0xf8, 0x36, 0x5f, 0xfc, 0x2d, 0x03, 0x5a, 0x23, 0x04, 0x34, 0xa1, 0xa6, 0x4d, 0xc5, 0x9f, 0x70, 0x13, 0xfd]);
t.is(secp256k1.verifySignatureSchnorr(sig2, pk2, msg2), true);
/* Test vector 6: R.y is not a quadratic residue */
// prettier-ignore
const pk6 = Uint8Array.from([0x02, 0xdf, 0xf1, 0xd7, 0x7f, 0x2a, 0x67, 0x1c, 0x5f, 0x36, 0x18, 0x37, 0x26, 0xdb, 0x23, 0x41, 0xbe, 0x58, 0xfe, 0xae, 0x1d, 0xa2, 0xde, 0xce, 0xd8, 0x43, 0x24, 0x0f, 0x7b, 0x50, 0x2b, 0xa6, 0x59]);
// prettier-ignore
const msg6 = Uint8Array.from([0x24, 0x3f, 0x6a, 0x88, 0x85, 0xa3, 0x08, 0xd3, 0x13, 0x19, 0x8a, 0x2e, 0x03, 0x70, 0x73, 0x44, 0xa4, 0x09, 0x38, 0x22, 0x29, 0x9f, 0x31, 0xd0, 0x08, 0x2e, 0xfa, 0x98, 0xec, 0x4e, 0x6c, 0x89]);
// prettier-ignore
const sig6 = Uint8Array.from([0x2a, 0x29, 0x8d, 0xac, 0xae, 0x57, 0x39, 0x5a, 0x15, 0xd0, 0x79, 0x5d, 0xdb, 0xfd, 0x1d, 0xcb, 0x56, 0x4d, 0xa8, 0x2b, 0x0f, 0x26, 0x9b, 0xc7, 0x0a, 0x74, 0xf8, 0x22, 0x04, 0x29, 0xba, 0x1d, 0xfa, 0x16, 0xae, 0xe0, 0x66, 0x09, 0x28, 0x0a, 0x19, 0xb6, 0x7a, 0x24, 0xe1, 0x97, 0x7e, 0x46, 0x97, 0x71, 0x2b, 0x5f, 0xd2, 0x94, 0x39, 0x14, 0xec, 0xd5, 0xf7, 0x30, 0x90, 0x1b, 0x4a, 0xb7]);
t.is(secp256k1.verifySignatureSchnorr(sig6, pk6, msg6), false);
}); | the_stack |
import * as AWS from 'aws-sdk';
import * as AWSMock from 'aws-sdk-mock';
import * as sinon from 'sinon';
import { BackoffGenerator } from '../../lib/backoff-generator';
import { CompositeStringIndexTable } from '../../lib/dynamodb';
import { Certificate } from '../../lib/x509-certs';
import { AcmCertificateImporter } from '../acm-handlers';
import { IAcmImportCertProps } from '../types';
describe('AcmCertificateImporter', () => {
const physicalId = 'physicalId';
const certArn = 'certArn';
const oldEnv = process.env;
let consoleWarnSpy: jest.SpyInstance;
beforeAll(() => {
jest.spyOn(global.console, 'log').mockImplementation(() => {});
jest.spyOn(global.console, 'error').mockImplementation(() => {});
consoleWarnSpy = jest.spyOn(global.console, 'warn').mockImplementation(() => {});
});
afterAll(() => {
jest.restoreAllMocks();
});
beforeEach(() => {
process.env.DATABASE = 'database';
AWSMock.setSDKInstance(AWS);
});
afterEach(() => {
process.env = oldEnv;
sinon.restore();
AWSMock.restore();
});
describe('doCreate', () => {
const doCreateProps: IAcmImportCertProps = {
Tags: [],
X509CertificatePem: {
Cert: 'cert',
CertChain: 'certChain',
Key: 'key',
Passphrase: 'passphrase',
},
};
beforeEach(() => {
sinon.stub(Certificate, 'decryptKey').returns(Promise.resolve('key'));
// Mock out the API call in getSecretString
AWSMock.mock('SecretsManager', 'getSecretValue', sinon.fake.resolves({ SecretString: 'secret' }));
});
test('throws when a secret does not have SecretString', async () => {
// GIVEN
const getSecretValueFake = sinon.fake.resolves({});
AWSMock.remock('SecretsManager', 'getSecretValue', getSecretValueFake);
const importer = new TestAcmCertificateImporter({
acm: new AWS.ACM(),
dynamoDb: new AWS.DynamoDB(),
secretsManager: new AWS.SecretsManager(),
resourceTableOverride: new MockCompositeStringIndexTable(),
});
// WHEN
await expect(importer.doCreate(physicalId, doCreateProps))
// THEN
.rejects.toThrow(/Secret .* did not contain a SecretString as expected/);
expect(getSecretValueFake.calledOnce).toBe(true);
});
test('retries importing certificate', async () => {
// GIVEN
const resourceTable = new MockCompositeStringIndexTable();
const getItemStub = sinon.stub(resourceTable, 'getItem').resolves(undefined);
const putItemStub = sinon.stub(resourceTable, 'putItem').resolves(true);
const importCertificateStub = sinon.stub()
.onFirstCall().rejects('Rate exceeded')
.onSecondCall().rejects('Rate exceeded')
.onThirdCall().resolves({ CertificateArn: certArn });
AWSMock.mock('ACM', 'importCertificate', importCertificateStub);
const backoffStub = sinon.stub(BackoffGenerator.prototype, 'backoff').resolves(true);
const importer = new TestAcmCertificateImporter({
acm: new AWS.ACM(),
dynamoDb: new AWS.DynamoDB(),
secretsManager: new AWS.SecretsManager(),
resourceTableOverride: resourceTable,
});
// WHEN
await expect(importer.doCreate(physicalId, doCreateProps))
// THEN
.resolves.toEqual({ CertificateArn: certArn });
expect(getItemStub.calledOnce).toBe(true);
expect(putItemStub.calledOnce).toBe(true);
expect(importCertificateStub.calledThrice).toBe(true);
expect(backoffStub.callCount).toEqual(2);
});
test('throws after max import retries', async () => {
// GIVEN
const resourceTable = new MockCompositeStringIndexTable();
const getItemStub = sinon.stub(resourceTable, 'getItem').resolves(undefined);
const attempts = 10;
const importCertificateStub = sinon.stub();
const backoffStub = sinon.stub(BackoffGenerator.prototype, 'backoff');
for (let i = 0; i < attempts; i++) {
importCertificateStub.onCall(i).rejects('Rate exceeded');
backoffStub.onCall(i).resolves(i < attempts - 1);
}
AWSMock.mock('ACM', 'importCertificate', importCertificateStub);
const importer = new TestAcmCertificateImporter({
acm: new AWS.ACM(),
dynamoDb: new AWS.DynamoDB(),
secretsManager: new AWS.SecretsManager(),
resourceTableOverride: resourceTable,
});
// WHEN
await expect(importer.doCreate(physicalId, doCreateProps))
// THEN
.rejects.toThrow(/Failed to import certificate .* after [0-9]+ attempts\./);
expect(getItemStub.calledOnce).toBe(true);
expect(importCertificateStub.callCount).toBe(attempts);
expect(backoffStub.callCount).toEqual(attempts);
});
describe('existing', () => {
test('throws if item ARN is missing', async () => {
// GIVEN
const resourceTable = new MockCompositeStringIndexTable();
const getItemStub = sinon.stub(resourceTable, 'getItem').resolves({});
const importer = new TestAcmCertificateImporter({
acm: new AWS.ACM(),
dynamoDb: new AWS.DynamoDB(),
secretsManager: new AWS.SecretsManager(),
resourceTableOverride: resourceTable,
});
// WHEN
await expect(importer.doCreate(physicalId, doCreateProps))
// THEN
.rejects.toEqual(new Error("Database Item missing 'ARN' attribute"));
expect(getItemStub.calledOnce).toBe(true);
});
test('throws if certificate not found in ACM', async () => {
// GIVEN
const resourceTable = new MockCompositeStringIndexTable();
const getItemStub = sinon.stub(resourceTable, 'getItem').resolves({ ARN: certArn });
const getCertificateFake = sinon.fake.rejects({});
AWSMock.mock('ACM', 'getCertificate', getCertificateFake);
const importer = new TestAcmCertificateImporter({
acm: new AWS.ACM(),
dynamoDb: new AWS.DynamoDB(),
secretsManager: new AWS.SecretsManager(),
resourceTableOverride: resourceTable,
});
// WHEN
await expect(importer.doCreate(physicalId, doCreateProps))
// THEN
.rejects.toThrow(new RegExp(`Database entry ${certArn} could not be found in ACM:`));
expect(getItemStub.calledOnce).toBe(true);
expect(getCertificateFake.calledOnce).toBe(true);
});
test('imports certificate', async () => {
// GIVEN
const resourceTable = new MockCompositeStringIndexTable();
const getItemStub = sinon.stub(resourceTable, 'getItem').resolves({ ARN: certArn });
const getCertificateFake = sinon.fake.resolves({ Certificate: 'cert' });
AWSMock.mock('ACM', 'getCertificate', getCertificateFake);
const importCertificateFake = sinon.fake.resolves({});
AWSMock.mock('ACM', 'importCertificate', importCertificateFake);
const importer = new TestAcmCertificateImporter({
acm: new AWS.ACM(),
dynamoDb: new AWS.DynamoDB(),
secretsManager: new AWS.SecretsManager(),
resourceTableOverride: resourceTable,
});
// WHEN
await expect(importer.doCreate(physicalId, doCreateProps))
// THEN
.resolves.toEqual({ CertificateArn: certArn });
expect(getItemStub.calledOnce).toBe(true);
expect(getCertificateFake.calledOnce).toBe(true);
// Verify that we import the existing certificate to support replacing/updating of it (e.g. to rotate certs)
expect(importCertificateFake.calledOnce).toBe(true);
});
});
describe('new', () => {
test('throws if CertificateArn not populated', async () => {
// GIVEN
const resourceTable = new MockCompositeStringIndexTable();
const getItemStub = sinon.stub(resourceTable, 'getItem').resolves(undefined);
const importCertificateFake = sinon.fake.resolves({});
AWSMock.mock('ACM', 'importCertificate', importCertificateFake);
const importer = new TestAcmCertificateImporter({
acm: new AWS.ACM(),
dynamoDb: new AWS.DynamoDB(),
secretsManager: new AWS.SecretsManager(),
resourceTableOverride: resourceTable,
});
// WHEN
await expect(importer.doCreate(physicalId, doCreateProps))
// THEN
.rejects.toThrow(/CertificateArn was not properly populated after attempt to import .*$/);
expect(getItemStub.calledOnce).toBe(true);
expect(importCertificateFake.calledOnce).toBe(true);
});
test('imports certificate', async () => {
// GIVEN
const resourceTable = new MockCompositeStringIndexTable();
const getItemStub = sinon.stub(resourceTable, 'getItem').resolves(undefined);
const putItemStub = sinon.stub(resourceTable, 'putItem').resolves(true);
const importCertificateFake = sinon.fake.resolves({ CertificateArn: certArn });
AWSMock.mock('ACM', 'importCertificate', importCertificateFake);
const importer = new TestAcmCertificateImporter({
acm: new AWS.ACM(),
dynamoDb: new AWS.DynamoDB(),
secretsManager: new AWS.SecretsManager(),
resourceTableOverride: resourceTable,
});
// WHEN
await expect(importer.doCreate(physicalId, doCreateProps))
// THEN
.resolves.toEqual({ CertificateArn: certArn });
expect(getItemStub.calledOnce).toBe(true);
expect(putItemStub.calledOnce).toBe(true);
expect(importCertificateFake.calledOnce).toBe(true);
});
});
});
describe('doDelete', () => {
test('throws if describeCertificate is in use after max attempts', async () => {
// GIVEN
const resourceTable = new MockCompositeStringIndexTable();
const queryStub = sinon.stub(resourceTable, 'query').resolves({
key: { ARN: certArn },
});
const describeCertificateFake = sinon.fake.resolves({ Certificate: { InUseBy: ['something'] } });
AWSMock.mock('ACM', 'describeCertificate', describeCertificateFake);
// This is hardcoded in the code being tested
const maxAttempts = 10;
const backoffStub = sinon.stub(BackoffGenerator.prototype, 'backoff').resolves();
const shouldContinueStub = sinon.stub(BackoffGenerator.prototype, 'shouldContinue')
.returns(true)
.onCall(maxAttempts - 1).returns(false);
const importer = new TestAcmCertificateImporter({
acm: new AWS.ACM(),
dynamoDb: new AWS.DynamoDB(),
secretsManager: new AWS.SecretsManager(),
resourceTableOverride: resourceTable,
});
// WHEN
await expect(importer.doDelete(physicalId))
// THEN
.rejects.toEqual(new Error(`Response from describeCertificate did not contain an empty InUseBy list after ${maxAttempts} attempts.`));
expect(queryStub.calledOnce).toBe(true);
expect(describeCertificateFake.callCount).toEqual(maxAttempts);
expect(backoffStub.callCount).toEqual(maxAttempts);
expect(shouldContinueStub.callCount).toEqual(maxAttempts);
});
test('throws when deleting certificate from ACM fails', async () => {
// GIVEN
const resourceTable = new MockCompositeStringIndexTable();
const queryStub = sinon.stub(resourceTable, 'query').resolves({
key: { ARN: certArn },
});
const describeCertificateFake = sinon.fake.resolves({ Certificate: { InUseBy: [] }});
AWSMock.mock('ACM', 'describeCertificate', describeCertificateFake);
const error = new Error('error');
const deleteCertificateFake = sinon.fake.rejects(error);
AWSMock.mock('ACM', 'deleteCertificate', deleteCertificateFake);
const importer = new TestAcmCertificateImporter({
acm: new AWS.ACM(),
dynamoDb: new AWS.DynamoDB(),
secretsManager: new AWS.SecretsManager(),
resourceTableOverride: resourceTable,
});
// WHEN
await expect(importer.doDelete(physicalId))
// THEN
.rejects.toEqual(error);
expect(queryStub.calledOnce).toBe(true);
expect(describeCertificateFake.calledOnce).toBe(true);
expect(deleteCertificateFake.calledOnce).toBe(true);
});
test('warns when deleting certificate from ACM fails with AccessDeniedException', async () => {
// GIVEN
const resourceTable = new MockCompositeStringIndexTable();
const queryStub = sinon.stub(resourceTable, 'query').resolves({
key: { ARN: certArn },
});
const describeCertificateFake = sinon.fake.resolves({ Certificate: { InUseBy: [] }});
AWSMock.mock('ACM', 'describeCertificate', describeCertificateFake);
const error = new Error('AccessDeniedException');
const deleteCertificateFake = sinon.fake.rejects(error);
AWSMock.mock('ACM', 'deleteCertificate', deleteCertificateFake);
const importer = new TestAcmCertificateImporter({
acm: new AWS.ACM(),
dynamoDb: new AWS.DynamoDB(),
secretsManager: new AWS.SecretsManager(),
resourceTableOverride: resourceTable,
});
// WHEN
await expect(importer.doDelete(physicalId))
// THEN
.rejects.toEqual(error);
expect(queryStub.calledOnce).toBe(true);
expect(describeCertificateFake.calledOnce).toBe(true);
expect(deleteCertificateFake.calledOnce).toBe(true);
expect(consoleWarnSpy.mock.calls.length).toBeGreaterThanOrEqual(1);
expect(consoleWarnSpy.mock.calls.map(args => args[0]).join('\n')).toMatch(new RegExp(`Could not delete Certificate ${certArn}. Please ensure it has been deleted.`));
});
test('deletes the certificate', async () => {
// GIVEN
const resourceTable = new MockCompositeStringIndexTable();
const queryStub = sinon.stub(resourceTable, 'query').resolves({ key: { ARN: certArn } });
const deleteItemStub = sinon.stub(resourceTable, 'deleteItem').resolves(true);
const describeCertificateFake = sinon.fake.resolves({ Certificate: { InUseBy: [] }});
AWSMock.mock('ACM', 'describeCertificate', describeCertificateFake);
const deleteCertificateFake = sinon.fake.resolves({});
AWSMock.mock('ACM', 'deleteCertificate', deleteCertificateFake);
const importer = new TestAcmCertificateImporter({
acm: new AWS.ACM(),
dynamoDb: new AWS.DynamoDB(),
secretsManager: new AWS.SecretsManager(),
resourceTableOverride: resourceTable,
});
// WHEN
await expect(importer.doDelete(physicalId))
// THEN
.resolves.not.toThrow();
expect(queryStub.calledOnce).toBe(true);
expect(describeCertificateFake.calledOnce).toBe(true);
expect(deleteCertificateFake.calledOnce).toBe(true);
expect(deleteItemStub.calledOnce).toBe(true);
});
});
});
/**
* Specialization of AcmCertificateImporter that overrides methods inherited from
* DynamoBackedResource so that no API calls are made.
*
* This allows the testing code above to focus on the testing the AcmCertificateImporter
* class without having to deal with mocking out API calls from its parent class.
*/
class TestAcmCertificateImporter extends AcmCertificateImporter {
private readonly resourceTableOverride: CompositeStringIndexTable;
constructor(props: {
acm: AWS.ACM,
dynamoDb: AWS.DynamoDB,
secretsManager: AWS.SecretsManager,
resourceTableOverride?: CompositeStringIndexTable
}) {
super(props.acm, props.dynamoDb, props.secretsManager);
this.resourceTableOverride = props.resourceTableOverride ?? new MockCompositeStringIndexTable();
}
protected async databasePermissionsCheck(): Promise<void> {
// Do nothing
return;
}
protected async getResourceTable(): Promise<CompositeStringIndexTable> {
return this.resourceTableOverride;
}
}
/**
* Mock implementation of CompositeStringIndexTable that does not make API calls.
*
* This allows the test code above to instantiate a CompositeStringIndexTable object
* that can be mocked.
*/
class MockCompositeStringIndexTable extends CompositeStringIndexTable {
constructor() {
super(new AWS.DynamoDB(), '', '', '');
}
public async deleteTable(): Promise<void> {}
public async putItem(_props: {
primaryKeyValue: string,
sortKeyValue: string,
attributes?: object,
allow_overwrite?: boolean,
}): Promise<boolean> {
return true;
}
public async getItem(_props: {
primaryKeyValue: string,
sortKeyValue: string,
}): Promise<{ [key: string]: any } | undefined> {
return {};
}
public async deleteItem(_props: {
primaryKeyValue: string,
sortKeyValue: string,
}): Promise<boolean> {
return true;
}
public async query(
_primaryKeyValue: string,
_pageLimit?: number,
): Promise<{ [key: string]: { [key: string]: any }}> {
return {};
}
} | the_stack |
import { assert, expect, use, should } from 'chai';
import Chaifs = require('chai-fs');
use(Chaifs);
should();
const name = 'name';
const path = 'tmp/';
const otherPath = 'otherPath/';
const msg = 'message';
const array: any[] = [1, 2, 3, 4];
const data: ArrayBuffer = new ArrayBuffer(512);
const obj: object = { key: 'value' };
const schema = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
// basename()
expect(path).to.have.basename(name);
expect(path).to.have.basename(name, msg);
expect(path).to.not.have.basename(name);
expect(path).to.not.have.basename(name, msg);
path.should.have.basename(name);
path.should.have.basename(name, msg);
path.should.not.have.basename(name);
path.should.not.have.basename(name, msg);
assert.basename(path, name);
assert.basename(path, name, msg);
assert.notBasename(path, name);
assert.notBasename(path, name, msg);
// dirname()
expect(path).to.have.dirname(name);
expect(path).to.have.dirname(name, msg);
expect(path).to.not.have.dirname(name);
expect(path).to.not.have.dirname(name, msg);
path.should.have.dirname(name);
path.should.have.dirname(name, msg);
path.should.not.have.dirname(name);
path.should.not.have.dirname(name, msg);
assert.dirname(path, name);
assert.dirname(path, name, msg);
assert.notDirname(path, name);
assert.notDirname(path, name, msg);
// extname()
expect(path).to.have.extname(name);
expect(path).to.have.extname(name, msg);
expect(path).to.not.have.extname(name);
expect(path).to.not.have.extname(name, msg);
path.should.have.extname(name);
path.should.have.extname(name, msg);
path.should.not.have.extname(name);
path.should.not.have.extname(name, msg);
assert.extname(path, name);
assert.extname(path, name, msg);
assert.notExtname(path, name);
assert.notExtname(path, name, msg);
// path()
expect(path).to.be.a.path();
expect(path).to.be.a.path(msg);
expect(path).to.not.be.a.path();
expect(path).to.not.be.a.path(msg);
path.should.be.a.path();
path.should.be.a.path(msg);
path.should.be.a.path();
path.should.be.a.path(msg);
path.should.not.be.a.path();
path.should.not.be.a.path(msg);
assert.pathExists(path);
assert.pathExists(path, msg);
assert.notPathExists(path);
assert.notPathExists(path, msg);
// directory
expect(path).to.be.a.directory();
expect(path).to.be.a.directory(msg);
expect(path).to.not.be.a.directory();
expect(path).to.not.be.a.directory(msg);
path.should.be.a.directory();
path.should.be.a.directory(msg);
path.should.not.be.a.directory();
path.should.not.be.a.directory(msg);
assert.isDirectory(path);
assert.isDirectory(path, msg);
assert.notIsDirectory(path);
assert.notIsDirectory(path, msg);
// directory().and.empty
expect(path).to.be.a.directory().and.empty;
expect(path).to.be.a.directory(msg).and.empty;
expect(path).to.be.a.directory().and.not.empty;
expect(path).to.be.a.directory(msg).and.not.empty;
path.should.be.a.directory().and.empty;
path.should.be.a.directory(msg).and.empty;
path.should.be.a.directory().and.not.empty;
path.should.be.a.directory(msg).and.not.empty;
assert.isEmptyDirectory(path);
assert.isEmptyDirectory(path, msg);
assert.notIsEmptyDirectory(path);
assert.notIsEmptyDirectory(path, msg);
// directory().with.contents([...])
// #1
expect(path).to.be.a.directory(msg).with.contents(array);
expect(path).to.be.a.directory(msg).with.contents(array, msg);
// #2
expect(path).to.be.a.directory(msg).and.not.have.contents(array);
expect(path).to.be.a.directory(msg).and.not.have.contents(array, msg);
// #3
expect(path).to.be.a.directory(msg).with.deep.contents(array);
expect(path).to.be.a.directory(msg).with.deep.contents(array, msg);
// #4
expect(path).to.be.a.directory(msg).and.not.have.deep.contents(array);
expect(path).to.be.a.directory(msg).and.not.have.deep.contents(array, msg);
// #5
expect(path).to.be.a.directory(msg).and.include.contents(array);
expect(path).to.be.a.directory(msg).and.include.contents(array, msg);
// #6
expect(path).to.be.a.directory(msg).and.not.include.contents(array);
expect(path).to.be.a.directory(msg).and.not.include.contents(array, msg);
// #1
path.should.be.a.directory(msg).with.contents(array);
path.should.be.a.directory(msg).with.contents(array, msg);
// #2
path.should.be.a.directory(msg).and.not.have.contents(array);
path.should.be.a.directory(msg).and.not.have.contents(array, msg);
// #3
path.should.be.a.directory(msg).with.deep.contents(array);
path.should.be.a.directory(msg).with.deep.contents(array, msg);
// #4
path.should.be.a.directory(msg).and.not.have.deep.contents(array);
path.should.be.a.directory(msg).and.not.have.deep.contents(array, msg);
// #5
path.should.be.a.directory(msg).and.include.contents(array);
path.should.be.a.directory(msg).and.include.contents(array, msg);
// #6
path.should.be.a.directory(msg).and.not.include.contents(array);
path.should.be.a.directory(msg).and.not.include.contents(array, msg);
assert.directoryContent(path, array);
assert.directoryContent(path, array, msg);
assert.notDirectoryContent(path, array);
assert.notDirectoryContent(path, array, msg);
assert.directoryDeepContent(path, array);
assert.directoryDeepContent(path, array, msg);
assert.notDirectoryDeepContent(path, array);
assert.notDirectoryDeepContent(path, array, msg);
assert.directoryInclude(path, array);
assert.directoryInclude(path, array, msg);
assert.notDirectoryInclude(path, array);
assert.notDirectoryInclude(path, array, msg);
// directory().with.files([...])
// #1
expect(path).to.be.a.directory(msg).with.files(array);
expect(path).to.be.a.directory(msg).with.files(array, msg);
// #2
expect(path).to.be.a.directory(msg).with.files(array);
expect(path).to.be.a.directory(msg).with.files(array, msg);
// #3
expect(path).to.be.a.directory(msg).and.not.have.files(array);
expect(path).to.be.a.directory(msg).and.not.have.files(array, msg);
// #4
expect(path).to.be.a.directory(msg).and.not.have.files(array);
expect(path).to.be.a.directory(msg).and.not.have.files(array, msg);
// #5
expect(path).to.be.a.directory(msg).with.deep.files(array, msg);
expect(path).to.be.a.directory(msg).with.deep.files(array);
// #6
expect(path).to.be.a.directory(msg).with.deep.files(array);
expect(path).to.be.a.directory(msg).with.deep.files(array, msg);
// #7
expect(path).to.be.a.directory(msg).and.not.have.deep.files(array);
expect(path).to.be.a.directory(msg).and.not.have.deep.files(array, msg);
// #8
expect(path).to.be.a.directory(msg).and.not.have.deep.files(array);
expect(path).to.be.a.directory(msg).and.not.have.deep.files(array, msg);
// #9
expect(path).to.be.a.directory(msg).and.include.files(array);
expect(path).to.be.a.directory(msg).and.include.files(array, msg);
// #10
expect(path).to.be.a.directory(msg).and.not.include.files(array);
expect(path).to.be.a.directory(msg).and.not.include.files(array, msg);
// #1
path.should.be.a.directory(msg).with.files(array);
path.should.be.a.directory(msg).with.files(array, msg);
// #2
path.should.be.a.directory().and.not.have.files(array);
path.should.be.a.directory(msg).and.not.have.files(array);
path.should.be.a.directory(msg).and.not.have.files(array, msg);
// #3
path.should.be.a.directory().with.deep.files(array);
path.should.be.a.directory(msg).with.deep.files(array);
path.should.be.a.directory(msg).with.deep.files(array, msg);
// #4
path.should.be.a.directory(msg).and.not.have.deep.files(array);
path.should.be.a.directory(msg).and.not.have.deep.files(array, msg);
// #5
path.should.be.a.directory(msg).and.include.files(array);
path.should.be.a.directory(msg).and.include.files(array, msg);
// #6
path.should.be.a.directory(msg).and.not.include.files(array);
path.should.be.a.directory(msg).and.not.include.files(array, msg);
assert.directoryFiles(path, array);
assert.directoryFiles(path, array, msg);
assert.notDirectoryFiles(path, array);
assert.notDirectoryFiles(path, array, msg);
assert.directoryDeepFiles(path, array);
assert.directoryDeepFiles(path, array, msg);
assert.notDirectoryDeepFiles(path, array);
assert.notDirectoryDeepFiles(path, array, msg);
assert.directoryIncludeFiles(path, array);
assert.directoryIncludeFiles(path, array, msg);
assert.notDirectoryIncludeFiles(path, array);
assert.notDirectoryIncludeFiles(path, array, msg);
// directory().with.subDirs([...])
// #1
expect(path).to.be.a.directory(msg).with.subDirs(array);
expect(path).to.be.a.directory(msg).with.subDirs(array, msg);
// #2
expect(path).to.be.a.directory(msg).and.not.have.subDirs(array);
expect(path).to.be.a.directory(msg).and.not.have.subDirs(array, msg);
// #3
expect(path).to.be.a.directory(msg).with.deep.subDirs(array);
expect(path).to.be.a.directory(msg).with.deep.subDirs(array, msg);
// #4
expect(path).to.be.a.directory(msg).and.not.have.deep.subDirs(array);
expect(path).to.be.a.directory(msg).and.not.have.deep.subDirs(array, msg);
// #5
expect(path).to.be.a.directory(msg).and.include.subDirs(array);
expect(path).to.be.a.directory(msg).and.include.subDirs(array, msg);
// #6
expect(path).to.be.a.directory(msg).and.not.include.subDirs(array);
expect(path).to.be.a.directory(msg).and.not.include.subDirs(array, msg);
// #1
path.should.be.a.directory(msg).with.subDirs(array);
path.should.be.a.directory(msg).with.subDirs(array, msg);
// #2
path.should.be.a.directory(msg).and.not.have.subDirs(array);
path.should.be.a.directory(msg).and.not.have.subDirs(array, msg);
// #3
path.should.be.a.directory(msg).with.deep.subDirs(array);
path.should.be.a.directory(msg).with.deep.subDirs(array, msg);
// #4
path.should.be.a.directory(msg).and.not.have.deep.subDirs(array);
path.should.be.a.directory(msg).and.not.have.deep.subDirs(array, msg);
// #5
path.should.be.a.directory(msg).and.include.subDirs(array);
path.should.be.a.directory(msg).and.include.subDirs(array, msg);
// #6
path.should.be.a.directory(msg).and.not.include.subDirs(array);
path.should.be.a.directory(msg).and.not.include.subDirs(array, msg);
assert.directorySubDirs(path, array, msg);
assert.notDirectorySubDirs(path, array, msg);
assert.directoryDeepSubDirs(path, array, msg);
assert.notDirectoryDeepSubDirs(path, array, msg);
assert.directoryIncludeSubDirs(path, array, msg);
assert.notDirectoryIncludeSubDirs(path, array, msg);
// directory().and.equal(otherPath)
// #1
expect(path).to.be.a.directory(msg).and.equal(otherPath);
expect(path).to.be.a.directory(msg).and.equal(otherPath, msg);
// #2
expect(path).to.be.a.directory(msg).and.not.equal(otherPath);
expect(path).to.be.a.directory(msg).and.not.equal(otherPath, msg);
// #3
expect(path).to.be.a.directory(msg).and.deep.equal(otherPath);
expect(path).to.be.a.directory(msg).and.deep.equal(otherPath, msg);
// #4
expect(path).to.be.a.directory(msg).and.not.deep.equal(otherPath);
expect(path).to.be.a.directory(msg).and.not.deep.equal(otherPath, msg);
// #1
path.should.be.a.directory(msg).and.equal(otherPath);
path.should.be.a.directory(msg).and.equal(otherPath, msg);
// #2
path.should.be.a.directory(msg).and.not.equal(otherPath);
path.should.be.a.directory(msg).and.not.equal(otherPath, msg);
// #3
path.should.be.a.directory(msg).and.deep.equal(otherPath);
path.should.be.a.directory(msg).and.deep.equal(otherPath, msg);
// #4
path.should.be.a.directory(msg).and.not.deep.equal(otherPath);
path.should.be.a.directory(msg).and.not.deep.equal(otherPath, msg);
assert.directoryEqual(path, otherPath, msg);
assert.notDirectoryEqual(path, otherPath, msg);
assert.directoryDeepEqual(path, otherPath, msg);
assert.notDirectoryDeepEqual(path, otherPath, msg);
// file()
expect(path).to.be.a.file();
expect(path).to.be.a.file(msg);
expect(path).to.not.be.a.file();
expect(path).to.not.be.a.file(msg);
path.should.be.a.file();
path.should.be.a.file(msg);
path.should.not.be.a.file();
path.should.not.be.a.file(msg);
assert.isFile(path);
assert.isFile(path, msg);
assert.notIsFile(path);
assert.notIsFile(path, msg);
// file().and.empty
expect(path).to.be.a.file(msg).and.empty;
expect(path).to.be.a.file(msg).and.not.empty;
path.should.be.a.file(msg).and.empty;
path.should.be.a.file(msg).and.not.empty;
assert.isEmptyFile(path, msg);
assert.notIsEmptyFile(path, msg);
// file().with.content(str)
expect(path).to.be.a.file(msg).with.content(data);
expect(path).to.be.a.file(msg).with.content(data, msg);
expect(path).to.be.a.file(msg).and.not.have.content(data);
expect(path).to.be.a.file(msg).and.not.have.content(data, msg);
path.should.be.a.file(msg).with.content(data);
path.should.be.a.file(msg).with.content(data, msg);
path.should.be.a.file(msg).and.not.have.content(data);
path.should.be.a.file(msg).and.not.have.content(data, msg);
assert.fileContent(path, data);
assert.fileContent(path, data, msg);
assert.notFileContent(path, data);
assert.notFileContent(path, data, msg);
// file().with.contents.that.match(/xyz/)
// expect(path).to.be.a.file(msg).with.contents.that.match(/xyz/, msg);
// expect(path).to.be.a.file(msg).and.not.have.contents.that.match(/xyz/, msg);
// path.should.be.a.file(msg).with.contents.that.match(/xyz/, msg);
// path.should.be.a.file(msg).and.not.have.contents.that.match(/xyz/, msg);
assert.fileContentMatch(path, /xyz/);
assert.fileContentMatch(path, /xyz/, msg);
assert.notFileContentMatch(path, /xyz/);
assert.notFileContentMatch(path, /xyz/, msg);
// file().and.equal(otherPath)
expect(path).to.be.a.file(msg).and.equal(otherPath);
expect(path).to.be.a.file(msg).and.equal(otherPath, msg);
expect(path).to.be.a.file(msg).and.not.equal(otherPath);
expect(path).to.be.a.file(msg).and.not.equal(otherPath, msg);
path.should.be.a.file(msg).and.equal(otherPath);
path.should.be.a.file(msg).and.equal(otherPath, msg);
path.should.be.a.file(msg).and.not.equal(otherPath);
path.should.be.a.file(msg).and.not.equal(otherPath, msg);
assert.fileEqual(path, otherPath, msg);
assert.notFileEqual(path, otherPath, msg);
// file().with.json
expect(path).to.be.a.file(msg).with.json;
expect(path).to.be.a.file(msg).with.not.json;
path.should.be.a.file(msg).with.json;
path.should.be.a.file(msg).with.not.json;
assert.jsonFile(path);
assert.jsonFile(path, msg);
assert.notJsonFile(path);
assert.notJsonFile(path, msg);
// file().using.json.schema(obj)
expect(path).to.be.a.file(msg).with.json.using.schema(obj);
expect(path).to.be.a.file(msg).with.json.not.using.schema(obj);
path.should.be.a.file(msg).with.json.using.schema(obj);
path.should.be.a.file(msg).with.json.not.using.schema(obj);
assert.jsonSchemaFile(path, schema);
assert.jsonSchemaFile(path, schema, msg);
assert.notJsonSchemaFile(path, schema);
assert.notJsonSchemaFile(path, schema, msg); | the_stack |
import axios, { AxiosError } from 'axios';
import hljs from 'highlight.js';
import { License, Homepage, Versions, Dependency, Dependencies, ReverseDependency, DependencyCondition } from '../components/pages/package/common';
import cheerio, { CheerioAPI, BasicAcceptedElems } from 'cheerio';
import unescape from 'lodash/unescape';
export type Package = {
id: string,
name: string,
versions: Versions | null,
currentVersion: string | null,
versionsCount: number,
shortDescription: string | null,
longDescriptionHtml: string | null,
license: License | null,
homepageUrl: Homepage | null,
repositoryUrl: string | null,
bugReportsUrl: string | null,
updatedAt: string | null,
reverseDependencies: ReverseDependency[] | null,
dependencies: Dependencies | null
}
export async function getPackage(packageId: string): Promise<null | Package> {
let html = '';
try {
html = await getPackageRawHtml(packageId);
} catch (err) {
console.log(err);
}
if (html === '') {
return null;
}
const $ = cheerio.load(html);
monkeyPatchDocument($);
const docContent = $('#content');
const name = $('h1 a', docContent).html()?.trim() || '';
const shortDescription = $('h1 small', docContent).html()?.trim() || null;
const longDescriptionHtml = $('#description').html()?.trim() || null;
// XXX - take care on the order of arguments here... Or implement a better solution.
const [
versions,
dependencies,
reverseDependencies
] = await (await Promise.allSettled([
await getVersions(name),
await getDependencies(packageId),
await getReverseDependencies(name),
])).map((res) => (res as any).value) as [
Versions,
Dependencies,
ReverseDependency[]
];
const versionsCount = Array.from(new Set([
...versions.normal,
...versions.unpreferred,
...versions.deprecated,
])).length;
return {
id: packageId,
name,
currentVersion: getCurrentVersion($),
versions,
versionsCount,
bugReportsUrl: getBugReportsUrl($),
homepageUrl: getHomepageUrl($),
license: getLicense($),
shortDescription,
longDescriptionHtml,
repositoryUrl: getRepositoryUrl($),
updatedAt: getUpdatedAt($),
reverseDependencies,
dependencies
}
}
// highlight.js often recognize Haskell code as Erlang, OCaml and others.
// We decided to specify subset of popular languages here excluding from ML family.
// If you want to modify the list or know a better solution, please raise an issue or pull request at our issue tracker.
// Full list here https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md
const languagesToHighlight = [
'Haskell',
'Shell',
'Bash',
'Diff',
'JSON',
'LaTeX',
'Protocol Buffers',
'TOML',
'XML',
'YAML',
'Nix'
];
export async function getPackageRawHtml(packageId: string): Promise<string> {
let html: string = '';
try {
html = await (await axios(`https://hackage.haskell.org/package/${encodeURIComponent(packageId)}`)).data;
} catch (err) {
if (!(axios.isAxiosError(err) && err.response?.status === 404)) {
console.log(err);
}
}
return html;
}
// XXX - We can get rid of most content of this function after the hackage-server will implement missing APIs.
export function monkeyPatchDocument($: CheerioAPI): void {
// Rewrite urls.
$('a').map((_, a) => {
$(a).attr('href', $(a).attr('href')?.replace('https://hackage.haskell.org/package/', '/package/') || '#')
});
// Highlight code blocks
$('code, pre').map((_, el) => {
/* Ignore blocks containing other HTML elements:
<code><a href="http://hackage.haskell.org/package/array">array</a></code>
*/
if ($(el).children().length) {
return el;
}
const highlightedHtml = hljs.highlightAuto(unescape($(el).html() as string), languagesToHighlight).value;
$(el).html(highlightedHtml);
$(el).addClass('hljs');
});
// Remove "Skip to Readme" links.
const description = $('#content #description');
const newDescriptionHtml = (description.html() || '').replace(`<hr>
[<a href="#readme">Skip to Readme</a>]`, '').trim();
description.html(newDescriptionHtml);
}
export function getCurrentVersion($: CheerioAPI): string | null {
const propertiesElement = $('#properties').get(0);
const tableTd = $(`th:contains('Version') + td`, propertiesElement).get(0);
if (!tableTd) {
return null;
}
return $(`strong`, tableTd).text().trim();
}
export function getLicense($: CheerioAPI): License | null {
const propertiesElement = $('#properties').get(0);
const tableTd = $(`th:contains('License') + td`, propertiesElement).get(0);
if (!tableTd) {
return null;
}
const licenseEl = $(`> *`, tableTd);
return { name: $(tableTd).text(), url: licenseEl.attr('href') || null };
}
export function getHomepageUrl($: CheerioAPI): Homepage | null {
const propertiesElement = $('#properties').get(0);
const tableTd = $(`th:contains('Home page') + td`, propertiesElement).get(0);
if (!tableTd) {
return null;
}
const homepageLink = $(`a`, tableTd);
return {
text: homepageLink.text().trim(),
url: homepageLink.attr('href')?.trim() || '#'
};
}
export function getRepositoryUrl($: CheerioAPI): string | null {
const propertiesElement = $('#properties').get(0);
const tableTd = $(`th:contains('Source') + td`, propertiesElement).get(0);
if (!tableTd) {
return null;
}
const repositoryLink = $(`a`, tableTd);
return repositoryLink.attr('href')?.trim() || null;
}
export function getBugReportsUrl($: CheerioAPI): string | null {
const propertiesElement = $('#properties').get(0);
const tableTd = $(`th:contains('Bug') + td`, propertiesElement).get(0);
if (!tableTd) {
return null;
}
const repositoryLink = $(`a`, tableTd);
return repositoryLink.attr('href')?.trim() || null;
}
export function getUpdatedAt($: CheerioAPI): string | null {
const propertiesElement = $('#properties').get(0);
const tableTd = $(`th:contains('Uploaded') + td`, propertiesElement).get(0);
if (!tableTd) {
return null;
}
return $(tableTd).text().replace(/^by .* at /, '').trim();
}
export async function getVersions(packageName: string): Promise<Versions> {
// ee5ad44c22b245e960ee2f8670ada3a55bbb7e16
let versions: Versions = { normal: [], unpreferred: [], deprecated: [] };
try {
const data = await (await axios.get(`https://hackage.haskell.org/package/${packageName}/preferred`, { headers: { accept: 'application/json' } })).data;
versions = {
normal: data['normal-version'] || [],
unpreferred: data['unpreferred-version'] || [],
deprecated: data['deprecated-version'] || [],
}
} catch (err) {
console.log(err);
} finally {
return versions;
}
}
export async function getDependencies(packageId: string): Promise<Dependencies> {
let dependencies: Dependencies = { modules: [], dependenciesCount: 0, conditionalDependenciesCount: 0 };
let html: string = '';
try {
html = await (await axios(`https://hackage.haskell.org/package/${encodeURIComponent(packageId)}/dependencies`)).data;
const $ = cheerio.load(html);
const getDep = (li: BasicAcceptedElems<any>): Dependency => {
const versionRangeSpecified = $(li).text().trim().match(/^.*\(.*\)$/);
return {
packageName: $('a', li).text().trim(),
versionsRange: versionRangeSpecified ? $(li).text().trim().replace(/^.*\(/, '').replace(/\).*$/, '') : null
}
}
const modules = $('#content table.properties > tbody > tr').toArray().map(tr => {
return {
name: $('th', tr).text().trim(),
dependencies: $('> td > #detailed-dependencies > ul > li:not(:has(strong))', tr).map((_, li) => getDep(li)).toArray(),
conditions: $('> td > #detailed-dependencies > ul > li:has(strong)', tr).map((_, li) => {
const elements = $(li).contents();
const ifIndex = $(elements).index($('strong:contains(if)', li));
const elseIndex = $(elements).index($('strong:contains(else)', li));
const predicate = $($(elements).get(ifIndex + 1)).text().trim();
const ifBranchEl = $(elements).get(ifIndex + 2);
const elseBranchEl = $(elements).get(elseIndex + 1);
const ifDeps = $('> ul > li:not(:has(strong))', ifBranchEl).map((_, li) => getDep(li)).toArray();
const elseDeps = $('> ul > li:not(:has(strong))', elseBranchEl).map((_, li) => getDep(li)).toArray();
const condition: DependencyCondition = {
predicate,
ifDeps,
elseDeps
}
return condition;
}).toArray()
}
});
// Probably deduplicate dependencies here?
const conditionalDependenciesCount = modules.reduce((c, m) => c + m.conditions.reduce((mc, cm) => mc + cm.ifDeps.length + cm.elseDeps.length, 0), 0);
const dependenciesCount = modules.reduce((c, m) => c + m.dependencies.length, 0);
dependencies = { modules, dependenciesCount, conditionalDependenciesCount };
} catch (err) {
if (!axios.isAxiosError(err)) {
console.log(err);
}
} finally {
return dependencies;
}
}
export async function getReverseDependencies(packageName: string): Promise<ReverseDependency[]> {
let reverseDependencies: ReverseDependency[] = [];
let html: string = '';
try {
html = await (await axios(`https://packdeps.haskellers.com/reverse/${encodeURIComponent(packageName)}`)).data;
const $ = cheerio.load(html);
reverseDependencies = $('table tbody tr').toArray().map(tr => {
const isOutdated = $(tr).hasClass('out-of-date');
const tds = $('td', tr);
const td0 = $(tds).get(0);
const td1 = $(tds).get(1);
const packageName = $(td0).text().trim();
const versionsRange = $(td1).text().trim();
const hasReverseDependencies = $('a', td0).toArray().length > 0;
return {
isOutdated,
packageName,
versionsRange,
hasReverseDependencies
}
});
} catch (err) {
if (!axios.isAxiosError(err)) {
console.log(err);
}
} finally {
return reverseDependencies;
}
} | the_stack |
import tcb from '../../src/index'
import assert, { rejects } from 'assert'
import config from '../config.local'
import { SYMBOL_CURRENT_ENV } from '../../src/const/symbol'
import { create } from 'domain'
const app = tcb.init({
...config,
credentials: {
private_key_id: 'da86590d-dd17-45bd-84df-433f05612d0a',
private_key:
'-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDNo9vk/GFDkihEJv5SbN4zQKW9OAjf4C2Z13eGYxLYIYhwNDi5\nl2O5+NLpPzH4Q839ULJIYQ6hfBAVO7mvQ+WP2oYeIqQyRe9NkDlCLmJ10SDwGQRq\nqekVHbz+2fIugxJf3BqIDX3nSHC4TkZZldSgZJIBwIUI5h0t2/IqEjFaHwIDAQAB\nAoGBALdRZrrIPhDVn2258Sgbgy3faKC47jhdiWlGinfTpD3mDtIvy42vJqjn52Uk\n/+/Yyi4THQum8jsE9PVoy8wxU9eDJN4AVjNf8Y98a/z8FCEVyXsvUPp4+Y9pPSmd\nmZe6JKU3mDTXtQDMrtZlkSHVGhSCo/vLMccrAdus8DEnWD0BAkEA2scDuCx9qb4A\nHs8t2j1jL483lsTT8dV8bX5UCwIpOP8jCgQmBbxIyL3/IIwonS7eRSeUDhh2aim+\ng2uhxqSygQJBAPCgo9jOQ/uwy2YjSOE3r6Q1gDCfclvY9z2Xb2IH0AZg529l2rg2\nqh3PPFEB7dBxzNimu9rhDG+dre61ilNwfJ8CQFrCfTSGoIsum3YslOUY2nD8hR8z\nAIou+rOh2NPITbmrfqnFFtECT1+YEqM6Ag9TRjqCNNW0KEvajYKPwElcQgECQHQj\nJFGM5FUDNHh8iT1iUhywUcml+10HL/WDNJgc6zNY6/rhLxqAD8VJc3QpuS1E77iV\naM+wlP7+HKe86SFyhkMCQFWmIveCeb0U0MTHV+Uem1vYWu5gLwSRvvvQlBiTx8Nb\ngLo8C8GxW6uCVPxk4gqnvwVSIN8sBfxQksHMOU3zQYo=\n-----END RSA PRIVATE KEY-----\n'
// env_id: 'luke-87pns'
}
})
describe('auth 不注入环境变量', () => {
it('校验uid', async () => {
let uid
try {
uid = 1
app.auth().createTicket(uid)
} catch (e) {
assert(e.message === 'uid must be a string')
}
try {
uid = '1'
app.auth().createTicket(uid)
} catch (e) {
assert(e.message === `Invalid uid: "${uid}"`)
}
})
})
describe('auth 注入环境变量', () => {
// it('生成登录ticket', async () => {
// const result = app.auth().createTicket('oyeju0Eoc1ZCEgyxfk2vNeYDMpRs', {
// refresh: 5000
// })
// assert(result)
// }, 30000)
// it('生成登录ticket 不传refresh', async () => {
// const result = app.auth().createTicket('oyeju0Eoc1ZCEgyxfk2vNeYDMpRs')
// assert(result)
// }, 30000)
it('不注入环境变量 默认取空字符串', async () => {
process.env.WX_OPENID = ''
process.env.WX_APPID = ''
process.env.TCB_UUID = ''
process.env.TCB_CUSTOM_USER_ID = ''
process.env.TCB_SOURCE_IP = ''
assert.deepStrictEqual(app.auth().getUserInfo(), {
openId: '',
appId: '',
uid: '',
customUserId: '',
isAnonymous: false
})
assert.deepStrictEqual(app.auth().getClientIP(), '')
assert.deepStrictEqual(app.auth().getEndUserInfo(), {
userInfo: {
openId: '',
appId: '',
uid: '',
customUserId: '',
isAnonymous: false
}
})
})
it('mock getEndUserInfo return code', async () => {
jest.resetModules()
jest.mock('request', () => {
return jest.fn().mockImplementation((params, callback) => {
const body = { code: 'mockCode', message: 'mockMessage' }
process.nextTick(() => {
callback(null, { req: {reusedSocket: false}, statusCode: 200, body })
})
})
})
const tcb1 = require('../../src/index')
const app1 = tcb1.init({
...config,
credentials: {
private_key_id: 'da86590d-dd17-45bd-84df-433f05612d0a',
private_key:
'-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDNo9vk/GFDkihEJv5SbN4zQKW9OAjf4C2Z13eGYxLYIYhwNDi5\nl2O5+NLpPzH4Q839ULJIYQ6hfBAVO7mvQ+WP2oYeIqQyRe9NkDlCLmJ10SDwGQRq\nqekVHbz+2fIugxJf3BqIDX3nSHC4TkZZldSgZJIBwIUI5h0t2/IqEjFaHwIDAQAB\nAoGBALdRZrrIPhDVn2258Sgbgy3faKC47jhdiWlGinfTpD3mDtIvy42vJqjn52Uk\n/+/Yyi4THQum8jsE9PVoy8wxU9eDJN4AVjNf8Y98a/z8FCEVyXsvUPp4+Y9pPSmd\nmZe6JKU3mDTXtQDMrtZlkSHVGhSCo/vLMccrAdus8DEnWD0BAkEA2scDuCx9qb4A\nHs8t2j1jL483lsTT8dV8bX5UCwIpOP8jCgQmBbxIyL3/IIwonS7eRSeUDhh2aim+\ng2uhxqSygQJBAPCgo9jOQ/uwy2YjSOE3r6Q1gDCfclvY9z2Xb2IH0AZg529l2rg2\nqh3PPFEB7dBxzNimu9rhDG+dre61ilNwfJ8CQFrCfTSGoIsum3YslOUY2nD8hR8z\nAIou+rOh2NPITbmrfqnFFtECT1+YEqM6Ag9TRjqCNNW0KEvajYKPwElcQgECQHQj\nJFGM5FUDNHh8iT1iUhywUcml+10HL/WDNJgc6zNY6/rhLxqAD8VJc3QpuS1E77iV\naM+wlP7+HKe86SFyhkMCQFWmIveCeb0U0MTHV+Uem1vYWu5gLwSRvvvQlBiTx8Nb\ngLo8C8GxW6uCVPxk4gqnvwVSIN8sBfxQksHMOU3zQYo=\n-----END RSA PRIVATE KEY-----\n'
}
})
expect(app1.auth().getEndUserInfo('c7446481324445a0bca211d747281ca3')).rejects.toThrow(
new Error('mockMessage')
)
const app2 = tcb1.init({
...config,
credentials: {
private_key_id: 'da86590d-dd17-45bd-84df-433f05612d0a',
private_key:
'-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDNo9vk/GFDkihEJv5SbN4zQKW9OAjf4C2Z13eGYxLYIYhwNDi5\nl2O5+NLpPzH4Q839ULJIYQ6hfBAVO7mvQ+WP2oYeIqQyRe9NkDlCLmJ10SDwGQRq\nqekVHbz+2fIugxJf3BqIDX3nSHC4TkZZldSgZJIBwIUI5h0t2/IqEjFaHwIDAQAB\nAoGBALdRZrrIPhDVn2258Sgbgy3faKC47jhdiWlGinfTpD3mDtIvy42vJqjn52Uk\n/+/Yyi4THQum8jsE9PVoy8wxU9eDJN4AVjNf8Y98a/z8FCEVyXsvUPp4+Y9pPSmd\nmZe6JKU3mDTXtQDMrtZlkSHVGhSCo/vLMccrAdus8DEnWD0BAkEA2scDuCx9qb4A\nHs8t2j1jL483lsTT8dV8bX5UCwIpOP8jCgQmBbxIyL3/IIwonS7eRSeUDhh2aim+\ng2uhxqSygQJBAPCgo9jOQ/uwy2YjSOE3r6Q1gDCfclvY9z2Xb2IH0AZg529l2rg2\nqh3PPFEB7dBxzNimu9rhDG+dre61ilNwfJ8CQFrCfTSGoIsum3YslOUY2nD8hR8z\nAIou+rOh2NPITbmrfqnFFtECT1+YEqM6Ag9TRjqCNNW0KEvajYKPwElcQgECQHQj\nJFGM5FUDNHh8iT1iUhywUcml+10HL/WDNJgc6zNY6/rhLxqAD8VJc3QpuS1E77iV\naM+wlP7+HKe86SFyhkMCQFWmIveCeb0U0MTHV+Uem1vYWu5gLwSRvvvQlBiTx8Nb\ngLo8C8GxW6uCVPxk4gqnvwVSIN8sBfxQksHMOU3zQYo=\n-----END RSA PRIVATE KEY-----\n'
},
throwOnCode: false
})
const res = await app2.auth().getEndUserInfo('c7446481324445a0bca211d747281ca3')
assert.ok(res.code === 'mockCode')
})
it('mock auth.getUserInfoForAdmin 接口报错', async () => {
const uid = 'luke123'
expect(app.auth().getEndUserInfo(uid)).rejects.toThrow(
new Error('[100007] user_do_not_exist')
)
})
it('获取用户信息getUserInfo 不传入uid', () => {
process.env.WX_OPENID = 'WX_OPENID'
process.env.WX_APPID = 'WX_APPID'
process.env.TCB_UUID = 'TCB_UUID'
process.env.TCB_CUSTOM_USER_ID = 'TCB_CUSTOM_USER_ID'
process.env.TCB_ISANONYMOUS_USER = 'true'
process.env.TCB_CONTEXT_KEYS = 'TCB_UUID,TCB_CUSTOM_USER_ID,TCB_ISANONYMOUS_USER'
process.env.WX_CONTEXT_KEYS = 'WX_OPENID,WX_APPID'
assert.deepStrictEqual(app.auth().getUserInfo(), {
openId: 'WX_OPENID',
appId: 'WX_APPID',
uid: 'TCB_UUID',
customUserId: 'TCB_CUSTOM_USER_ID',
isAnonymous: true
})
})
it('获取云开发用户信息 getEndUserInfo 传入uid', async () => {
try {
const { userInfo } = await app.auth().getEndUserInfo('c7446481324445a0bca211d747281ca3')
const keysAreValid = [
'openId',
'appId',
'uid',
'customUserId',
'isAnonymous',
'envName',
'nickName',
'gender',
'country',
'province',
'city',
'avatarUrl',
'uuid',
'wxOpenid',
'wxOpenId',
'wxUnionId',
'wxPublicId',
'qqMiniOpenId',
'email',
'hasPassword',
'username',
'createTime',
'updateTime'
].every(key => userInfo.hasOwnProperty(key))
assert.ok(keysAreValid)
} catch (error) {
assert.ok(error instanceof Error)
}
})
it('获取客户端IP', async () => {
process.env.TCB_SOURCE_IP = 'TCB_SOURCE_IP'
process.env.TCB_CONTEXT_KEYS = 'TCB_SOURCE_IP'
assert.deepStrictEqual(app.auth().getClientIP(), 'TCB_SOURCE_IP')
})
it('校验createTicket 时,init config 不含 env', async () => {
const app1 = tcb.init({
...config,
credentials: {
private_key_id: 'da86590d-dd17-45bd-84df-433f05612d0a',
private_key:
'-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDNo9vk/GFDkihEJv5SbN4zQKW9OAjf4C2Z13eGYxLYIYhwNDi5\nl2O5+NLpPzH4Q839ULJIYQ6hfBAVO7mvQ+WP2oYeIqQyRe9NkDlCLmJ10SDwGQRq\nqekVHbz+2fIugxJf3BqIDX3nSHC4TkZZldSgZJIBwIUI5h0t2/IqEjFaHwIDAQAB\nAoGBALdRZrrIPhDVn2258Sgbgy3faKC47jhdiWlGinfTpD3mDtIvy42vJqjn52Uk\n/+/Yyi4THQum8jsE9PVoy8wxU9eDJN4AVjNf8Y98a/z8FCEVyXsvUPp4+Y9pPSmd\nmZe6JKU3mDTXtQDMrtZlkSHVGhSCo/vLMccrAdus8DEnWD0BAkEA2scDuCx9qb4A\nHs8t2j1jL483lsTT8dV8bX5UCwIpOP8jCgQmBbxIyL3/IIwonS7eRSeUDhh2aim+\ng2uhxqSygQJBAPCgo9jOQ/uwy2YjSOE3r6Q1gDCfclvY9z2Xb2IH0AZg529l2rg2\nqh3PPFEB7dBxzNimu9rhDG+dre61ilNwfJ8CQFrCfTSGoIsum3YslOUY2nD8hR8z\nAIou+rOh2NPITbmrfqnFFtECT1+YEqM6Ag9TRjqCNNW0KEvajYKPwElcQgECQHQj\nJFGM5FUDNHh8iT1iUhywUcml+10HL/WDNJgc6zNY6/rhLxqAD8VJc3QpuS1E77iV\naM+wlP7+HKe86SFyhkMCQFWmIveCeb0U0MTHV+Uem1vYWu5gLwSRvvvQlBiTx8Nb\ngLo8C8GxW6uCVPxk4gqnvwVSIN8sBfxQksHMOU3zQYo=\n-----END RSA PRIVATE KEY-----\n'
// env_id: 'luke-87pns'
},
env: ''
})
expect(() => {
app1.auth().createTicket('luke123')
}).toThrow(new Error('no env in config'))
})
it('校验createTicket时,init config 为 symbol_current_env', async () => {
process.env.SCF_NAMESPACE = 'luke-87pns'
const app1 = tcb.init({
...config,
credentials: {
private_key_id: 'da86590d-dd17-45bd-84df-433f05612d0a',
private_key:
'-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDNo9vk/GFDkihEJv5SbN4zQKW9OAjf4C2Z13eGYxLYIYhwNDi5\nl2O5+NLpPzH4Q839ULJIYQ6hfBAVO7mvQ+WP2oYeIqQyRe9NkDlCLmJ10SDwGQRq\nqekVHbz+2fIugxJf3BqIDX3nSHC4TkZZldSgZJIBwIUI5h0t2/IqEjFaHwIDAQAB\nAoGBALdRZrrIPhDVn2258Sgbgy3faKC47jhdiWlGinfTpD3mDtIvy42vJqjn52Uk\n/+/Yyi4THQum8jsE9PVoy8wxU9eDJN4AVjNf8Y98a/z8FCEVyXsvUPp4+Y9pPSmd\nmZe6JKU3mDTXtQDMrtZlkSHVGhSCo/vLMccrAdus8DEnWD0BAkEA2scDuCx9qb4A\nHs8t2j1jL483lsTT8dV8bX5UCwIpOP8jCgQmBbxIyL3/IIwonS7eRSeUDhh2aim+\ng2uhxqSygQJBAPCgo9jOQ/uwy2YjSOE3r6Q1gDCfclvY9z2Xb2IH0AZg529l2rg2\nqh3PPFEB7dBxzNimu9rhDG+dre61ilNwfJ8CQFrCfTSGoIsum3YslOUY2nD8hR8z\nAIou+rOh2NPITbmrfqnFFtECT1+YEqM6Ag9TRjqCNNW0KEvajYKPwElcQgECQHQj\nJFGM5FUDNHh8iT1iUhywUcml+10HL/WDNJgc6zNY6/rhLxqAD8VJc3QpuS1E77iV\naM+wlP7+HKe86SFyhkMCQFWmIveCeb0U0MTHV+Uem1vYWu5gLwSRvvvQlBiTx8Nb\ngLo8C8GxW6uCVPxk4gqnvwVSIN8sBfxQksHMOU3zQYo=\n-----END RSA PRIVATE KEY-----\n',
env_id: 'luke-87pns'
},
env: SYMBOL_CURRENT_ENV
})
const createTicketRes = app1.auth().createTicket('luke123')
assert.ok(typeof createTicketRes === 'string')
process.env.TCB_ENV = ''
})
it('校验credentials 不含env', async () => {
let result
try {
result = app.auth().createTicket('oyeju0Eoc1ZCEgyxfk2vNeYDMpRs')
} catch (e) {
assert(e.code === 'INVALID_PARAM')
}
})
it('校验credentials 含 env 且 与 init env不一致', async () => {
const app1 = tcb.init({
...config,
credentials: {
private_key_id: 'da86590d-dd17-45bd-84df-433f05612d0a',
private_key:
'-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDNo9vk/GFDkihEJv5SbN4zQKW9OAjf4C2Z13eGYxLYIYhwNDi5\nl2O5+NLpPzH4Q839ULJIYQ6hfBAVO7mvQ+WP2oYeIqQyRe9NkDlCLmJ10SDwGQRq\nqekVHbz+2fIugxJf3BqIDX3nSHC4TkZZldSgZJIBwIUI5h0t2/IqEjFaHwIDAQAB\nAoGBALdRZrrIPhDVn2258Sgbgy3faKC47jhdiWlGinfTpD3mDtIvy42vJqjn52Uk\n/+/Yyi4THQum8jsE9PVoy8wxU9eDJN4AVjNf8Y98a/z8FCEVyXsvUPp4+Y9pPSmd\nmZe6JKU3mDTXtQDMrtZlkSHVGhSCo/vLMccrAdus8DEnWD0BAkEA2scDuCx9qb4A\nHs8t2j1jL483lsTT8dV8bX5UCwIpOP8jCgQmBbxIyL3/IIwonS7eRSeUDhh2aim+\ng2uhxqSygQJBAPCgo9jOQ/uwy2YjSOE3r6Q1gDCfclvY9z2Xb2IH0AZg529l2rg2\nqh3PPFEB7dBxzNimu9rhDG+dre61ilNwfJ8CQFrCfTSGoIsum3YslOUY2nD8hR8z\nAIou+rOh2NPITbmrfqnFFtECT1+YEqM6Ag9TRjqCNNW0KEvajYKPwElcQgECQHQj\nJFGM5FUDNHh8iT1iUhywUcml+10HL/WDNJgc6zNY6/rhLxqAD8VJc3QpuS1E77iV\naM+wlP7+HKe86SFyhkMCQFWmIveCeb0U0MTHV+Uem1vYWu5gLwSRvvvQlBiTx8Nb\ngLo8C8GxW6uCVPxk4gqnvwVSIN8sBfxQksHMOU3zQYo=\n-----END RSA PRIVATE KEY-----\n',
// env_id: 'luke-87pns'
env_id: 'luketest-0nmm1'
}
})
let result
try {
result = app1.auth().createTicket('oyeju0Eoc1ZCEgyxfk2vNeYDMpRs')
} catch (e) {
assert(e.code === 'INVALID_PARAM')
}
})
it('校验credentials 含 env 且 与 init env 一致', async () => {
const app1 = tcb.init({
...config,
credentials: {
private_key_id: 'da86590d-dd17-45bd-84df-433f05612d0a',
private_key:
'-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDNo9vk/GFDkihEJv5SbN4zQKW9OAjf4C2Z13eGYxLYIYhwNDi5\nl2O5+NLpPzH4Q839ULJIYQ6hfBAVO7mvQ+WP2oYeIqQyRe9NkDlCLmJ10SDwGQRq\nqekVHbz+2fIugxJf3BqIDX3nSHC4TkZZldSgZJIBwIUI5h0t2/IqEjFaHwIDAQAB\nAoGBALdRZrrIPhDVn2258Sgbgy3faKC47jhdiWlGinfTpD3mDtIvy42vJqjn52Uk\n/+/Yyi4THQum8jsE9PVoy8wxU9eDJN4AVjNf8Y98a/z8FCEVyXsvUPp4+Y9pPSmd\nmZe6JKU3mDTXtQDMrtZlkSHVGhSCo/vLMccrAdus8DEnWD0BAkEA2scDuCx9qb4A\nHs8t2j1jL483lsTT8dV8bX5UCwIpOP8jCgQmBbxIyL3/IIwonS7eRSeUDhh2aim+\ng2uhxqSygQJBAPCgo9jOQ/uwy2YjSOE3r6Q1gDCfclvY9z2Xb2IH0AZg529l2rg2\nqh3PPFEB7dBxzNimu9rhDG+dre61ilNwfJ8CQFrCfTSGoIsum3YslOUY2nD8hR8z\nAIou+rOh2NPITbmrfqnFFtECT1+YEqM6Ag9TRjqCNNW0KEvajYKPwElcQgECQHQj\nJFGM5FUDNHh8iT1iUhywUcml+10HL/WDNJgc6zNY6/rhLxqAD8VJc3QpuS1E77iV\naM+wlP7+HKe86SFyhkMCQFWmIveCeb0U0MTHV+Uem1vYWu5gLwSRvvvQlBiTx8Nb\ngLo8C8GxW6uCVPxk4gqnvwVSIN8sBfxQksHMOU3zQYo=\n-----END RSA PRIVATE KEY-----\n',
env_id: 'luke-87pns'
}
})
let result = app1.auth().createTicket('oyeju0Eoc1ZCEgyxfk2vNeYDMpRs')
// console.log(result)
assert(result)
})
}) | the_stack |
import * as zlib_deflate from "./zlib/deflate.js";
import * as utils from "./utils/common.js";
import * as strings from "./utils/strings.js";
import msg from "./zlib/messages.js";
import { ZStream } from "./zlib/zstream.js";
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overridden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
* - `dictionary`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
function Deflate(options) {
if (!(this instanceof Deflate)) return new Deflate(options);
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new ZStream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
if (opt.dictionary) {
var dict;
// Convert data if needed
if (typeof opt.dictionary === 'string') {
// If we need to compress text, change encoding to utf8.
dict = strings.string2buf(opt.dictionary);
} else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
dict = new Uint8Array(opt.dictionary);
} else {
dict = opt.dictionary;
}
status = zlib_deflate.deflateSetDictionary(this.strm, dict);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
this._dict_set = true;
}
}
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function (data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): output data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function (chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function (status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate algorithm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
* - dictionary
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
export {
Deflate,
deflate,
deflateRaw,
gzip
} | the_stack |
const Me = imports.misc.extensionUtils.getCurrentExtension();
/** Gnome libs imports */
import * as Clutter from 'clutter';
import * as GLib from 'glib';
import * as GObject from 'gobject';
import * as Meta from 'meta';
import { App } from 'shell';
import {
MetaWindowActorWithMsProperties,
MetaWindowWithMsProperties,
} from 'src/manager/msWindowManager';
import { Rectangular } from 'src/types/mod';
import { throttle } from 'src/utils';
import { assert, assertNotNull } from 'src/utils/assert';
import { Async } from 'src/utils/async';
/** Extension imports */
import {
Allocate,
AllocatePreferredSize,
SetAllocation,
} from 'src/utils/compatibility';
import { registerGObjectClass } from 'src/utils/gjs';
import { logAsyncException } from 'src/utils/log';
import { set_style_class } from 'src/utils/styling_utils';
import * as WindowUtils from 'src/utils/windows';
import { AppPlaceholder } from 'src/widget/appPlaceholder';
import * as St from 'st';
import { main as Main } from 'ui';
import { MsWorkspace } from './msWorkspace';
import { PrimaryBorderEffect } from './tilingLayouts/baseResizeableTiling';
const isWayland = GLib.getenv('XDG_SESSION_TYPE').toLowerCase() === 'wayland';
export const isMsWindow = (obj: any): obj is MsWindow => {
return obj instanceof MsWindow;
};
export function buildMetaWindowIdentifier(metaWindow: Meta.Window) {
return `${metaWindow.get_wm_class_instance()}-${metaWindow.get_pid()}-${metaWindow.get_stable_sequence()}`;
}
interface Dialog {
metaWindow: MetaWindowWithMsProperties;
clone: Clutter.Clone;
}
export interface MsWindowMatchingInfo {
appId: string;
/** Window title */
title: string | undefined;
pid: number | undefined;
wmClass: string | undefined;
/** Meta windows have a unique integer associated with them, this can be used to differentiate otherwise identical windows */
stableSeq: number | undefined;
}
export interface MsWindowState {
appId: string;
matchingInfo: MsWindowMatchingInfo | undefined;
metaWindowIdentifier: string | null;
persistent: boolean | undefined;
x: number;
y: number;
width: number;
height: number;
}
export interface MsWindowConstructProps {
app: App;
persistent?: boolean;
initialAllocation?: Rectangular;
msWorkspace: MsWorkspace;
lifecycleState: MsWindowLifecycleState;
}
type MsWindowLifecycleState =
| {
/** An MsWindow displaying an app with optional dialogs, or in rare cases only dialogs */
type: 'window';
/** The main window. Note that this can be null if a dialog was opened and then the main window closed */
metaWindow: MetaWindowWithMsProperties | null;
metaWindowSignals: number[];
dialogs: Dialog[];
/** Original matching info from when the window was associated.
* This does not necessarily perfectly match the current window.
* It is used to allow swapping window association for a small duration after an application has started in case new information becomes available.
* For example window titles are often updated if the application loads a document, which it might do automatically on startup.
*/
matchingInfo: MsWindowMatchingInfo;
/** Time when the meta window was associated with this MsWindow */
matchedAtTime: Date;
}
| {
/** An MsWindow showing a placeholder for a particular app */
type: 'app-placeholder';
/** Desired properties of windows to be assigned to this MsWindow.
* This is in particular used when restoring from a persisted state.
* It allows meta windows to be associated with the correct MsWindows when restoring.
*
* These are not hard constraints, they only come into play if there are multiple alternatives
* for how meta windows could be associated with MsWindows.
*/
matchingInfo: MsWindowMatchingInfo;
/** Set when an app has been launched and this window is expecting to be associated to that app */
waitingForAppSince: Date | undefined;
}
| {
/** An MsWindow which will be destroyed soon unless another window or dialog opens */
type: 'waiting-for-destroy';
}
| {
/** A destroyed MsWindow. This cannot be used for anything anymore. */
type: 'destroyed';
};
@registerGObjectClass
export class MsWindow extends Clutter.Actor {
static metaInfo: GObject.MetaInfo = {
GTypeName: 'MsWindow',
Signals: {
title_changed: {
param_types: [GObject.TYPE_STRING],
accumulator: 0,
},
dragged_changed: {
param_types: [GObject.TYPE_BOOLEAN],
accumulator: 0,
},
request_new_meta_window: {
param_types: [],
accumulator: 0,
},
},
};
lifecycleState: MsWindowLifecycleState;
public app: App;
_persistent: boolean | undefined;
windowClone: Clutter.Clone;
placeholder: AppPlaceholder;
destroyId: number;
msContent: MsWindowContent;
msWorkspace: MsWorkspace;
focusEffects?: {
dimmer?: Clutter.BrightnessContrastEffect;
border?: PrimaryBorderEffect;
};
updateMetaWindowPositionAndSizeThrottled: () => void;
constructor({
app,
persistent,
initialAllocation,
msWorkspace,
lifecycleState,
}: MsWindowConstructProps) {
super({
reactive: true,
x: initialAllocation ? initialAllocation.x || 0 : 0,
y: initialAllocation ? initialAllocation.y || 0 : 0,
width: initialAllocation ? initialAllocation.width || 0 : 0,
height: initialAllocation ? initialAllocation.height || 0 : 0,
});
this.lifecycleState = lifecycleState;
this.app = app;
this._persistent = persistent;
this.msWorkspace = msWorkspace;
this.updateMetaWindowPositionAndSizeThrottled = throttle(
() => this.updateMetaWindowPositionAndSizeInternal(),
16
);
this.windowClone = new Clutter.Clone();
this.placeholder = new AppPlaceholder(this.app);
this.placeholder.connect('activated', (_) => {
this.emit('request-new-meta-window');
});
this.destroyId = this.connect('destroy', this._onDestroy.bind(this));
this.connect('parent-set', () => {
this.msContent.style_changed();
this.updateMetaWindowVisibility();
});
this.connect('notify::visible', () => {
this.updateMetaWindowVisibility();
});
this.msContent = new MsWindowContent({
placeholder: this.placeholder,
clone: this.windowClone,
});
this.add_child(this.msContent);
this.setMsWorkspace(msWorkspace);
}
get state(): MsWindowState {
const metaWindow = this.metaWindow;
let matchingInfo: MsWindowMatchingInfo;
switch (this.lifecycleState.type) {
case 'app-placeholder':
matchingInfo = this.lifecycleState.matchingInfo;
break;
case 'window':
matchingInfo = {
appId: this.app.id,
title: this.lifecycleState.metaWindow?.title,
pid: this.lifecycleState.metaWindow?.get_pid(),
wmClass:
this.lifecycleState.metaWindow?.get_wm_class_instance(),
stableSeq:
this.lifecycleState.metaWindow?.get_stable_sequence(),
};
break;
default:
matchingInfo = {
appId: this.app.id,
title: undefined,
pid: undefined,
wmClass: undefined,
stableSeq: undefined,
};
}
return {
appId: this.app.id,
// For compatibility we save a meta window identifier string.
// This is useful if the user decides to downgrade material-shell to a previous version.
metaWindowIdentifier:
metaWindow !== null
? buildMetaWindowIdentifier(metaWindow)
: null,
matchingInfo: matchingInfo,
persistent: this._persistent,
x: this.x,
y: this.y,
width: this.width,
height: this.height,
};
}
get metaWindow(): MetaWindowWithMsProperties | null {
const state = this.lifecycleState;
if (state.type !== 'window') return null;
return (
state.metaWindow ||
(state.dialogs && state.dialogs.length > 0
? state.dialogs[state.dialogs.length - 1].metaWindow
: null)
);
}
/** All meta windows represented by this MSWindow.
*
* This may be more than one window if dialogs are present, or it may be no windows if no app is launched for example.
*/
get metaWindows(): MetaWindowWithMsProperties[] {
const state = this.lifecycleState;
if (state.type !== 'window') return [];
const windows = state.dialogs.map((d) => d.metaWindow);
if (state.metaWindow !== null) windows.push(state.metaWindow);
return windows;
}
/** A human-readable identifier for this window.
* This is not intended for anything other than debugging.
*/
get windowIdentifier(): string {
const metaWindow = this.metaWindow;
if (metaWindow !== null) {
return buildMetaWindowIdentifier(metaWindow);
} else {
return `${this.app.id}-${this.lifecycleState.type}`;
}
}
get title() {
if (!this.app) return '';
const metaWindow = this.metaWindow;
return metaWindow ? metaWindow.get_title() : this.app.get_name();
}
set persistent(boolean: boolean) {
this._persistent = boolean;
Me.stateManager.stateChanged();
}
delayGetMetaWindowActor(
metaWindow: MetaWindowWithMsProperties,
delayedCount: number,
resolve: (actor: Meta.WindowActor) => void,
reject: () => void
) {
if (delayedCount < 20) {
// If we don't have actor we hope to get it in the next loop
Async.addTimeout(GLib.PRIORITY_DEFAULT, 50, () => {
const actor =
metaWindow.get_compositor_private<Meta.WindowActor>();
if (actor && actor.get_texture()) {
resolve(actor);
} else {
this.delayGetMetaWindowActor(
metaWindow,
delayedCount++,
resolve,
reject
);
}
});
} else {
reject();
}
}
get dragged() {
return (
Me.msWindowManager.msDndManager.dragInProgress?.msWindow === this
);
}
get followMetaWindow() {
if (!this.msWorkspace) return false;
return (
(this.msWorkspace &&
this.msWorkspace.layout.state.key === 'float') ||
(this.metaWindow && this.metaWindow.fullscreen)
);
}
async onMetaWindowActorExist(
metaWindow: MetaWindowWithMsProperties
): Promise<Meta.WindowActor | void> {
return new Promise<Meta.WindowActor | void>((resolve, reject) => {
if (!metaWindow) {
return resolve();
}
const actor = metaWindow.get_compositor_private<Meta.WindowActor>();
if (actor && actor.get_texture()) {
resolve(actor);
} else {
this.delayGetMetaWindowActor(metaWindow, 0, resolve, reject);
}
});
}
async onMetaWindowFirstFrameDrawn(metaWindow: MetaWindowWithMsProperties) {
return new Promise<void>((resolve) => {
if (!metaWindow) {
return resolve();
}
if (metaWindow.firstFrameDrawn) {
resolve();
} else {
metaWindow
.get_compositor_private<Meta.WindowActor>()
.connect('first-frame', () => {
resolve();
});
}
});
}
override vfunc_allocate(
box: Clutter.ActorBox,
flags?: Clutter.AllocationFlags
) {
box.x1 = Math.round(box.x1);
box.y1 = Math.round(box.y1);
box.x2 = Math.round(box.x2);
box.y2 = Math.round(box.y2);
SetAllocation(this, box, flags);
const contentBox = Clutter.ActorBox.new(
0,
0,
box.get_width(),
box.get_height()
);
Allocate(this.msContent, contentBox, flags);
const workArea = Main.layoutManager.getWorkAreaForMonitor(
this.msWorkspace.monitor.index
);
const monitorInFullScreen = global.display.get_monitor_in_fullscreen(
this.msWorkspace.monitor.index
);
const offsetX = monitorInFullScreen
? this.msWorkspace.monitor.x
: workArea.x;
const offsetY = monitorInFullScreen
? this.msWorkspace.monitor.y
: workArea.y;
if (this.lifecycleState.type === 'window') {
// The dialogs are sorted because it affects their stacking order when displayed. We show the most recently interacted with window one on top.
[...this.lifecycleState.dialogs]
.sort(
(firstDialog, secondDialog) =>
firstDialog.metaWindow.user_time -
secondDialog.metaWindow.user_time
)
.forEach((dialog) => {
const dialogFrame = dialog.metaWindow.get_buffer_rect();
const x1 = dialogFrame.x - box.x1 - offsetX;
const x2 = x1 + dialogFrame.width;
const y1 = dialogFrame.y - box.y1 - offsetY;
const y2 = y1 + dialogFrame.height;
const dialogBox = Clutter.ActorBox.new(x1, y1, x2, y2);
Allocate(dialog.clone, dialogBox, flags);
});
}
}
// eslint-disable-next-line camelcase
override set_position(x: number, y: number) {
if (this.followMetaWindow) return;
super.set_position(x, y);
}
// eslint-disable-next-line camelcase
override set_size(width: number, height: number) {
if (this.followMetaWindow) return;
super.set_size(width, height);
}
getRelativeMetaWindowPosition(metaWindow: Meta.Window) {
if (this.dragged) {
const currentFrameRect = metaWindow.get_frame_rect();
return {
x: currentFrameRect.x,
y: currentFrameRect.y,
};
} else {
const workArea = Main.layoutManager.getWorkAreaForMonitor(
this.msWorkspace.monitor.index
);
return {
x: workArea.x + this.x,
y: workArea.y + this.y,
};
}
}
/*
* This function is called every time the position or the size of the actor change and is meant to update the metaWindow accordingly
*/
updateMetaWindowPositionAndSize() {
// This will call updateMetaWindowPositionAndSizeInternal immediately, or in a little while if it has been throttled
this.updateMetaWindowPositionAndSizeThrottled();
}
private updateMetaWindowPositionAndSizeInternal() {
const state = this.lifecycleState;
if (state.type !== 'window') return;
const metaWindow = state.metaWindow;
const windowActor =
metaWindow &&
metaWindow.get_compositor_private<MetaWindowActorWithMsProperties>();
if (
!windowActor ||
!this.mapped ||
this.width === 0 ||
this.height === 0 ||
!metaWindow.firstFrameDrawn ||
this.followMetaWindow ||
metaWindow.minimized
) {
return;
}
let shouldBeMaximizedHorizontally = metaWindow.maximized_horizontally;
let shouldBeMaximizedVertically = metaWindow.maximized_vertically;
// Check for maximized only if the msWindow is inside the tileableContainer
if (
this.get_parent() ===
this.msWorkspace.msWorkspaceActor.tileableContainer
) {
//Check if the actor position is corresponding of the maximized state (is equal of the size of the workArea)
shouldBeMaximizedHorizontally =
this.x === 0 &&
this.width ===
this.msWorkspace.msWorkspaceActor.tileableContainer.allocation.get_width();
shouldBeMaximizedVertically =
this.y === 0 &&
this.height ===
this.msWorkspace.msWorkspaceActor.tileableContainer.allocation.get_height();
}
const needToChangeMaximizeHorizontally =
shouldBeMaximizedHorizontally !== metaWindow.maximized_horizontally;
const needToChangeMaximizeVertically =
shouldBeMaximizedVertically !== metaWindow.maximized_vertically;
let needToMove = false;
let needToResize = false;
let needToMoveOrResize = false;
let moveTo: { x: number; y: number } | undefined = undefined;
let resizeTo: { width: number; height: number } | undefined = undefined;
// check if the window need a changes only if we don't need to already maximize
if (!shouldBeMaximizedHorizontally || !shouldBeMaximizedVertically) {
const currentFrameRect = metaWindow.get_frame_rect();
const contentBox = this.msContent.allocation;
if (metaWindow.allows_resize()) {
moveTo = this.getRelativeMetaWindowPosition(metaWindow);
resizeTo = {
width: this.width,
height: this.height,
};
} else {
const relativePosition =
this.getRelativeMetaWindowPosition(metaWindow);
moveTo = {
x:
relativePosition.x +
(contentBox.get_width() - currentFrameRect.width) / 2,
y:
relativePosition.y +
(contentBox.get_height() - currentFrameRect.height) / 2,
};
resizeTo = {
width: currentFrameRect.width,
height: currentFrameRect.height,
};
}
needToMove =
currentFrameRect.x !== moveTo.x ||
currentFrameRect.y !== moveTo.y;
needToResize =
currentFrameRect.width !== resizeTo.width ||
currentFrameRect.height !== resizeTo.height;
needToMoveOrResize = needToMove || needToResize;
}
// If there is no need to maximize, unmaximize, resize or move discard
if (
!needToChangeMaximizeHorizontally &&
!needToChangeMaximizeVertically &&
!needToMoveOrResize
) {
return;
}
if (
needToChangeMaximizeHorizontally ||
needToChangeMaximizeVertically
) {
const shouldMaximizeHorizontally =
shouldBeMaximizedHorizontally &&
!metaWindow.maximized_horizontally;
const shouldMaximizeVertically =
shouldBeMaximizedVertically && !metaWindow.maximized_vertically;
const shouldUnMaximizeHorizontally =
!shouldBeMaximizedHorizontally &&
metaWindow.maximized_horizontally;
const shouldUnMaximizeVertically =
!shouldBeMaximizedVertically && metaWindow.maximized_vertically;
const callback = () => {
if (
shouldUnMaximizeHorizontally &&
shouldUnMaximizeVertically
) {
metaWindow.unmaximize(Meta.MaximizeFlags.BOTH);
} else if (shouldUnMaximizeHorizontally) {
metaWindow.unmaximize(Meta.MaximizeFlags.HORIZONTAL);
} else if (shouldUnMaximizeVertically) {
metaWindow.unmaximize(Meta.MaximizeFlags.VERTICAL);
}
if (shouldMaximizeHorizontally && shouldMaximizeVertically) {
metaWindow.maximize(Meta.MaximizeFlags.BOTH);
} else if (shouldMaximizeHorizontally) {
metaWindow.maximize(Meta.MaximizeFlags.HORIZONTAL);
} else if (shouldMaximizeVertically) {
metaWindow.maximize(Meta.MaximizeFlags.VERTICAL);
}
};
if (isWayland) {
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
callback();
return GLib.SOURCE_REMOVE;
});
} else {
callback();
}
}
if (
needToMoveOrResize &&
moveTo !== undefined &&
resizeTo !== undefined
) {
// Secure the futur metaWindow Position to ensure it's not outside the current monitor
if (!this.dragged) {
moveTo.x = Math.max(
Math.min(
moveTo.x,
this.msWorkspace.monitor.x +
this.msWorkspace.monitor.width -
resizeTo.width
),
this.msWorkspace.monitor.x
);
moveTo.y = Math.max(
Math.min(
moveTo.y,
this.msWorkspace.monitor.y +
this.msWorkspace.monitor.height -
resizeTo.height
),
this.msWorkspace.monitor.y
);
}
//Set the size accordingly
if (isWayland) {
const moveTo2 = moveTo;
const resizeTo2 = resizeTo;
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
if (needToResize) {
metaWindow.move_resize_frame(
true,
moveTo2.x,
moveTo2.y,
resizeTo2.width,
resizeTo2.height
);
} else {
metaWindow.move_frame(true, moveTo2.x, moveTo2.y);
}
return GLib.SOURCE_REMOVE;
});
} else {
if (needToResize) {
metaWindow.move_resize_frame(
true,
moveTo.x,
moveTo.y,
resizeTo.width,
resizeTo.height
);
// Enforce window positioning since Gnome Terminal don't always move when requested
const moveTo2 = moveTo;
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
const currentFrameRect = metaWindow.get_frame_rect();
if (
currentFrameRect.x !== moveTo2.x ||
currentFrameRect.y !== moveTo2.y
) {
metaWindow.move_frame(true, moveTo2.x, moveTo2.y);
}
return GLib.SOURCE_REMOVE;
});
} else {
metaWindow.move_frame(true, moveTo.x, moveTo.y);
}
}
}
}
mimicMetaWindowPositionAndSize() {
const metaWindow = this.metaWindow;
if (!metaWindow || this.dragged) return;
const workArea = Main.layoutManager.getWorkAreaForMonitor(
metaWindow.get_monitor()
);
const currentFrameRect = metaWindow.get_frame_rect();
const newPosition = {
x:
currentFrameRect.x -
(metaWindow.fullscreen
? this.msWorkspace.monitor.x
: workArea.x) -
this.msContent.x,
y:
currentFrameRect.y -
(metaWindow.fullscreen
? this.msWorkspace.monitor.y
: workArea.y) -
this.msContent.y,
};
const newSize = {
width: currentFrameRect.width + this.msContent.x * 2,
height: currentFrameRect.height + this.msContent.y * 2,
};
super.set_position(newPosition.x, newPosition.y);
super.set_size(newSize.width, newSize.height);
}
resizeDialogs() {
if (this.lifecycleState.type !== 'window') return;
this.lifecycleState.dialogs.forEach((dialog) => {
const { metaWindow } = dialog;
const frame = metaWindow.get_frame_rect();
const workArea = Main.layoutManager.getWorkAreaForMonitor(
this.msWorkspace.monitor.index
);
const monitorInFullScreen =
global.display.get_monitor_in_fullscreen(
this.msWorkspace.monitor.index
);
const offsetX = monitorInFullScreen
? this.msWorkspace.monitor.x
: workArea.x;
const offsetY = monitorInFullScreen
? this.msWorkspace.monitor.y
: workArea.y;
const needMove =
frame.x - offsetX < this.x ||
frame.x - offsetX + frame.width > this.x + this.width ||
frame.y - offsetY < this.y ||
frame.y - offsetY + frame.height > this.y + this.height;
const needResize =
frame.width > this.width || frame.height > this.height;
if (needResize && metaWindow.resizeable) {
const minWidth = Math.min(frame.width, this.width);
const minHeight = Math.min(frame.height, this.height);
metaWindow.move_resize_frame(
true,
needMove
? offsetX + this.x + (this.width - minWidth) / 2
: frame.x,
needMove
? offsetY + this.y + (this.height - minHeight) / 2
: frame.y,
minWidth,
minHeight
);
} else if (needMove && metaWindow.allows_move()) {
metaWindow.move_frame(
true,
offsetX + this.x + (this.width - frame.width) / 2,
offsetY + this.y + (this.height - frame.height) / 2
);
}
});
}
resizeMetaWindows() {
if (
this.lifecycleState.type == 'window' &&
this.lifecycleState.metaWindow !== null
) {
this.followMetaWindow
? this.mimicMetaWindowPositionAndSize()
: this.updateMetaWindowPositionAndSize();
}
this.resizeDialogs();
}
registerOnMetaWindowSignals(
metaWindow: MetaWindowWithMsProperties
): number[] {
return [
metaWindow.connect('notify::title', (_) => {
this.emit('title-changed', this.title);
}),
metaWindow.connect('position-changed', () => {
if (this.followMetaWindow) {
this.mimicMetaWindowPositionAndSize();
}
}),
metaWindow.connect('size-changed', () => {
if (this.followMetaWindow) {
this.mimicMetaWindowPositionAndSize();
}
}),
metaWindow.connect('notify::fullscreen', () => {
if (this.followMetaWindow) {
this.mimicMetaWindowPositionAndSize();
}
}),
];
}
unregisterOnMetaWindowSignals() {
const state = this.lifecycleState;
if (state.type !== 'window' || state.metaWindow === null) return;
for (const signalId of state.metaWindowSignals) {
state.metaWindow.disconnect(signalId);
}
state.metaWindowSignals = [];
}
setMsWorkspace(msWorkspace: MsWorkspace) {
this.msWorkspace = msWorkspace;
if (this.lifecycleState.type === 'window') {
[
...this.lifecycleState.dialogs.map(
(dialog) => dialog.metaWindow
),
this.lifecycleState.metaWindow,
].forEach((metaWindow) => {
if (metaWindow) {
WindowUtils.updateTitleBarVisibility(metaWindow);
this.updateWorkspaceAndMonitor(metaWindow);
}
});
this.resizeMetaWindows();
}
}
async setWindow(metaWindow: MetaWindowWithMsProperties): Promise<void> {
assert(
this.lifecycleState.type === 'app-placeholder',
'Can only set the window if the MsWindow is in the app-placeholder state.'
);
this.lifecycleState = {
type: 'window',
metaWindow: metaWindow,
metaWindowSignals: this.registerOnMetaWindowSignals(metaWindow),
dialogs: [],
matchingInfo: this.lifecycleState.matchingInfo,
matchedAtTime: new Date(),
};
metaWindow.msWindow = this;
await this.onMetaWindowActorExist(metaWindow);
await this.onMetaWindowFirstFrameDrawn(metaWindow);
this.updateWorkspaceAndMonitor(metaWindow);
this.windowClone.set_source(
metaWindow.get_compositor_private<Meta.WindowActor>()
);
await this.onMetaWindowsChanged();
}
public unsetWindow() {
assert(
this.lifecycleState.type === 'window',
'Can only unset the window when in the window state'
);
this.unregisterOnMetaWindowSignals();
// Required when re-assigning windows.
// Normally if a window is destroyed the source is implicitly cleared because the source window doesn't exist anymore.
this.windowClone.set_source(null);
this.reactive = true;
this.lifecycleState = {
type: 'app-placeholder',
matchingInfo: this.lifecycleState.matchingInfo,
waitingForAppSince: undefined,
};
this.onMetaWindowsChanged().catch(logAsyncException);
}
updateWorkspaceAndMonitor(metaWindow: Meta.Window) {
if (metaWindow && this.msWorkspace) {
// We need to move the window before changing the workspace, because
// the move itself could cause a workspace change if the window enters
// the primary monitor
if (metaWindow.get_monitor() != this.msWorkspace.monitor.index) {
metaWindow.move_to_monitor(this.msWorkspace.monitor.index);
}
const workspace = Me.msWorkspaceManager.getWorkspaceOfMsWorkspace(
this.msWorkspace
);
if (workspace && metaWindow.get_workspace() != workspace) {
metaWindow.change_workspace(workspace);
}
}
}
addDialog(metaWindow: MetaWindowWithMsProperties): void {
if (this.lifecycleState.type === 'app-placeholder') {
this.lifecycleState = {
type: 'window',
metaWindow: null,
metaWindowSignals: [],
dialogs: [],
matchingInfo: this.lifecycleState.matchingInfo,
matchedAtTime: new Date(),
};
}
if (this.lifecycleState.type !== 'window') {
throw new Error(
`Cannot add dialog to an MsWindow in the ${this.lifecycleState.type} state`
);
}
this.updateWorkspaceAndMonitor(metaWindow);
const clone = new Clutter.Clone({
source: metaWindow.get_compositor_private<Meta.WindowActor>(),
});
const dialog = {
metaWindow,
clone,
};
metaWindow.msWindow = this;
this.lifecycleState.dialogs.push(dialog);
this.add_child(clone);
this.resizeDialogs();
this.onMetaWindowsChanged();
if (this.msWorkspace.tileableFocused === this) {
this.grab_key_focus();
}
}
removeAllDialogs() {
if (this.lifecycleState.type === 'window') {
const d = [...this.lifecycleState.dialogs];
for (const dialog of d) {
this.removeDialog(dialog.metaWindow);
}
}
}
removeDialog(metaWindow: MetaWindowWithMsProperties) {
if (this.lifecycleState.type !== 'window') {
throw new Error('Can only remove dialogs when in the window state');
}
const idx = this.lifecycleState.dialogs.findIndex(
(x) => x.metaWindow == metaWindow
);
if (idx === -1) {
throw new Error('Dialog is not added to window');
}
const dialog = this.lifecycleState.dialogs[idx];
this.lifecycleState.dialogs.splice(idx, 1);
this.remove_child(dialog.clone);
dialog.clone.destroy();
metaWindow.msWindow = undefined;
}
async onMetaWindowsChanged(): Promise<void> {
if (this.lifecycleState.type == 'window') {
this.reactive = false;
const metaWindow = assertNotNull(this.metaWindow);
await this.onMetaWindowActorExist(metaWindow);
await this.onMetaWindowFirstFrameDrawn(metaWindow);
WindowUtils.updateTitleBarVisibility(metaWindow);
this.resizeMetaWindows();
set_style_class(
this.msContent,
'surface-darker',
this.lifecycleState.metaWindow === null
);
if (this.placeholder.get_parent()) {
this.fadeOutPlaceholder();
}
} else {
this.reactive = false;
set_style_class(this.msContent, 'surface-darker', false);
if (!this.placeholder.get_parent()) {
this.msContent.add_child(this.placeholder);
}
}
this.emit('title-changed', this.title);
}
grab_key_focus(): void {
// TODO: Seems a bit redundant to first focus the dialogs and then change focus to the main window (is that even desired?)
this.focusDialogs();
if (!Me.msWindowManager.msFocusManager.requestFocus(this)) return;
if (this.metaWindow) {
this.metaWindow.activate(global.get_current_time());
} else {
this.placeholder.grab_key_focus();
}
}
/**
* Set focus to the most recent dialog but ONLY if they are of type Meta.WindowType.DIALOG or Meta.WindowType.MODAL_DIALOG. Other dialogs are not necessarily in front of the main window and do not necessarily require the users attention.
*/
focusDialogs(): boolean {
let focused = false;
if (
this.lifecycleState.type === 'window' &&
this.lifecycleState.dialogs
) {
[
...this.lifecycleState.dialogs.filter((dialog) =>
// Filter out Meta.WindowType.UTILITY Windows
[
Meta.WindowType.DIALOG,
Meta.WindowType.MODAL_DIALOG,
].includes(dialog.metaWindow.window_type)
),
]
.sort((firstDialog, secondDialog) => {
return (
firstDialog.metaWindow.user_time -
secondDialog.metaWindow.user_time
);
})
.forEach((dialog, index, array) => {
this.set_child_above_sibling(dialog.clone, null);
if (index === array.length - 1) {
dialog.metaWindow.activate(global.get_current_time());
focused = true;
}
});
}
return focused;
}
/**
* When a MetaWindow associated to this MsWindow is unManaged we remove it from the dialogs if it's a dialog or the MainMetaWindow then we kill the MsWindow only if it was the last one.
* @param {MetaWindow} metaWindow the MetaWindow currently unManaged
*/
metaWindowUnManaged(metaWindow: MetaWindowWithMsProperties): void {
const state = this.lifecycleState;
assert(
state.type == 'window',
"Expected the MsWindow to be in the 'window' state"
);
const isMainMetaWindow = metaWindow === state.metaWindow;
const dialog = state.dialogs.some(
(dialog) => dialog.metaWindow === metaWindow
);
// If it's neither the MainMetaWindow or a Dialog we ignore, but this shouldn't happen
if (!isMainMetaWindow && !dialog) {
Me.log('Cannot find the window which was unmanaged');
return;
}
if (dialog) {
this.removeDialog(metaWindow);
}
if (isMainMetaWindow) {
state.metaWindow = null;
}
// Not really important since the window is getting destroyed anyway, but here we clean up our association with the meta window.
metaWindow.msWindow = undefined;
metaWindow.handledByMaterialShell = false;
if (state.metaWindow == null && state.dialogs.length == 0) {
if (this._persistent) {
this.unsetWindow();
} else {
this.lifecycleState = { type: 'waiting-for-destroy' };
// We check in an idle that closing dialog didn't pop up a new window. If there is no new window we kill the msWindow
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
if (this.lifecycleState.type === 'waiting-for-destroy') {
this.kill();
}
return GLib.SOURCE_REMOVE;
});
}
}
}
async kill() {
const state = this.lifecycleState;
switch (state.type) {
case 'window': {
const dialogPromises = state.dialogs.map((dialog) => {
return new Promise<void>((resolve) => {
// TODO: When can this return false?
if (
dialog.metaWindow.get_compositor_private<Meta.WindowActor>()
) {
dialog.metaWindow.connect('unmanaged', (_) => {
resolve();
});
dialog.metaWindow.delete(global.get_current_time());
} else {
resolve();
}
});
});
const promise = new Promise<void>((resolve) => {
if (
state.metaWindow &&
state.metaWindow.get_compositor_private<Meta.WindowActor>()
) {
state.metaWindow.connect('unmanaged', (_) => {
resolve();
});
state.metaWindow.delete(global.get_current_time());
} else {
resolve();
}
});
await Promise.all([...dialogPromises, promise]);
// The above code will call metaWindowUnManaged for all meta windows managed by this MsWindow which will handle all necessary cleanup.
// Note that just because we call `delete` doesn't mean the windows will actually close. For example, some applications
// show 'Do you want to save this document' dialogs which allow the user to cancel closing the window.
break;
}
case 'app-placeholder': {
if (this._persistent) {
// Persistent app placeholders cannot be closed
} else {
// Note: This is here and not in _onDestroy because _onDestroy can sometimes be called when the workspace
// has already been destroyed. TODO: This should be done in a better way.
this.msWorkspace.removeMsWindow(this);
this.destroy();
}
break;
}
case 'waiting-for-destroy':
this.msWorkspace.removeMsWindow(this);
this.destroy();
break;
case 'destroyed':
break;
}
}
fadeOutPlaceholder() {
const onComplete = () => {
this.placeholder.set_opacity(255);
if (this.metaWindow) {
this.msContent.remove_child(this.placeholder);
}
this.placeholder.reset();
};
this.placeholder.ease({
opacity: 0,
duration: 250,
mode: Clutter.AnimationMode.EASE_OUT_CUBIC,
onComplete,
});
}
freezeAllocation() {
this.set_width(this.allocation.get_width());
this.set_height(this.allocation.get_height());
}
unFreezeAllocation() {
this.set_width(-1);
this.set_height(-1);
}
updateMetaWindowVisibility() {
const metaWindow = this.metaWindow;
if (metaWindow) {
const shouldBeHidden =
!this.visible ||
this.get_parent() === null ||
Me.msWindowManager.msDndManager.dragInProgress;
if (shouldBeHidden && !metaWindow.minimized) {
metaWindow.minimize();
} else if (!shouldBeHidden && metaWindow.minimized) {
metaWindow.unminimize();
}
}
}
toString() {
// When MS function parameter logging is enabled, toString may be called on windows that have been destroyed.
// So we need to guard against this. super.toString would otherwise try to access the destroyed C object.
if (this.lifecycleState.type === 'destroyed') {
return `[destroyed MsWindow - ${this.app.get_name()}]`;
}
const string = super.toString();
return `${string.slice(0, string.length - 1)} ${this.app.get_name()}]`;
}
_onDestroy() {
if (this.destroyId) this.disconnect(this.destroyId);
this.unregisterOnMetaWindowSignals();
this.lifecycleState = { type: 'destroyed' };
}
}
@registerGObjectClass
export class MsWindowContent extends St.Widget {
placeholder: Clutter.Actor;
clone: Clutter.Clone;
static metaInfo: GObject.MetaInfo = {
GTypeName: 'MsWindowContent',
};
constructor({
placeholder,
clone,
}: {
placeholder: Clutter.Actor;
clone: Clutter.Clone;
}) {
super({ clip_to_allocation: true });
this.placeholder = placeholder;
this.clone = clone;
this.add_child(this.clone);
this.add_child(this.placeholder);
}
override vfunc_allocate(
box: Clutter.ActorBox,
flags?: Clutter.AllocationFlags
) {
SetAllocation(this, box, flags);
const themeNode = this.get_theme_node();
box = themeNode.get_content_box(box);
const parent = this.get_parent();
assert(parent instanceof MsWindow, 'expected parent to be an MsWindow');
const metaWindow = parent.metaWindow;
if (metaWindow && metaWindow.firstFrameDrawn) {
const windowFrameRect = metaWindow.get_frame_rect();
const windowBufferRect = metaWindow.get_buffer_rect();
//The WindowActor position are not the same as the real window position, I'm not sure why. We need to determine the offset to correctly position the windowClone inside the msWindow container;
if (metaWindow.get_compositor_private<Meta.WindowActor>()) {
let x1: number, x2: number, y1: number, y2: number;
if (metaWindow.resizeable || metaWindow.fullscreen) {
x1 = windowBufferRect.x - windowFrameRect.x;
y1 = windowBufferRect.y - windowFrameRect.y;
x2 = x1 + windowBufferRect.width;
y2 = y1 + windowBufferRect.height;
} else {
const monitor = parent.msWorkspace.monitor;
const workArea = Main.layoutManager.getWorkAreaForMonitor(
monitor.index
);
x1 = windowBufferRect.x - workArea.x - parent.x;
y1 = windowBufferRect.y - workArea.y - parent.y;
x2 = x1 + windowBufferRect.width;
y2 = y1 + windowBufferRect.height;
}
const cloneBox = Clutter.ActorBox.new(x1, y1, x2, y2);
Allocate(this.clone, cloneBox, flags);
} else {
AllocatePreferredSize(this.clone, flags);
}
} else {
AllocatePreferredSize(this.clone, flags);
}
if (this.placeholder.get_parent() === this) {
Allocate(this.placeholder, box, flags);
}
}
} | the_stack |
import { Trans, t } from "@lingui/macro";
import { withI18n } from "@lingui/react";
import PropTypes from "prop-types";
import * as React from "react";
import SchemaForm from "react-jsonschema-form";
import { MountService } from "foundation-ui";
import { InfoBoxInline } from "@dcos/ui-kit";
import TabButton from "#SRC/js/components/TabButton";
import TabButtonList from "#SRC/js/components/TabButtonList";
import Tabs from "#SRC/js/components/Tabs";
import Util from "#SRC/js/utils/Util";
import ErrorsAlert from "#SRC/js/components/ErrorsAlert";
import FluidGeminiScrollbar from "#SRC/js/components/FluidGeminiScrollbar";
import JSONEditorLoading from "#SRC/js/components/JSONEditorLoading";
import PageHeaderNavigationDropdown from "#SRC/js/components/PageHeaderNavigationDropdown";
import UniversePackage from "#SRC/js/structs/UniversePackage";
import SchemaField from "#SRC/js/components/SchemaField";
import SplitPanel, {
PrimaryPanel,
SidePanel,
} from "#SRC/js/components/SplitPanel";
import StringUtil from "#SRC/js/utils/StringUtil";
import PlacementConstraintsSchemaField from "#SRC/js/components/PlacementConstraintsSchemaField";
import FrameworkConfigurationConstants from "#SRC/js/constants/FrameworkConfigurationConstants";
const JSONEditor = React.lazy(
() =>
import(/* webpackChunkName: "jsoneditor" */ "#SRC/js/components/JSONEditor")
);
const YamlEditorSchemaField = React.lazy(
() =>
import(
/* webpackChunkName: "yamleditorschemafield" */ "#SRC/js/components/YamlEditorSchemaField"
)
);
const YamlEditorSchemaFieldWrapper = (props) => (
<React.Suspense fallback={<JSONEditorLoading />}>
<YamlEditorSchemaField {...props} />
</React.Suspense>
);
MountService.MountService.registerComponent(
PlacementConstraintsSchemaField,
"SchemaField:application/x-region-zone-constraints+json"
);
MountService.MountService.registerComponent(
PlacementConstraintsSchemaField,
"SchemaField:application/x-zone-constraints+json"
);
MountService.MountService.registerComponent(
YamlEditorSchemaFieldWrapper,
"SchemaField:application/x-yaml"
);
class FrameworkConfigurationForm extends React.Component {
static defaultProps = {
deployErrors: null,
submitRef: () => {},
liveValidate: false,
};
static propTypes = {
packageDetails: PropTypes.instanceOf(UniversePackage).isRequired,
jsonEditorActive: PropTypes.bool.isRequired,
formData: PropTypes.object.isRequired,
formErrors: PropTypes.object.isRequired,
focusField: PropTypes.string.isRequired,
activeTab: PropTypes.string.isRequired,
onFormDataChange: PropTypes.func.isRequired,
onFormErrorChange: PropTypes.func.isRequired,
onFormSubmit: PropTypes.func.isRequired,
handleActiveTabChange: PropTypes.func.isRequired,
handleFocusFieldChange: PropTypes.func.isRequired,
defaultConfigWarning: PropTypes.string,
// Will be populated with a reference to the form submit button in order
// to enable the form to be controlled externally
//
// See https://github.com/mozilla-services/react-jsonschema-form#tips-and-tricks
submitRef: PropTypes.func,
liveValidate: PropTypes.bool,
};
state = { errorSchema: null };
handleBadgeClick = (activeTab, event) => {
event.stopPropagation();
const { errorSchema } = this.state;
const { formData, handleFocusFieldChange } = this.props;
const fieldsWithErrors = Object.keys(errorSchema[activeTab]).filter(
(field) =>
errorSchema[activeTab][field].__errors &&
errorSchema[activeTab][field].__errors.length > 0
);
// first field with errors in the current tab
const fieldToFocus = Object.keys(formData[activeTab]).find((field) =>
fieldsWithErrors.includes(field)
);
handleFocusFieldChange(activeTab, fieldToFocus);
};
getFormTabList() {
const { formErrors, packageDetails } = this.props;
const schema = packageDetails.getConfig();
// the config will have 2-levels, we will render first level as the tabs
return Object.keys(schema.properties).map((tabName) => {
const issueCount = formErrors[tabName];
return (
<TabButton
label={StringUtil.capitalizeEveryWord(tabName)}
labelClassName={"padded-right"}
id={tabName}
key={tabName}
showErrorBadge={issueCount > 0}
count={issueCount}
description={
<Trans render="span">{issueCount} issues need addressing</Trans>
}
onClickBadge={this.handleBadgeClick.bind(this, tabName)}
/>
);
});
}
handleTabChange = (activeTab) => {
this.props.handleActiveTabChange(activeTab);
};
handleDropdownNavigationSelection = (item) => {
this.props.handleActiveTabChange(item.id);
};
getDropdownNavigationList() {
const { packageDetails, activeTab } = this.props;
const schema = packageDetails.getConfig();
return Object.keys(schema.properties).map((tabName) => ({
id: tabName,
isActive: activeTab === tabName,
label: tabName,
}));
}
getUiSchema() {
const { formData, focusField, activeTab } = this.props;
const uiSchema = {
[activeTab]: {
[focusField]: { "ui:autofocus": true },
},
};
// hide all tabs not selected
Object.keys(formData).forEach((tabName) => {
if (tabName !== activeTab) {
if (uiSchema[tabName] == null) {
uiSchema[tabName] = {};
}
uiSchema[tabName].classNames = "hidden";
}
});
return uiSchema;
}
handleJSONChange = (formData) => {
this.props.onFormDataChange(formData);
};
writeErrors(formData, schema, isRequired, errors) {
if (schema == null) {
return;
}
if (Util.isObject(formData) && schema.properties) {
Object.keys(formData).forEach((property) => {
this.writeErrors(
formData[property],
schema.properties[property],
schema.required && schema.required.includes(property),
errors[property]
);
});
return;
}
if (isRequired && formData === "") {
errors.addError(
schema.default
? `Expecting a ${schema.type} here, eg: ${schema.default}`
: `Expecting a ${schema.type} here`
);
}
}
getTotalErrorsForLevel(errorSchemaLevel) {
if (!errorSchemaLevel.__errors) {
return 0;
}
// only show one error per field in badge count
const currentLevelErrors = errorSchemaLevel.__errors.length > 0 ? 1 : 0;
return Object.keys(errorSchemaLevel)
.map((key) => this.getTotalErrorsForLevel(errorSchemaLevel[key]))
.reduce((a, b) => a + b, currentLevelErrors);
}
handleFormChange = (form) => {
const { formData } = form;
this.props.onFormDataChange(formData);
if (this.props.liveValidate) {
// When liveValidate is true, errorSchema is available for each change
this.probeErrorsSchemaForm();
}
};
handleFormError = () => {
this.probeErrorsSchemaForm();
};
onEditorResize = (newSize) => {
this.setState({ editorWidth: newSize });
};
probeErrorsSchemaForm() {
const { errorSchema } = this.schemaForm.state;
if (errorSchema) {
const formErrors = {};
Object.keys(errorSchema).forEach((tab) => {
formErrors[tab] = this.getTotalErrorsForLevel(errorSchema[tab]);
});
this.setState({ errorSchema }, () => {
this.props.onFormErrorChange(formErrors);
});
}
}
validate = (formData, errors) => {
const { packageDetails } = this.props;
this.writeErrors(formData, packageDetails.getConfig(), false, errors);
return errors;
};
formatErrorForJSON(errorSchema, path) {
if (!errorSchema.__errors) {
return [];
}
const currentLevelErrors = errorSchema.__errors.map((message) => ({
message,
path,
}));
return Object.keys(errorSchema)
.map((key) => this.formatErrorForJSON(errorSchema[key], path.concat(key)))
.reduce((a, b) => a.concat(b), currentLevelErrors);
}
getErrorsForJSONEditor() {
const { errorSchema } = this.state;
if (!errorSchema) {
return [];
}
return this.formatErrorForJSON(errorSchema, []);
}
transformErrors(errorSchema) {
// Filter "type" errors as they're caught by the validate() function and
// capitalize error messages
return errorSchema
.filter(({ name }) => name !== "type")
.map(({ message, ...rest }) => ({
message: StringUtil.capitalize(message),
...rest,
}));
}
jsonSchemaErrorList = (props) => {
return (
<ErrorsAlert
errors={props.errors.map((error) => ({
message: error.stack,
}))}
/>
);
};
render() {
const {
packageDetails,
jsonEditorActive,
formData,
activeTab,
defaultConfigWarning,
onFormSubmit,
liveValidate,
submitRef,
i18n,
} = this.props;
const TitleField = (props) => {
const level = props.formContext.level;
if (level === FrameworkConfigurationConstants.headingLevel.H1) {
return (
<h1 className="flush-top short-bottom">
{StringUtil.capitalizeEveryWord(props.title)}
</h1>
);
}
if (level === FrameworkConfigurationConstants.headingLevel.H2) {
return (
<h2 className="short-bottom">
{StringUtil.capitalizeEveryWord(props.title)}
</h2>
);
}
return (
<h3 className="short-bottom">
{StringUtil.capitalizeEveryWord(props.title)}
</h3>
);
};
const schema = packageDetails.getConfig();
let defaultConfigWarningMessage = null;
if (defaultConfigWarning) {
defaultConfigWarningMessage = (
<div className="infoBoxWrapper">
<InfoBoxInline
appearance="warning"
message={
<div>
<strong>{i18n._(t`Warning`)}: </strong>
<Trans id={defaultConfigWarning} render="span" />
</div>
}
/>
</div>
);
}
return (
<SplitPanel onResize={this.onEditorResize}>
<PrimaryPanel className="create-service-modal-form__scrollbar-container modal-body-offset gm-scrollbar-container-flex">
<PageHeaderNavigationDropdown
handleNavigationItemSelection={
this.handleDropdownNavigationSelection
}
items={this.getDropdownNavigationList()}
/>
<FluidGeminiScrollbar>
<div className="modal-body-padding-surrogate create-service-modal-form-container">
<div className="framework-configuration-form create-service-modal-form container">
<Tabs
activeTab={activeTab}
handleTabChange={this.handleTabChange}
vertical={true}
className={"menu-tabbed-container-fixed"}
>
<TabButtonList>{this.getFormTabList()}</TabButtonList>
<div className="menu-tabbed-view-container">
{defaultConfigWarningMessage}
<SchemaForm
schema={schema}
formData={formData}
onChange={this.handleFormChange}
onSubmit={onFormSubmit}
onError={this.handleFormError}
uiSchema={this.getUiSchema()}
fields={{ SchemaField, TitleField }}
liveValidate={liveValidate}
validate={this.validate}
ErrorList={this.jsonSchemaErrorList}
transformErrors={this.transformErrors}
noHtml5Validate={true}
ref={(form) => {
this.schemaForm = form;
}}
>
<button ref={submitRef} className="hidden" />
</SchemaForm>
</div>
</Tabs>
</div>
</div>
</FluidGeminiScrollbar>
</PrimaryPanel>
<SidePanel isActive={jsonEditorActive} className="jsonEditorWrapper">
<React.Suspense fallback={<JSONEditorLoading isSidePanel={true} />}>
<JSONEditor
errors={this.getErrorsForJSONEditor()}
showGutter={true}
showPrintMargin={false}
onChange={this.handleJSONChange}
theme="monokai"
height="100%"
value={formData}
width={
this.state.editorWidth ? `${this.state.editorWidth}px` : "100%"
}
/>
</React.Suspense>
</SidePanel>
</SplitPanel>
);
}
}
export default withI18n()(FrameworkConfigurationForm);
export function unwrapped() {
return FrameworkConfigurationForm;
} | the_stack |
import { CompressionTypes } from 'kafkajs';
interface messageValue {
topic: string,
messages: object[],
}
// Fail Fast Strategy
export class FailFastError extends Error {
message: any;
reference: any;
name: any;
retryCount: number;
strategy: string;
originalError: any;
constructor(e: any) {
super(e);
Error.captureStackTrace(this, this.constructor);
this.strategy = 'Fail Fast';
this.reference = `This error was executed as part of the kafka-penguin Fail Fast message reprocessing strategy. Your producer attempted to deliver a message ${e.retryCount + 1} times but was unsuccessful. As a result, the producer successfully executed a disconnect operation. Refer to the original error for further information`;
this.name = e.name;
this.message = e.message;
this.originalError = e.originalError;
this.retryCount = e.retryCount;
}
}
export class FailFast {
retry: number;
client: any;
innerProducer: any;
constructor(num: number, kafkaJSClient: any) {
this.retry = num;
this.client = kafkaJSClient;
this.innerProducer = null;
}
producer() {
const options = {
retry:
{ retries: this.retry },
};
// Create a producer from client passing in retry options
// Save to FailFast class
this.innerProducer = this.client.producer(options);
// Return curr FailFast instance instead of a producer
return this;
}
connect() {
return this.innerProducer.connect();
}
disconnect() {
return this.innerProducer.disconnect();
}
send(message: messageValue) {
return this.innerProducer.send(message)
.catch((e: any) => {
this.innerProducer.disconnect();
const newError = new FailFastError(e);
// eslint-disable-next-line no-console
console.log(newError);
});
}
}
// Dead Letter Queue
export class DeadLetterQueueErrorConsumer extends Error {
message: any;
reference: any;
name: any;
retryCount: number;
strategy: string;
originalError: any;
constructor(e: any) {
super(e);
Error.captureStackTrace(this, this.constructor);
this.strategy = 'Dead Letter Queue';
this.reference = `This error was executed as part of the kafka-penguin Dead Letter Queue message reprocessing strategy. Your consumer attempted to receive a message ${e.retryCount + 1} times but was unsuccessful. As a result, the message was sent to a Dead Letter Queue. Refer to the original error for further information`;
this.name = `${e.name}(Consumer Side)`;
this.message = e.message;
this.originalError = e.originalError;
this.retryCount = e.retryCount;
}
}
export class DeadLetterQueueErrorProducer extends Error {
message: any;
reference: any;
name: any;
retryCount: number;
strategy: string;
originalError: any;
constructor(e: any) {
super(e);
Error.captureStackTrace(this, this.constructor);
this.strategy = 'Dead Letter Queue';
this.reference = `This error was executed as part of the kafka-penguin Dead Letter Queue message reprocessing strategy. Your producer attempted to deliver a message ${e.retryCount + 1} times but was unsuccessful. As a result, the message was sent to a Dead Letter Queue. Refer to the original error for further information`;
this.name = `${e.name}(Producer Side)`;
this.message = e.message;
this.originalError = e.originalError;
this.retryCount = e.retryCount;
}
}
interface consumerRunInput {
eachMessage: ({
topic,
partitions,
message,
}: {
topic: string,
partitions: number,
message: any
}) => void,
eachBatchAutoResolve: boolean,
}
interface consumerSubscribeInput {
groupId?: String,
partitionAssigners?: any,
sessionTimeout?: Number,
rebalanceTimeout?: Number,
heartbeatInterval?: Number,
metadataMaxAge?: Number,
allowAutoTopicCreation?: Boolean,
maxBytesPerPartition?: Number,
minBytes?: Number,
maxBytes?: Number,
maxWaitTimeInMs?: Number,
retry?: Object,
maxInFlightRequests?: Number,
rackId?: String
}
interface input {
eachMessage: ({
topic,
partitions,
message,
}: {
topic: string,
partitions: number,
message: any
}) => void
}
export class DeadLetterQueue {
client: any;
topic: string;
callback?: (message: any) => boolean;
innerConsumer: any;
admin: any;
innerProducer: any;
constructor(client: any, topic: string, callback?: any) {
this.topic = topic;
this.client = client;
this.callback = callback;
this.admin = this.client.admin();
this.innerConsumer = null;
this.innerProducer = this.client.producer();
}
producer() {
// Reference the DLQ instance for closure in the returned object
const dlqInstance = this;
const { innerProducer } = dlqInstance;
// Return an object with all Producer methods adapted to execute a dead letter queue strategy
console.log('INNER PRODUCER', innerProducer);
return {
...innerProducer,
connect() {
return innerProducer.connect()
.then(() => {
dlqInstance.createDLQ();
})
.catch((e: Error) => console.log(e));
},
send(message: messageValue) {
return innerProducer.connect()
.then(() => {
innerProducer.send({
...message,
topic: message.topic,
messages: message.messages,
})
// Upon error, reroute message to DLQ for the strategy topic
.catch((e?: any) => {
innerProducer.send({
messages: message.messages,
topic: `${dlqInstance.topic}.deadLetterQueue`,
})
.then(innerProducer.disconnect())
.catch((e: Error) => console.log(e));
// Print the error to the console
const newError = new DeadLetterQueueErrorProducer(e);
console.log(newError);
});
});
},
};
}
consumer(groupId: { groupId: string }) {
this.innerConsumer = this.client.consumer(groupId);
const dlqInstance = this;
const { innerConsumer, innerProducer } = dlqInstance;
// Returns an object with all Consumer methods adapter to execute a dead letter queue strategy
return {
...innerConsumer,
connect() {
return innerConsumer.connect().then(() => {
dlqInstance.createDLQ();
});
},
subscribe(input?: consumerSubscribeInput) {
return innerConsumer.subscribe({
...input,
topic: dlqInstance.topic,
fromBeginning: false,
});
},
run(input: consumerRunInput) {
const { eachMessage } = input;
return innerConsumer.run({
...input,
eachMessage: ({ topic, partitions, message }: {
topic: string, partitions: number, message: any
}) => {
try {
// If user doesn't pass in callback, DLQ simply listens and returns errors
if (dlqInstance.callback) {
if (!dlqInstance.callback(message)) throw Error;
eachMessage({ topic, partitions, message });
}
} catch (e) {
const newError = new DeadLetterQueueErrorConsumer(e);
console.error(newError);
innerProducer.connect()
.then(() => console.log('kafka-penguin: Connected to DLQ topic'))
.then(() => {
innerProducer.send({
topic: `${dlqInstance.topic}.deadLetterQueue`,
messages: [message],
});
})
.then(() => console.log('kafka-penguin: Message published to DLQ'))
.then(() => innerProducer.disconnect())
.then(() => console.log('kafka-penguin: Producer disconnected'))
.catch((e: any) => console.log('Error with producing to DLQ: ', e));
}
},
});
},
};
}
// Creates a new DLQ topic with the original topic name
async createDLQ() {
const adminCreateDLQ = await this.admin.connect()
.then(async () => {
await this.admin.createTopics({
topics: [{
topic: `${this.topic}.deadLetterQueue`,
numPartitions: 1,
replicationFactor: 1,
replicaAssignment: [{ partition: 0, replicas: [0, 1, 2] }],
}],
});
})
.then(() => this.admin.disconnect())
.catch((err: any) => console.log('Error from createDLQ', err));
return adminCreateDLQ;
}
}
// Ignore
export class IgnoreErrorProducer extends Error {
message: any;
reference: any;
name: any;
retryCount: number;
strategy: string;
originalError: any;
constructor(e: any) {
super(e);
Error.captureStackTrace(this, this.constructor);
this.strategy = 'Ignore';
this.reference = `This error was executed as part of the kafka-penguin Ignore message reprocessing strategy. Your producer attempted to deliver a message ${e.retryCount + 1} times but was unsuccessful.`;
this.name = `${e.name} (Producer Side)`;
this.message = e.message;
this.originalError = e.originalError;
this.retryCount = e.retryCount;
}
}
export class IgnoreErrorConsumer extends Error {
message: any;
reference: any;
name: any;
retryCount: number;
strategy: string;
originalError: any;
constructor(e: any) {
super(e);
Error.captureStackTrace(this, this.constructor);
this.strategy = 'Ignore';
this.reference = `This error was executed as part of the kafka-penguin Ignore message reprocessing strategy. Your consumer attempted to receive a message ${e.retryCount + 1} times but was unsuccessful. As a result, the message was sent to a Dead Letter Queue. Refer to the original error for further information`;
this.name = `${e.name} (Consumer Side)`;
this.message = e.message;
this.originalError = e.originalError;
this.retryCount = e.retryCount;
}
}
interface messageValue {
acks?: Number,
timeout?: Number,
compression?: CompressionTypes,
topic: string,
messages: object[],
}
interface consumerRunInput {
eachMessage: ({
topic,
partitions,
message,
}: {
topic: string,
partitions: number,
message: any
}) => void,
eachBatchAutoResolve: boolean,
}
interface consumerSubscribeInput {
groupId?: String,
partitionAssigners?: any,
sessionTimeout?: Number,
rebalanceTimeout?: Number,
heartbeatInterval?: Number,
metadataMaxAge?: Number,
allowAutoTopicCreation?: Boolean,
maxBytesPerPartition?: Number,
minBytes?: Number,
maxBytes?: Number,
maxWaitTimeInMs?: Number,
retry?: Object,
maxInFlightRequests?: Number,
rackId?: String
}
export class Ignore {
client: any;
topic: string;
callback?: (message: any) => boolean;
innerConsumer: any;
admin: any;
innerProducer: any;
constructor(client: any, topic: string, callback?: any) {
this.topic = topic;
this.client = client;
this.callback = callback;
this.admin = this.client.admin();
this.innerConsumer = null;
this.innerProducer = this.client.producer();
}
producer() {
// Reference the Ignore instance for closure in the returned object
const ignoreInstance = this;
const { innerProducer } = ignoreInstance;
// Return an object with all Producer methods adapted to execute Ignore strategy
console.log('INNER PRODUCER', innerProducer);
return {
...innerProducer,
connect() {
return innerProducer.connect()
.catch((e: Error) => console.log(e));
},
send(message: messageValue) {
return innerProducer.connect()
.then(() => {
innerProducer.send({
...message,
topic: message.topic,
messages: message.messages,
})
.catch((e: Error) => {
console.log(e);
// Print the error to the console
const newError = new IgnoreErrorProducer(e);
console.log(newError);
});
});
},
};
}
consumer(groupId: { groupId: string }) {
this.innerConsumer = this.client.consumer(groupId);
const ignoreInstance = this;
const { innerConsumer } = ignoreInstance;
// Returns an object with all Consumer methods adapter to execute ignore strategy
return {
...innerConsumer,
connect() {
return innerConsumer.connect();
},
subscribe(input?: consumerSubscribeInput) {
return innerConsumer.subscribe({
...input,
topic: ignoreInstance.topic,
fromBeginning: false,
});
},
run(input: consumerRunInput) {
const { eachMessage } = input;
return innerConsumer.run({
...input,
eachMessage: (
{ topic, partitions, message }: {
topic: string, partitions: number, message: any
// eslint-disable-next-line comma-dangle
}
) => {
try {
// If user doesn't pass in callback
if (ignoreInstance.callback) {
if (!ignoreInstance.callback(message)) throw Error;
eachMessage({ topic, partitions, message });
}
} catch (e) {
const newError = new IgnoreErrorConsumer(e);
console.error("kafka Error:", newError);
}
},
})
},
};
}
} | the_stack |
import fs from 'fs';
import util from 'util';
import path from 'path';
import os from 'os';
import { app, dialog, shell, ipcMain, BrowserWindow } from 'electron';
import { ipcConsts } from '../app/vars';
import { SocketAddress, WalletFile, WalletMeta, WalletSecretData } from '../shared/types';
import { isLocalNodeApi, isRemoteNodeApi, stringifySocketAddress, toSocketAddress } from '../shared/utils';
import { LOCAL_NODE_API_URL } from '../shared/constants';
import MeshService from './MeshService';
import GlobalStateService from './GlobalStateService';
import TransactionManager from './TransactionManager';
import fileEncryptionService from './fileEncryptionService';
import cryptoService from './cryptoService';
import encryptionConst from './encryptionConst';
import Logger from './logger';
import StoreService from './storeService';
import TransactionService from './TransactionService';
import NodeManager from './NodeManager';
import { readFileAsync, writeFileAsync } from './utils';
const logger = Logger({ className: 'WalletManager' });
const readDirectoryAsync = util.promisify(fs.readdir);
const copyFileAsync = util.promisify(fs.copyFile);
const unlinkFileAsync = util.promisify(fs.unlink);
const { exec } = require('child_process');
// Linux: ~/.config/<App Name>
// Mac OS: ~/Library/Application Support/<App Name>
// Windows: C:\Users\<user>\AppData\Local\<App Name>
const appFilesDirPath = app.getPath('userData');
const documentsDirPath = app.getPath('documents');
class WalletManager {
private readonly meshService: MeshService;
private readonly glStateService: GlobalStateService;
private readonly txService: TransactionService;
private nodeManager: NodeManager;
private txManager: TransactionManager;
private mnemonic = '';
private openedWalletFilePath: string | null = null;
constructor(mainWindow: BrowserWindow, nodeManager: NodeManager) {
this.subscribeToEvents(mainWindow);
this.nodeManager = nodeManager;
this.meshService = new MeshService();
this.glStateService = new GlobalStateService();
this.txService = new TransactionService();
this.txManager = new TransactionManager(this.meshService, this.glStateService, this.txService, mainWindow);
}
__getNewAccountFromTemplate = ({ index, timestamp, publicKey, secretKey }: { index: number; timestamp: string; publicKey: string; secretKey: string }) => ({
displayName: index > 0 ? `Account ${index}` : 'Main Account',
created: timestamp,
path: `0/0/${index}`,
publicKey,
secretKey,
});
subscribeToEvents = (mainWindow: BrowserWindow) => {
ipcMain.handle(ipcConsts.W_M_ACTIVATE, (_event, apiUrl) => {
try {
this.activateWalletManager(apiUrl);
} catch (e) {
logger.error('W_M_ACTIVATE channel', true, apiUrl);
throw e;
}
});
ipcMain.handle(ipcConsts.W_M_GET_NETWORK_DEFINITIONS, () => {
const netId = StoreService.get('netSettings.netId');
const netName = StoreService.get('netSettings.netName');
const genesisTime = StoreService.get('netSettings.genesisTime');
const layerDurationSec = StoreService.get('netSettings.layerDurationSec');
const explorerUrl = StoreService.get('netSettings.explorerUrl');
return { netId, netName, genesisTime, layerDurationSec, explorerUrl };
});
ipcMain.handle(ipcConsts.W_M_GET_CURRENT_LAYER, () => this.meshService.getCurrentLayer());
ipcMain.handle(ipcConsts.W_M_GET_GLOBAL_STATE_HASH, () => this.glStateService.getGlobalStateHash());
ipcMain.handle(ipcConsts.W_M_CREATE_WALLET, (_event, request) =>
this.createWalletFile({ ...request }).catch((err) => {
logger.error('W_M_CREATE_WALLET channel', err, request);
throw err;
})
);
ipcMain.handle(ipcConsts.W_M_READ_WALLET_FILES, async () => {
const res = await this.readWalletFiles();
return res;
});
ipcMain.handle(ipcConsts.W_M_UNLOCK_WALLET, async (_event, request) => {
const res = await this.unlockWalletFile({ ...request });
return res;
});
ipcMain.on(ipcConsts.W_M_UPDATE_WALLET_SECRETS, async (_event, { fileName, password, data }: { fileName: string; password: string; data: WalletSecretData }) => {
await this.updateWalletSecret(fileName, password, data);
});
ipcMain.on(ipcConsts.W_M_UPDATE_WALLET_META, async <T extends keyof WalletMeta>(_event, { fileName, key, value }: { fileName: string; key: T; value: WalletMeta[T] }) => {
await this.updateWalletMeta(fileName, key, value);
});
ipcMain.handle(ipcConsts.W_M_CREATE_NEW_ACCOUNT, async (_event, request) => {
const res = await this.createNewAccount({ ...request });
return res;
});
ipcMain.handle(ipcConsts.W_M_COPY_FILE, async (_event, request) => {
const res = await this.copyFile({ ...request });
return res;
});
ipcMain.on(ipcConsts.W_M_SHOW_FILE_IN_FOLDER, (_event, request) => {
this.showFileInDirectory({ ...request });
});
ipcMain.on(ipcConsts.W_M_SHOW_DELETE_FILE, async (_event, request) => {
await this.deleteWalletFile({ browserWindow: mainWindow, ...request });
});
ipcMain.on(ipcConsts.W_M_WIPE_OUT, async () => {
await this.wipeOut({ browserWindow: mainWindow });
});
ipcMain.handle(ipcConsts.W_M_SEND_TX, async (_event, request) => {
const res = await this.txManager.sendTx({ ...request });
return res;
});
ipcMain.handle(ipcConsts.W_M_UPDATE_TX_NOTE, async (_event, request) => {
await this.txManager.updateTxNote(request);
return true;
});
ipcMain.handle(ipcConsts.W_M_SIGN_MESSAGE, async (_event, request) => {
const { message, accountIndex } = request;
const res = await cryptoService.signMessage({ message, secretKey: this.txManager.accounts[accountIndex].secretKey });
return res;
});
ipcMain.handle(ipcConsts.SWITCH_API_PROVIDER, async (_event, apiUrl: SocketAddress) => {
this.switchApiProvider(apiUrl);
return true;
});
};
activateWalletManager = (apiUrl: SocketAddress) => {
if (isLocalNodeApi(apiUrl)) {
this.openedWalletFilePath && this.updateWalletMeta(this.openedWalletFilePath, 'remoteApi', '');
} else {
this.openedWalletFilePath && this.updateWalletMeta(this.openedWalletFilePath, 'remoteApi', stringifySocketAddress(apiUrl));
this.nodeManager.connectToRemoteNode(apiUrl);
}
this.meshService.createService(apiUrl);
this.glStateService.createService(apiUrl);
this.txService.createService(apiUrl);
};
createWalletFile = async ({ password, existingMnemonic, apiUrl = LOCAL_NODE_API_URL }: { password: string; existingMnemonic: string; apiUrl: SocketAddress }) => {
const timestamp = new Date().toISOString().replace(/:/g, '-');
this.mnemonic = existingMnemonic || cryptoService.generateMnemonic();
const { publicKey, secretKey } = cryptoService.deriveNewKeyPair({ mnemonic: this.mnemonic, index: 0 });
const dataToEncrypt = {
mnemonic: this.mnemonic,
accounts: [this.__getNewAccountFromTemplate({ index: 0, timestamp, publicKey, secretKey })],
contacts: [],
};
const usingRemoteApi = isRemoteNodeApi(apiUrl);
!usingRemoteApi && (await this.nodeManager.startNode());
this.activateWalletManager(apiUrl);
this.txManager.setAccounts(dataToEncrypt.accounts);
const key = fileEncryptionService.createEncryptionKey({ password });
const encryptedAccountsData = fileEncryptionService.encryptData({ data: JSON.stringify(dataToEncrypt), key });
const meta: WalletMeta = {
displayName: 'Main Wallet',
created: timestamp,
netId: StoreService.get('netSettings.netId') as number,
remoteApi: usingRemoteApi ? stringifySocketAddress(apiUrl) : '',
meta: { salt: encryptionConst.DEFAULT_SALT },
};
const fileContent: WalletFile = {
meta,
crypto: { cipher: 'AES-128-CTR', cipherText: encryptedAccountsData },
};
const fileName = `my_wallet_${timestamp}.json`;
const fileNameWithPath = path.resolve(appFilesDirPath, fileName);
await writeFileAsync(fileNameWithPath, JSON.stringify(fileContent));
this.openedWalletFilePath = fileNameWithPath;
return { meta, accounts: dataToEncrypt.accounts, mnemonic: this.mnemonic };
};
readWalletFiles = async () => {
try {
const files = await readDirectoryAsync(appFilesDirPath);
const regex = new RegExp('(my_wallet_).*.(json)', 'ig');
const filteredFiles = files.filter((file) => file.match(regex));
const filesWithPath = filteredFiles.map((file) => path.join(appFilesDirPath, file));
return { error: null, files: filesWithPath };
} catch (error) {
logger.error('readWalletFiles', error);
return { error, files: null };
}
};
unlockWalletFile = async ({ path, password }: { path: string; password: string }) => {
try {
const fileContent = await readFileAsync(path);
// @ts-ignore
const { crypto, meta } = JSON.parse(fileContent) as WalletFile;
const key = fileEncryptionService.createEncryptionKey({ password });
const decryptedDataJSON = fileEncryptionService.decryptData({ data: crypto.cipherText, key });
const { accounts, mnemonic, contacts } = JSON.parse(decryptedDataJSON) as WalletSecretData;
const actualNetId = StoreService.get('netSettings.netId');
if (meta.netId !== actualNetId) {
// Update netId in wallet file to actual one
this.updateWalletMeta(path, 'netId', actualNetId);
meta.netId = actualNetId;
// And update remoteApi if it was specified
if (meta.remoteApi) {
const apis = StoreService.get('netSettings.grpcAPI');
if (!apis.find((x) => x === meta.remoteApi)) {
const [firstApi] = apis;
meta.remoteApi = firstApi;
this.updateWalletMeta(path, 'remoteApi', firstApi);
}
}
}
const apiUrl = toSocketAddress(meta.remoteApi);
const usingRemoteApi = isRemoteNodeApi(apiUrl);
!usingRemoteApi && (await this.nodeManager.startNode());
this.activateWalletManager(apiUrl);
this.txManager.setAccounts(accounts);
this.mnemonic = mnemonic;
this.openedWalletFilePath = path;
return { error: null, accounts, mnemonic, meta, contacts };
} catch (error) {
logger.error('unlockWalletFile', error, { path, password });
return { error, accounts: null, mnemonic: null, meta: null, contacts: null };
}
};
private loadWalletFile = async (fileName: string) => {
const rawFileContent = await readFileAsync(fileName, { encoding: 'utf-8' });
const fileContent: WalletFile = JSON.parse(rawFileContent);
return fileContent;
};
private updateWalletFile = async (fileName: string, data: Partial<WalletFile>) => {
try {
const wallet = await this.loadWalletFile(fileName);
await writeFileAsync(fileName, JSON.stringify({ ...wallet, ...data }));
return true;
} catch (error) {
logger.error('updateWalletFile', error);
return false;
}
};
updateWalletMeta = async <K extends keyof WalletMeta>(fileName: string, key: K, value: WalletMeta[K]) => {
const wallet = await this.loadWalletFile(fileName);
const updatedWallet: WalletFile = { ...wallet, meta: { ...wallet.meta, [key]: value } };
return this.updateWalletFile(fileName, updatedWallet);
};
updateWalletSecret = async (fileName: string, password: string, data: WalletSecretData) => {
const wallet = await this.loadWalletFile(fileName);
const key = fileEncryptionService.createEncryptionKey({ password });
const encryptedAccountsData = fileEncryptionService.encryptData({ data: JSON.stringify(data), key });
this.txManager.setAccounts(data.accounts);
return this.updateWalletFile(fileName, { ...wallet, crypto: { cipher: 'AES-128-CTR', cipherText: encryptedAccountsData } });
};
createNewAccount = async ({ fileName, password }: { fileName: string; password: string }) => {
try {
const key = fileEncryptionService.createEncryptionKey({ password });
const rawFileContent = await readFileAsync(fileName);
// @ts-ignore
const fileContent = JSON.parse(rawFileContent);
const decryptedDataJSON = fileEncryptionService.decryptData({ data: fileContent.crypto.cipherText, key });
const { mnemonic, accounts, contacts } = JSON.parse(decryptedDataJSON);
const { publicKey, secretKey } = cryptoService.deriveNewKeyPair({ mnemonic, index: accounts.length });
const timestamp = new Date().toISOString().replace(/:/, '-');
const newAccount = this.__getNewAccountFromTemplate({ index: accounts.length, timestamp, publicKey, secretKey });
const dataToEncrypt = {
mnemonic,
accounts: [...accounts, newAccount],
contacts,
};
const encryptedAccountsData = fileEncryptionService.encryptData({ data: JSON.stringify(dataToEncrypt), key });
await writeFileAsync(fileName, JSON.stringify({ ...fileContent, crypto: { cipher: 'AES-128-CTR', cipherText: encryptedAccountsData } }));
this.txManager.addAccount(newAccount);
return { error: null, newAccount };
} catch (error) {
logger.error('createNewAccount', error);
return { error };
}
};
copyFile = async ({ filePath, copyToDocuments }: { filePath: string; copyToDocuments: boolean }) => {
const timestamp = new Date().toISOString().replace(/:/g, '-');
const fileName = copyToDocuments ? `wallet_backup_${timestamp}.json` : `my_wallet_${timestamp}.json`;
const newFilePath = copyToDocuments ? path.join(documentsDirPath, fileName) : path.join(appFilesDirPath, fileName);
try {
await copyFileAsync(filePath, newFilePath);
return { error: null, newFilePath };
} catch (error) {
logger.error('copyFile', error);
return { error };
}
};
showFileInDirectory = async ({ isBackupFile, isLogFile }: { isBackupFile?: boolean; isLogFile?: boolean }) => {
if (isBackupFile) {
try {
const files = await readDirectoryAsync(documentsDirPath);
const regex = new RegExp('(wallet_backup_).*.(json)', 'ig');
const filteredFiles = files.filter((file) => file.match(regex));
const filesWithPath = filteredFiles.map((file) => path.join(documentsDirPath, file));
if (filesWithPath && filesWithPath[0]) {
shell.showItemInFolder(filesWithPath[0]);
} else {
shell.openPath(documentsDirPath);
}
} catch (error) {
logger.error('showFileInDirectory', error);
}
} else if (isLogFile) {
const logFilePath = path.resolve(appFilesDirPath, 'spacemesh-log.txt');
shell.showItemInFolder(logFilePath);
} else {
shell.openPath(appFilesDirPath);
}
};
deleteWalletFile = async ({ browserWindow, fileName }: { browserWindow: BrowserWindow; fileName: string }) => {
const options = {
title: 'Delete File',
message: 'All wallet data will be lost. Are You Sure?',
buttons: ['Delete Wallet File', 'Cancel'],
};
const { response } = await dialog.showMessageBox(browserWindow, options);
if (response === 0) {
try {
StoreService.clear();
await unlinkFileAsync(fileName);
this.openedWalletFilePath = null;
browserWindow.reload();
} catch (error) {
logger.error('deleteWalletFile', error);
}
}
};
wipeOut = async ({ browserWindow }: { browserWindow: BrowserWindow }) => {
const options = {
type: 'warning',
title: 'Reinstall App',
message: 'WARNING: All wallets, addresses and settings will be lost. Are you sure you want to do this?',
buttons: ['Delete All', 'Cancel'],
};
const { response } = await dialog.showMessageBox(browserWindow, options);
if (response === 0) {
browserWindow.destroy();
StoreService.clear();
const command = os.type() === 'Windows_NT' ? `rmdir /q/s '${appFilesDirPath}'` : `rm -rf '${appFilesDirPath}'`;
exec(command, (error: any) => {
if (error) {
logger.error('ipcMain wipeOut', error);
}
console.log('deleted'); // eslint-disable-line no-console
});
app.quit();
}
};
switchApiProvider = async (apiUrl: SocketAddress) => {
if (isRemoteNodeApi(apiUrl)) {
// We don't need to start Node here
// because it will be started on unlocking/creating the wallet file
// but we have to stop it in case that User switched to wallet mode
await this.nodeManager.stopNode();
}
this.activateWalletManager(apiUrl);
};
}
export default WalletManager; | the_stack |
"use strict";
// uuid: 39a65561-5c80-4732-a181-ced25c411e52
// ------------------------------------------------------------------------
// Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.
// Licensed under the MIT License+uuid License. See License.txt for details
// ------------------------------------------------------------------------
// Base server class for other servers agents
/** @module internal | This module is to be read only by developers */
// @WARN: Don't import any nodejs modules nor
// any other modules depending on node modules since it can be called by phantomjs
import { VERSION } from "../shared/version.js";
import { RelConsts } from "../shared/rel-consts.js";
import { Consts as consts } from '../shared/lib/consts.js';
import { OptsParser } from '../shared/opts-parser.js';
import { ServerConsts } from '../shared/lib/server-consts.js';
import { Sprintf } from '../shared/lib/sprintf.js';
import { PluginInjector } from './plugin-injector.js';
/**
* ## Description
*
* A **Render Server Agent** executes a server render, usually a headless web browser,
* sends order to start rendering, captures the render and saves it into a file.
*
*/
export namespace ServerAgent {
const sc = ServerConsts._SRV_CNT;
const sprintf = Sprintf.sprintf;
// ------------------------------------------------------------------------
// Consts
// ------------------------------------------------------------------------
const DO_PRINT_USAGE = 0;
const DO_RUN_SERVER = 1;
const DO_EXIT = 2;
// ------------------------------------------------------------------------
// Tools
// ------------------------------------------------------------------------
export function toPosixSlash(path: string): string {
return path.replace(/\\/g, '/');
}
/** Simple implementation of path.dirname()
* PhantomJs/SlimerJS don't support nodejs filesystem
*/
function dirName(filename: string): string {
const lastSlash = filename.lastIndexOf('/');
return lastSlash === -1 ? '.' : filename.substr(0, lastSlash);
}
// this function is credited to @Flygenring
// https://stackoverflow.com/questions/10830357/javascript-toisostring-ignores-timezone-offset
function getLocalISOTimeDate(): string {
const tzOffset = (new Date()).getTimezoneOffset() * 60000; // offset in milliseconds
return (new Date(Date.now() - tzOffset)).toISOString().substr(0, 19).replace('T', ' ');
}
// ------------------------------------------------------------------------
// Server
// ------------------------------------------------------------------------
const toExitOnError = true;
let isFirstFrame = true;
export abstract class BaseServer {
reportFileName: string = OptsParser.DEFAULT_OUT_REPORT;
width: uint = RelConsts.DEFAULT_WIDTH;
hasArgWidth: boolean = false;
height: uint = RelConsts.DEFAULT_HEIGHT;
hasArgHeight: boolean = false;
timeout: uint = 0;
maxWidth: uint = OptsParser.DEFAULT_MAX_WIDTH;
maxHeight: uint = OptsParser.DEFAULT_MAX_HEIGHT;
maxFps: uint = OptsParser.DEFAULT_MAX_FPS;
maxFrameCount: uint = OptsParser.DEFAULT_MAX_FRAME_COUNT;
progress: uint = OptsParser.DEFAULT_PROGRESS;
url: string = '';
framesPattern: string = '';
projDir = '';
fps = 1;
logLevel = consts.LL_WARN;
isVerbose = false;
toDeletePreviousVersion = false;
toGenFrames = true;
toTeleport = false;
rootPath = '';
configPath: string = '';
frameNr = 0;
frameCount = 0;
argsVars;
configFileMode = false;
constructor(public serverName: string,
public args: string[],
public platform: string, public cwd: string,
public existsSync: (fileName: string) => boolean,
public isDirectory: (fileName: string) => boolean,
public unlinkSync: (fileName: string) => void,
public mkdirpSync: (path: string) => void,
public readUtf8Sync: (fileName: string) => any,
public writeFileSync: (fileName: string, data) => void,
public posixPathJoin: (path1: string, path2: string) => string) {
}
exitServer(_retValue = 0) {
if (this.logLevel) { console.log(`Terminating Server`); }
}
abstract runServer();
getSetupVars(): string {
return this.argsVars ?
(Object.keys(this.argsVars).map(key =>
sc.RENDER_VAR_SUFFIX + encodeURIComponent(`${key}=${this.argsVars[key]}`),
).join('&') + '&') : '';
}
getPageUrl() {
let pageUrl = this.url
+ (this.url.indexOf('?') === -1 ? '?' : '&')
+ sc.LOG_LEVEL_SUFFIX + this.logLevel + '&'
+ (this.hasArgWidth ? `${sc.WIDTH_SUFFIX}${this.width}&` : '')
+ (this.hasArgHeight ? `${sc.HEIGHT_SUFFIX}${this.height}&` : '')
+ this.getSetupVars()
+ sc.TELEPORT_SUFFIX + this.toTeleport.toString();
// since this is an fundamental information it should always display
// even not on verbose mode.
if (this.logLevel !== 0) {
console.log(`serverless pageUrl: [${pageUrl}]`);
}
// adds the server in separated so it can have a serverless link
pageUrl += '&' + sc.SERVER_SUFFIX + this.serverName;
// since this is an fundamental information it should always display
// even not on verbose mode.
if (this.logLevel !== 0) {
console.log(`pageUrl: [${pageUrl}]`);
}
return pageUrl;
}
getViewport = () => {
const viewport = {
width: this.width,
height: this.height,
};
if (this.isVerbose) {
console.log(`width: ${viewport.width}, height: ${viewport.height}`);
}
return viewport;
}
/** .json configuration parser */
private parseJsonConfig(args: string[], cfg: any,
configFileName: string, argI: int): int {
const cfgConfigData = cfg['config'];
if (cfgConfigData) {
const pCfg = cfgConfigData['abeamer'];
if (pCfg) {
args.splice(0, argI + 1);
argI = 0;
this.projDir = this.projDir || dirName(configFileName);
Object.keys(pCfg).forEach(key => {
switch (key) {
case 'plugins':
PluginInjector.plugins = pCfg[key] || [];
break;
case 'file':
case 'report':
case 'fps':
case 'out':
// @WARN: Due security reasons:
// config can't not contain max-width, max-height, max-frame-count, max-fps,
// since these values can be part of a story teleported from the user.
case 'height':
case 'width':
args.push('--' + key, pCfg[key].toString().
replace('__PROJDIR__', this.projDir));
break;
}
});
}
}
return argI;
}
/** .ini configuration parser */
private parseIniCfgContent(cfgText: string): { [key: string]: any } {
const cfg = {};
// very basic .ini variables parser
// @TODO: place this code in a external module so it can be used by the library and the cli
cfgText.split(/\n/).forEach(line =>
line.replace(/^\s*[\$@]abeamer-([\w+-]+)\s*:\s*"?([^\n"]+)"?\s*;\s*$/,
(_all, p1, p2) => {
if (this.isVerbose) { console.log(`config: ${p1}=[${p2}]`); }
cfg[p1] = p2;
return '';
}));
return cfg;
}
/** Parses config */
private parseConfig(args: string[], cfgText: string,
configFileName: string, argI: int) {
return this.parseJsonConfig(args, configFileName.match(/\.json$/)
? JSON.parse(cfgText)
: { config: { abeamer: this.parseIniCfgContent(cfgText) } },
configFileName, argI);
}
// ------------------------------------------------------------------------
// Parse Arguments
// ------------------------------------------------------------------------
private parseArguments(args: string[]): int {
let argI = 1;
const self = this;
function getConfigFileName(value: string): string {
let configFileName = toPosixSlash(value);
if (!configFileName) { return ''; }
if (self.existsSync(configFileName) && self.isDirectory(configFileName)) {
configFileName = self.posixPathJoin(configFileName, 'abeamer.ini');
}
if (!self.existsSync(configFileName)) {
throw `Config file ${configFileName} doesn't exists`;
}
return configFileName;
}
function setFramesPattern(framesPattern?: string): void {
self.framesPattern = toPosixSlash(framesPattern || OptsParser.DEFAULT_OUT_PATTERN)
.replace('__PROJDIR__', self.projDir);
if (self.isVerbose && self.toGenFrames) {
console.log(`framesPattern: ${self.framesPattern}`);
}
}
function parseOption(option: string, value, multipleValue?): uint {
switch (option) {
case '@param':
parseOption('config', getConfigFileName(toPosixSlash(value)));
break;
case 'version':
console.log(VERSION);
return DO_EXIT;
case 'll':
self.logLevel = value as int;
self.isVerbose = self.logLevel >= consts.LL_VERBOSE;
if (self.isVerbose) { console.log(`Args: [${args.join('],[')}]`); }
break;
case 'url':
self.url = value;
if (self.isVerbose) { console.log(`url: ${self.url}`); }
break;
case 'var':
self.argsVars = multipleValue;
if (self.isVerbose) { console.log(`var: ${multipleValue}`); }
break;
case 'file':
const filename = toPosixSlash(value);
// rootPath is added at the beginning to able to generate report
// without self information due security reasons and provide a sharable report
let needsRootPath = false;
const isWin = self.platform.indexOf('win') !== -1;
if (isWin) {
needsRootPath = filename[1] !== ':' && filename[2] !== '/';
} else {
needsRootPath = filename[0] !== '/';
}
if (needsRootPath) { self.rootPath = toPosixSlash(self.cwd) + '/'; }
self.projDir = dirName(filename);
if (!self.framesPattern) {
setFramesPattern();
}
if (!self.existsSync(filename)) {
throw `Page File ${filename} doesn't exists`;
}
if (!self.url) {
self.url = 'file://' + (isWin ? '/' : '') +
encodeURI(self.rootPath + filename);
if (self.isVerbose) { console.log(`final url: ${self.url}`); }
}
break;
case 'out':
setFramesPattern(value);
break;
case 'width':
if (!self.hasArgWidth) {
self.width = value as int;
self.hasArgWidth = !self.configFileMode;
if (self.isVerbose) { console.log(`width: ${self.width}`); }
}
break;
case 'maxWidth':
self.maxWidth = value as int;
if (self.isVerbose) { console.log(`maxWidth: ${self.maxWidth}`); }
break;
case 'height':
if (!self.hasArgHeight) {
self.height = value as int;
self.hasArgHeight = !self.configFileMode;
if (self.isVerbose) { console.log(`height: ${self.height}`); }
}
break;
case 'maxHeight':
self.maxHeight = value as int;
if (self.isVerbose) { console.log(`maxHeight: ${self.maxHeight}`); }
break;
case 'fps':
self.fps = value as int;
if (self.isVerbose) { console.log(`fps: ${self.fps}`); }
break;
case 'maxFps':
self.maxFps = value as int;
if (self.isVerbose) { console.log(`maxFps: ${self.maxFps}`); }
break;
case 'maxFrameCount':
self.maxFrameCount = value as int;
if (self.isVerbose) { console.log(`maxFrameCount: ${self.maxFrameCount}`); }
break;
case 'timeout':
self.timeout = value as int;
if (self.isVerbose) { console.log(`timeout: ${self.timeout}`); }
break;
case 'progress':
self.progress = value as int;
if (self.isVerbose) { console.log(`progress: ${self.progress}`); }
break;
case 'allowedPlugins':
PluginInjector.loadAllowedPlugins(value,
self.existsSync, self.readUtf8Sync);
break;
case 'injectPage':
PluginInjector.injectPage = value;
if (self.isVerbose) { console.log(`injectPage: ${value}`); }
break;
case 'teleport':
self.toTeleport = true;
break;
case 'dp':
self.toDeletePreviousVersion = true;
break;
case 'noframes':
self.toGenFrames = false;
break;
case 'report':
self.reportFileName = value;
break;
case 'server':
self.serverName = value;
break;
case 'config':
const configFileName = getConfigFileName(value);
if (!configFileName) { return 0; }
if (self.isVerbose) { console.log(`Loading Config ${configFileName}`); }
if (!self.existsSync(configFileName)) {
throw `Config ${configFileName} doesn't exists`;
}
self.configPath = dirName(configFileName) + '/';
// @TODO: Investigate how to make an async version of load the config
const configFile = self.readUtf8Sync(configFileName);
const injectArgs = [];
let injectArgI = 0;
self.parseConfig(injectArgs, configFile, configFileName, argI);
// injects the config as args to the main loop
self.configFileMode = true;
try {
OptsParser.iterateArgOpts(true, () => injectArgs[injectArgI++],
parseOption,
);
} finally {
self.configFileMode = false;
}
break;
}
}
const res = OptsParser.iterateArgOpts(true, () => args[argI++], parseOption);
if (res) { return res; }
if (this.url) {
if (!this.projDir) { this.projDir = '.'; }
if (!this.framesPattern) { setFramesPattern(); }
return (this.framesPattern ? DO_RUN_SERVER : DO_PRINT_USAGE);
}
return DO_PRINT_USAGE;
}
/**
* Parse Arguments is async to later provide async config loading
* @param callback
*/
parseArgumentsAsync(callback: (res: int) => void) {
callback(this.parseArguments(this.args));
}
// ------------------------------------------------------------------------
// Message Handler
// ------------------------------------------------------------------------
handleMessage(msg: string,
sendClientMsg: (cmd: string, value?: string) => void,
takeScreenshot: (outFileName: string, onDone: () => void) => void) {
const self = this;
function renderDone(): void {
self.frameNr++;
if (self.frameNr >= self.frameCount) { self.frameCount = self.frameNr + 1; }
sendClientMsg(sc.MSG_RENDER_DONE);
}
if (msg.indexOf(sc.MESSAGE_PREFIX) === 0) {
try {
msg = msg.substr(sc.MESSAGE_PREFIX.length);
const parts = msg.split(sc.CMD_VALUE_SEP);
const cmd = parts[0];
const value = parts.length === 2 ? parts[1] : '';
if (this.isVerbose) { console.log(`Cmd: ${cmd}, Value: ${value}`); }
switch (cmd) {
case sc.MSG_READY:
sendClientMsg(sc.MSG_SERVER_READY);
break;
case sc.MSG_RENDER:
const frameFileName = sprintf(this.framesPattern, this.frameNr);
if (this.toGenFrames) {
// creates output tree if doesn't exists
if (isFirstFrame) {
isFirstFrame = false;
const matches = frameFileName.match(/^(.+)\/([^/]+)$/);
if (matches) {
const framesFolder = matches[1];
if (!this.existsSync(framesFolder)) {
if (this.isVerbose) {
console.log(`Creating Folder: ${framesFolder}`);
} else if (this.logLevel > consts.LL_SILENT) {
console.log(`Creating Story frames on: ${framesFolder}`);
}
this.mkdirpSync(framesFolder);
}
}
}
takeScreenshot(this.rootPath + frameFileName, () => {
if (this.isVerbose) { console.log(`Saved: ${frameFileName}`); }
if (this.progress > 0 && this.frameNr % this.progress === 0) {
console.log(new Array(2 + (this.frameNr / this.progress))
.join('▒') + ` ${this.frameNr} frames`);
}
renderDone();
});
} else {
renderDone();
}
break;
case sc.MSG_RENDER_FINISHED:
this.generateReport();
break;
case sc.MSG_SET_FRAME_NR:
this.frameNr = parseInt(value);
if (this.isVerbose) { console.log(`frame-nr: ${this.frameNr}`); }
this.checkForValidFrame(this.frameNr, true, `Invalid number frame nr`);
break;
case sc.MSG_SET_FRAME_COUNT:
this.frameCount = parseInt(value);
if (this.isVerbose) { console.log(`frame-count: ${this.frameCount}`); }
this.checkForValidFrame(this.frameCount, false, `Invalid number of frames count`);
break;
case sc.MSG_SET_FPS:
this.fps = parseInt(value);
if (this.isVerbose) { console.log(`fps: ${this.fps}`); }
this.checkForValidFps();
break;
case sc.MSG_LOG_MSG:
console.log(value);
break;
case sc.MSG_LOG_WARN:
console.warn(value);
break;
case sc.MSG_LOG_ERROR:
console.error(value);
break;
case sc.MSG_TELEPORT:
const storyFileName = (this.configPath ? this.configPath :
this.rootPath) + 'story.json';
console.log(`Created ${storyFileName}`);
this.writeFileSync(storyFileName, value);
this.exitServer();
break;
case sc.MSG_EXIT:
this.exitServer();
break;
}
} catch (error) {
self.handleError(error.message);
}
}
}
// ------------------------------------------------------------------------
// Handle Errors
// ------------------------------------------------------------------------
handleError(msg: string) {
console.error(msg);
if (toExitOnError) { this.exitServer(OptsParser.ON_ERROR_EXIT_VALUE); }
}
// ------------------------------------------------------------------------
// Prepare Server
// ------------------------------------------------------------------------
// security checks
checkForValidFps() {
if (this.fps <= 0 || this.fps > this.maxFps) {
throw `Invalid number of frames per second`;
}
}
// security checks
checkForValidFrame(frameNr: uint, allowZero: boolean, errorMsg: string) {
if ((allowZero || !frameNr) || frameNr < 0 || frameNr > this.maxFrameCount) {
throw errorMsg;
}
}
prepareServer() {
PluginInjector.inject(this.existsSync, this.readUtf8Sync, this.writeFileSync);
if (this.width <= 0 || this.width > this.maxWidth
|| this.height <= 0 || this.height > this.maxHeight) {
throw `Invalid frame output size`;
}
this.checkForValidFps();
if (this.toDeletePreviousVersion) {
if (this.isVerbose) { console.log(`Deleting previous frames`); }
let frameI = this.frameNr;
while (true) {
const frameFileName = sprintf(this.framesPattern, frameI);
if (this.isVerbose) { console.log(`frameFileName: ${frameFileName}`); }
if (this.existsSync(frameFileName)) {
this.unlinkSync(frameFileName);
} else {
break;
}
frameI++;
}
}
}
// ------------------------------------------------------------------------
// Generate Report
// ------------------------------------------------------------------------
generateReport() {
if (this.reportFileName && this.toGenFrames) {
const framesDir = dirName(this.framesPattern);
this.reportFileName = this.reportFileName.
replace('__FRAMES_DIR__', framesDir);
let framesPattern = this.framesPattern;
// removes the absolute path due security issues
if (framesDir === framesPattern.substr(0, framesDir.length)) {
framesPattern = './' + framesPattern.substr(framesDir.length + 1);
}
const report = {
width: this.width,
height: this.height,
fps: this.fps,
framecount: this.frameCount,
// @HINT: Doesn't include the absolute path for security reasons
framespattern: framesPattern,
timestamp: getLocalISOTimeDate(),
};
this.mkdirpSync(dirName(this.reportFileName));
this.writeFileSync(this.reportFileName, JSON.stringify(report, null, 2));
if (this.isVerbose) { console.log(`Generated Report ${this.reportFileName}`); }
console.log(`Generated ${this.frameCount} frames`);
}
}
// ------------------------------------------------------------------------
// Start
// ------------------------------------------------------------------------
start() {
try {
this.parseArgumentsAsync((res) => {
switch (res) {
case DO_PRINT_USAGE:
OptsParser.printUsage();
break;
case DO_RUN_SERVER:
this.prepareServer();
this.runServer();
break;
case DO_EXIT:
break;
}
});
} catch (error) {
console.log(`Server Error: ${error.message || error.toString()}`);
this.exitServer(OptsParser.ON_ERROR_EXIT_VALUE);
// throw error;
}
}
}
} | the_stack |
module Kiwi {
/**
* A TypeScript conversion of JS Signals by Miller Medeiros.
* Released under the MIT license
* http://millermedeiros.github.com/js-signals/
*
* @class Signal
* @namespace Kiwi
* @constructor
*
* @author Miller Medeiros, JS Signals
*/
export class Signal {
/**
* A list of all of the signal bindings that have been attached.
* @property _bindings
* @type Array
* @private
*/
private _bindings: SignalBinding[] = [];
/**
*
* @property _prevParams
* @type Any
* @private
*/
private _prevParams = null;
/**
* Signals Version Number
* @property VERSION
* @type String
* @default '1.0.0'
* @final
* @static
* @public
*/
public static VERSION: string = '1.0.0';
/**
* If Signal should keep record of previously dispatched parameters.
* @property memorize
* @type boolean
* @default false
* @public
*/
public memorize: boolean = false;
/**
* If the callbacks should propagate or not.
* @property _shouldPropagate
* @type boolean
* @default true
* @private
*/
private _shouldPropagate: boolean = true;
/**
* If Signal is active and should broadcast events.
* Note: Setting this property during a dispatch will only affect the next dispatch,
* if you want to stop the propagation of a signal use `halt()` instead.
* @property active
* @type boolean
* @default true
* @public
*/
public active: boolean = true;
/**
* Returns the type of this object
* @method objType
* @return {String} "Signal"
* @public
*/
public objType() {
return "Signal";
}
/**
* Validates a event listener an is used to check to see if it is valid or not.
* An event listener is not valid if it is not a function.
* If a event listener is not valid, then a Error is thrown.
*
* @method validateListener
* @param listener {Any} The event listener to be validated.
* @param fnName {Any} The name of the function.
* @public
*/
public validateListener(listener, fnName) {
if (typeof listener !== 'function')
{
throw new Error('listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName));
}
}
/**
* Internal Code which handles the registeration of a new callback (known as a "listener").
* Creates a new SignalBinding for the Signal and then adds the binding to the list by its priority level.
*
* @method _registerListener
* @param listener {Function} The method that is to be dispatched.
* @param isOnce {boolean} If the method should only be dispatched a single time or not.
* @param listenerContext {Object} The context that the callback should be executed with when called.
* @param priority {Number} The priority of this callback when Bindings are dispatched.
* @return {Kiwi.SignalBinding} The new SignalBinding that was created.
* @private
*/
private _registerListener(listener, isOnce: boolean, listenerContext, priority: number): SignalBinding {
var prevIndex: number = this._indexOfListener(listener, listenerContext);
var binding: SignalBinding;
if (prevIndex !== -1)
{
binding = this._bindings[prevIndex];
if (binding.isOnce() !== isOnce)
{
throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.');
}
}
else
{
binding = new SignalBinding(this, listener, isOnce, listenerContext, priority);
this._addBinding(binding);
}
if (this.memorize && this._prevParams)
{
binding.execute(this._prevParams);
}
return binding;
}
/**
* Handles the process of adding a new SignalBinding to the bindings list by the new Bindings priority.
*
* @method _addBinding
* @param binding {Kiwi.SignalBinding}
* @private
*/
private _addBinding(binding: SignalBinding) {
//simplified insertion sort
var n: number = this._bindings.length;
do { --n; } while (this._bindings[n] && binding.priority <= this._bindings[n].priority);
this._bindings.splice(n + 1, 0, binding);
}
/**
* Returns the index of any Binding which matches the listener and context that is passed.
* If none match then this method returns -1.
*
* @method _indexOfListener
* @param listener {Function} The method that we are checking to see.
* @param context {any} The context of the method we are checking.
* @return {number} The index of listener/context.
* @private
*/
private _indexOfListener(listener, context): number {
var n: number = this._bindings.length;
var cur: SignalBinding;
while (n--)
{
cur = this._bindings[n];
if (cur.getListener() === listener && cur.context === context)
{
return n;
}
}
return -1;
}
/**
* Accepts a function and returns a boolean indicating if the function
* has already been attached to this Signal.
*
* @method has
* @param listener {Function} The method you are checking for.
* @param [context=null] {Any} The context of the listener.
* @return {boolean} If this Signal already has the specified listener.
* @public
*/
public has(listener, context:any = null): boolean {
return this._indexOfListener(listener, context) !== -1;
}
/**
* Adds a new listener/callback to this Signal.
* The listener attached will be executed whenever this Signal dispatches an event.
*
* @method add
* @param listener {Function} Signal handler function.
* @param [listenerContext=null] {Any} Context on which listener will be executed. (object that should represent the `this` variable inside listener function).
* @param [priority=0] {Number} The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
* @return {Kiwi.SignalBinding} An Object representing the binding between the Signal and listener.
* @public
*/
public add(listener, listenerContext:any = null, priority: number = 0): SignalBinding {
this.validateListener(listener, 'add');
return this._registerListener(listener, false, listenerContext, priority);
}
/**
* Add listener to the signal that should be removed after first execution (will be executed only once).
*
* @method addOnce
* @param listener {Function} Signal handler function.
* @param [listenerContext=null] {Any} Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param [priority=0] {Number} The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
* @return {Kiwi.SignalBinding} An Object representing the binding between the Signal and listener.
* @public
*/
public addOnce(listener, listenerContext:any = null, priority: number = 0): SignalBinding {
this.validateListener(listener, 'addOnce');
return this._registerListener(listener, true, listenerContext, priority);
}
/**
* Remove a single listener from the dispatch queue.
*
* @method remove
* @param listener {Function} Handler function that should be removed.
* @param [context=null] {Any} Execution context (since you can add the same handler multiple times if executing in a different context).
* @return {Function} Listener handler function.
* @public
*/
public remove(listener, context:any = null) {
this.validateListener(listener, 'remove');
var i: number = this._indexOfListener(listener, context);
if (i !== -1)
{
this._bindings[i]._destroy(); //no reason to a SignalBinding exist if it isn't attached to a signal
this._bindings.splice(i, 1);
}
return listener;
}
/**
* Remove all listeners from the Signal.
* @method removeAll
* @public
*/
public removeAll() {
var n: number = this._bindings.length;
while (n--)
{
this._bindings[n]._destroy();
}
this._bindings.length = 0;
}
/**
* Returns the number of listeners that have been attached to this Signal.
*
* @method getNumListeners
* @return {number} Number of listeners attached to the Signal.
* @public
*/
public getNumListeners(): number {
return this._bindings.length;
}
/**
* Stop propagation of the event, blocking the dispatch to next listeners on the queue.
* Note: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.
*
* @method halt
* @public
*/
public halt() {
this._shouldPropagate = false;
}
/**
* Resume propagation of the event, resuming the dispatch to next listeners on the queue.
* Note: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.
*
* @method resume
* @public
*/
public resume() {
this._shouldPropagate = true;
}
/**
* Dispatch/Broadcast to all listeners added to this Signal.
* Parameters passed to this method will also be passed to each handler.
*
* @method dispatch
* @param [params]* {any} Parameters that should be passed to each handler.
* @public
*/
public dispatch(...paramsArr: any[]) {
if (!this.active)
{
return;
}
var n: number = this._bindings.length;
var bindings: SignalBinding[];
if (this.memorize)
{
this._prevParams = paramsArr;
}
if (!n)
{
//should come after memorize
return;
}
bindings = this._bindings.slice(0); //clone array in case add/remove items during dispatch
this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.
//execute all callbacks until end of the list or until a callback returns `false` or stops propagation
//reverse loop since listeners with higher priority will be added at the end of the list
do {
n--;
} while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
}
/**
* Forget memorized arguments. See the 'memorize' property.
* @method forget
* @public
*/
public forget() {
this._prevParams = null;
}
/**
* Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
* Note: calling any method on the signal instance after calling dispose will throw errors.
* @method dispose
* @public
*/
public dispose() {
this.removeAll();
delete this._bindings;
delete this._prevParams;
}
}
} | the_stack |
import md5 from "md5";
import "setimmediate";
import {Program, Library, createId, RawValue, RawEAV, RawMap, handleTuples} from "../../ts";
const EMPTY:never[] = [];
export interface Instance extends HTMLElement {
__element: RawValue,
__source: HTML,
__styles?: RawValue[],
__sort?:RawValue,
__autoSort?:RawValue,
__listeners?: {[event:string]: boolean},
__capturedKeys?: {[code:number]: boolean}
}
export interface Style extends RawMap<RawValue> {__count: number}
export interface StyleElement extends HTMLStyleElement {__style: RawValue}
////////////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////////////
let naturalComparator = new Intl.Collator("en", {numeric: true}).compare;
export class HTML extends Library {
static id = "html";
//////////////////////////////////////////////////////////////////////
// Public API
//////////////////////////////////////////////////////////////////////
addExternalRoot(tag:string, element:HTMLElement) {
let elemId = createId();
let eavs:RawEAV[] = [
[elemId, "tag", tag],
[elemId, "tag", "html/root/external"]
];
this._instances[elemId] = this.decorate(element, elemId);
this._sendEvent(eavs);
}
getInstances(elemId:RawValue) {
let instanceIds = this._elementToInstances[elemId];
if(!instanceIds) return;
return instanceIds.map((id) => this._instances[id]);
}
getContainer() {
return this._container;
}
// @DEPRECATED
getInstance(instanceId:RawValue) {
return this._instances[instanceId];
}
isInstance(elem?:any): elem is Instance {
if(!elem || !(elem instanceof Element)) return false;
let instance = elem as Instance;
return instance && !!instance["__element"] && instance.__source == this;
}
//////////////////////////////////////////////////////////////////////
// Implementation
//////////////////////////////////////////////////////////////////////
/** Topmost element containing root elements. */
_container:HTMLElement;
/** Instances are the physical DOM elements representing Eve elements. */
_instances:RawMap<Instance> = {};
/** Eve elements map to one or more instances. */
_elementToInstances:RawMap<RawValue[]> = {};
/** Eve style records represent a set of CSS properties for a class (the style id). */
_styles:RawMap<Style> = {};
/** Synthetic style container. */
_syntheticStyleContainer:HTMLElement;
/** One style element per synthetic style. */
_syntheticStyles:RawMap<StyleElement> = {};
/** Dummy used for converting style properties to CSS strings. */
_dummy:HTMLElement;
/** Map of currently checked radio buttons (used to uncheck them when their siblings are checked). */
_checkedRadios:{[name:string]: RawValue, [name:number]: RawValue} = {};
setup() {
if(typeof document === "undefined") {
this.handlers = {} as any;
return;
}
this._container = document.createElement("div");
this._container.setAttribute("program", this.program.name);
document.body.appendChild(this._container);
this._syntheticStyleContainer = document.createElement("div");
this._syntheticStyleContainer.style.display = "none"
this._syntheticStyleContainer.style.visibility = "hidden";
this._container.appendChild(this._syntheticStyleContainer);
this._dummy = document.createElement("div");
window.addEventListener("resize", this._resizeEventHandler("resize-window"));
window.addEventListener("click", this._mouseEventHandler("click"));
window.addEventListener("dblclick", this._mouseEventHandler("double-click"));
window.addEventListener("mousedown", this._mouseEventHandler("mouse-down"));
window.addEventListener("mouseup", this._mouseEventHandler("mouse-up"));
window.addEventListener("contextmenu", this._captureContextMenuHandler());
window.addEventListener("change", this._changeEventHandler("change"));
window.addEventListener("input", this._inputEventHandler("change"));
window.addEventListener("keydown", this._keyEventHandler("key-down"));
window.addEventListener("keyup", this._keyEventHandler("key-up"));
window.addEventListener("focus", this._focusEventHandler("focus"), true);
window.addEventListener("blur", this._focusEventHandler("blur"), true);
document.body.addEventListener("mouseenter", this._hoverEventHandler("hover-in"), true);
document.body.addEventListener("mouseleave", this._hoverEventHandler("hover-out"), true);
// window.addEventListener("hashchange", this._hashChangeHandler("url-change"));
}
protected decorate(elem:Element, elemId:RawValue): Instance {
let e = elem as Instance;
e.__element = elemId;
e.__source = this;
return e;
}
protected decorateStyle(styleElem:HTMLStyleElement, styleId:RawValue): StyleElement {
let s = styleElem as StyleElement;
s.__style = styleId;
return s;
}
protected _sendEvent(eavs:RawEAV[]) {
this.program.inputEAVs(eavs);
}
protected addInstance(id:RawValue, elemId:RawValue, tagname:RawValue, ns?:RawValue) {
if(id === null || id === "null") throw new Error(`Cannot create instance with null id for element '${elemId}'.`);
let instance = this._instances[id];
if(instance) throw new Error(`Recreating existing instance '${id}'`);
if(ns) instance = this.decorate(document.createElementNS(""+ns, ""+tagname), elemId);
else instance = this.decorate(document.createElement(""+tagname), elemId);
if(!this._elementToInstances[elemId]) this._elementToInstances[elemId] = [id];
else this._elementToInstances[elemId].push(id);
return this._instances[id] = instance;
}
protected removeInstance(id:RawValue) {
let instance = this._instances[id];
if(!instance) throw new Error(`Unable to clear nonexistent instance '${id}'`);
let elemId = instance.__element;
let instances = this._elementToInstances[elemId];
if(instances.length === 1) delete this._elementToInstances[elemId];
else instances[instances.indexOf(id)] = instances.pop()!;
if(instance.parentElement) instance.parentElement.removeChild(instance);
delete this._instances[id];
}
protected insertRoot(root:Instance) {
this.insertSortedChild(this._container, root, root.__sort);
}
protected insertChild(parent:Element|null, child:Instance, at:RawValue|undefined) {
if(!parent) return;
if(at === undefined) {
parent.appendChild(child);
return;
}
let current;
for(let curIx = 0; curIx < parent.childNodes.length; curIx++) {
let cur = parent.childNodes[curIx] as Instance;
let curSort = cur.__sort;
if(curSort === undefined) curSort = cur.__autoSort;
if(cur === child) continue;
if(curSort === undefined || naturalComparator(""+curSort, ""+at) > 0) {
current = cur;
break;
}
}
if(current) parent.insertBefore(child, current);
else parent.appendChild(child);
}
protected insertSortedChild(parent:Element|null, child:Instance, sort?:RawValue) {
child.__sort = sort;
this.insertChild(parent, child, sort);
}
protected insertAutoSortedChild(parent:Element|null, child:Instance, autoSort?:RawValue) {
child.__autoSort = autoSort;
if(child.__sort === undefined) this.insertChild(parent, child, autoSort);
}
protected addStyle(id:RawValue, attribute:RawValue, value:RawValue) {
let style = this._styles[id] || {__count: 0};
if(style[attribute]) throw new Error(`Cannot order multiple values per style '${id}' attribute '${attribute}'.`);
style[attribute] = value;
style.__count += 1;
this._styles[id] = style;
if(style.__count === 1) {
this._syntheticStyles[id] = this.decorateStyle(document.createElement("style"), id);
this._syntheticStyleContainer.appendChild(this._syntheticStyles[id]);
}
return style;
}
protected removeStyle(id:RawValue, attribute:RawValue) {
let style = this._styles[id];
if(!style) throw new Error(`Cannot remove attribute of nonexistent style '${id}'`);
delete style[attribute];
if(style.__count > 1) {
delete style[attribute];
style.__count -= 1;
} else {
let styleElem = this._syntheticStyles[id];
if(styleElem && styleElem.parentElement) styleElem.parentElement.removeChild(styleElem);
delete this._styles[id];
delete this._syntheticStyles[id];
}
}
protected styleToClass(styleId:RawValue):string {
return "s-" + md5(""+styleId).slice(16);
}
protected toCSS(style:Style):string {
let dummy = this._dummy;
// Clear previous values.
let dummyStyle = dummy.style;
for(let prop in dummyStyle) {
if(dummyStyle.hasOwnProperty(prop)) dummyStyle.removeProperty(prop);
}
for(let prop in style) {
dummyStyle.setProperty(prop, ""+style[prop]);
}
return dummy.getAttribute("style")!;
}
protected updateStyle(id:RawValue) {
let style = this._styles[id];
let styleElem = this._syntheticStyles[id];
if(!style) return;
if(!styleElem) throw new Error(`Missing style element for synthetic style '${id}'`);
let klass = this.styleToClass(id);
styleElem.textContent = `.${klass} {${this.toCSS(style)}}`;
}
protected focusElement(id:RawValue) {
let instances = this.getInstances(id);
if(!instances || !instances.length) throw new Error(`Unable to focus nonexistent element: '${id}'.`);
if(instances.length > 1) throw new Error(`Cannot assign focus to element with multiple instances: '${id}'.`);
if(instances[0].focus) instances[0].focus();
else console.warn(`Unable to focus element: '${id}' (element not focusable).`);
let eventId = createId();
this.program.inputEAVs([
[eventId, "tag", "html/event"],
[eventId, "tag", "html/event/trigger"],
[eventId, "trigger", "html/trigger/focus"],
[eventId, "element", id]
]);
}
protected blurElement(id:RawValue) {
let instances = this.getInstances(id);
for(let instance of instances || EMPTY) {
if(instance.blur) instance.blur();
else console.warn(`Unable to blur element: '${id}' (element not focusable).`);
}
let eventId = createId();
this.program.inputEAVs([
[eventId, "tag", "html/event"],
[eventId, "tag", "html/event/trigger"],
[eventId, "trigger", "html/trigger/blur"],
[eventId, "element", id]
]);
}
//////////////////////////////////////////////////////////////////////
// Handlers
//////////////////////////////////////////////////////////////////////
handlers = {
"export instances": handleTuples(({adds, removes}) => {
for(let [instanceId, elemId, tagname, ns] of removes || EMPTY) {
this.removeInstance(instanceId);
}
for(let [instanceId, elemId, tagname, ns] of adds || EMPTY) {
this.addInstance(instanceId, elemId, tagname, ns);
}
}),
"export roots": handleTuples(({adds}) => {
for(let [instanceId] of adds || EMPTY) {
if(!this._instances[instanceId]) throw new Error(`Instance '${instanceId}' cannot be promoted to root: no longer exists.`);
this.insertRoot(this._instances[instanceId]);
}
}),
"export parents": handleTuples(({adds, removes}) => {
for(let [instanceId, parentId] of removes || EMPTY) {
let instance = this._instances[instanceId];
let parent = this._instances[parentId];
if(!instance || !parent || parent != instance.parentElement) continue;
parent.removeChild(instance);
}
for(let [instanceId, parentId] of adds || EMPTY) {
let instance = this._instances[instanceId];
let parent = this._instances[parentId];
if(!instance || !parent) {
let msg = "";
if(!instance && !parent) msg = "could not find either instance or parent";
if(!instance) msg = "could not find instance";
if(!parent) msg = "could not find parent";
throw new Error(`Unable to reparent instance '${instanceId}' to '${parentId}', ${msg}.`);
}
this.insertChild(parent, instance, (instance.__sort !== undefined) ? instance.__sort : instance.__autoSort);
}
}),
"export styles": handleTuples(({adds, removes}) => {
let modified:RawMap<true> = {};
for(let [styleId, attribute] of removes || EMPTY) {
modified[styleId] = true;
this.removeStyle(styleId, attribute);
}
for(let [styleId, attribute, value] of adds || EMPTY) {
modified[styleId] = true;
this.addStyle(styleId, attribute, value);
}
for(let styleId of Object.keys(modified)) {
this.updateStyle(styleId);
}
}),
"export attributes": handleTuples(({adds, removes}) => {
for(let [e, a, v] of removes || EMPTY) {
let instance = this._instances[e];
if(!instance || a === "tagname" || a === "children" || a === "tag" || a === "ns" || a === "sort" || a === "eve-auto-index") continue;
else if(a === "text") instance.textContent = null
else if(a === "style") instance.classList.remove(this.styleToClass(v));
else if(a === "class") instance.classList.remove(""+v);
// else if(a === "value") (instance as any).value = ""; // @FIXME: This would be flicker-y if we then add something. :(
else instance.removeAttribute(""+a);
}
for(let [e, a, v] of adds || EMPTY) {
let instance = this._instances[e];
if(!instance) throw new Error(`Unable to add attribute to nonexistent instance '${e}' '${a}' '${v}'`);
if(a === "tagname" || a === "children" || a === "tag" || a === "ns") continue;
else if(a === "text") instance.textContent = ""+v;
else if(a === "style") instance.classList.add(this.styleToClass(v));
else if(a === "class") instance.classList.add(""+v);
else if(a === "value") (instance as any).value = ""+v;
else if(a === "sort") this.insertSortedChild(instance.parentElement, instance, v);
else if(a === "eve-auto-index") this.insertAutoSortedChild(instance.parentElement, instance, v);
else instance.setAttribute(""+a, ""+v);
}
}),
"export triggers": handleTuples(({adds}) => {
for(let [elemId, trigger] of adds || EMPTY) {
if(trigger === "html/trigger/focus") setImmediate(() => this.focusElement(elemId));
if(trigger === "html/trigger/blur") setImmediate(() => this.blurElement(elemId));
}
}),
"export listeners": handleTuples(({adds, removes}) => {
for(let [instanceId, listener] of removes || EMPTY) {
let instance = this._instances[instanceId];
if(!instance) continue;
if(!instance.__listeners) throw new Error(`Cannot remove never-added listener '${listener}' on instance '${instanceId}'.`);
else instance.__listeners[listener] = false;
}
for(let [instanceId, listener] of adds || EMPTY) {
let instance = this._instances[instanceId];
if(!instance) throw new Error(`Unable to add listener '${listener}' on nonexistent instance '${instanceId}'.`);
if(!instance.__listeners) instance.__listeners = {[listener]: true};
else instance.__listeners[listener] = true;
}
}),
"export captured keys": handleTuples(({adds, removes}) => {
for(let [instanceId, key] of removes || EMPTY) {
let instance = this._instances[instanceId];
if(!instance) continue;
if(!instance.__capturedKeys) throw new Error(`Cannot remove never-added captured key '${key}' on instance '${instanceId}'.`);
else {
let code = this._reverseKeyMap[key] || +key;
instance.__capturedKeys[code] = false;
}
}
for(let [instanceId, key] of adds || EMPTY) {
let instance = this._instances[instanceId];
if(!instance) throw new Error(`Unable to add captured key '${key}' on nonexistent instance '${instanceId}'.`);
let code = this._reverseKeyMap[key] || +key;
if(!instance.__capturedKeys) instance.__capturedKeys = {[code]: true};
else instance.__capturedKeys[code] = true;
}
})
};
//////////////////////////////////////////////////////////////////////
// Event Handlers
//////////////////////////////////////////////////////////////////////
_resizeTimeout: any; // @FIXME: what's up with this.
_resizeEventHandler(tagname:string) {
return (event:Event) => {
if(!this._resizeTimeout) {
this._resizeTimeout = setTimeout(() => {
this._resizeTimeout = null;
let width = window.innerWidth || document.documentElement.clientWidth;
let height = window.innerHeight || document.documentElement.clientHeight;
let eventId = createId();
let eavs:RawEAV[] = [
[eventId, "tag", "html/event"],
[eventId, "tag", `html/event/${tagname}`],
[eventId, "width", width],
[eventId, "height", height]
];
this._sendEvent(eavs);
}, 1000 / 5);
}
};
}
_mouseEventHandler(tagname:string) {
return (event:MouseEvent) => {
let {target} = event;
let eventId = createId();
let eavs:RawEAV[] = [
[eventId, "tag", "html/event"],
[eventId, "tag", `html/event/${tagname}`],
[eventId, "page-x", event.pageX],
[eventId, "page-y", event.pageY],
[eventId, "window-x", event.clientX],
[eventId, "window-y", event.clientY]
];
let button = event.button;
if(button === 0) eavs.push([eventId, "button", "left"]);
else if(button === 2) eavs.push([eventId, "button", "right"]);
else if(button === 1) eavs.push([eventId, "button", "middle"]);
else if(button) eavs.push([eventId, "button", button]);
if(this.isInstance(target)) {
eavs.push([eventId, "target", target.__element]);
}
let capturesContextMenu = false;
let anyInstances = false;
let current:Element|null = target as Element;
while(current && current != this._container) {
if(this.isInstance(current)) {
eavs.push([eventId, "element", current.__element]);
anyInstances = true;
if(button === 2 && current.__listeners && current.__listeners["html/listener/context-menu"] === true) {
capturesContextMenu = true;
}
}
current = current.parentElement;
}
// @NOTE: You'll get a mousedown but no mouseup for a right click if you don't capture the context menu,
// so we throw out the mousedown entirely in that case. :(
if(button === 2 && !capturesContextMenu) return;
if(anyInstances || current === this._container) this._sendEvent(eavs);
};
}
_captureContextMenuHandler() {
return (event:MouseEvent) => {
let captureContextMenu = false;
let current:Element|null = event.target as Element;
while(current && this.isInstance(current)) {
if(current.__listeners && current.__listeners["html/listener/context-menu"] === true) {
captureContextMenu = true;
}
current = current.parentElement;
}
if(captureContextMenu && event.button === 2) {
event.preventDefault();
}
};
}
_inputEventHandler(tagname:string) {
return (event:Event) => {
let target = event.target as (Instance & HTMLInputElement);
if(this.isInstance(target)) {
if(target.classList.contains("html-autosize-input")) {
target.size = target.value.length || 1;
}
let eventId = createId();
let eavs:RawEAV[] = [
[eventId, "tag", "html/event"],
[eventId, "tag", `html/event/${tagname}`],
[eventId, "element", target.__element],
[eventId, "value", target.value]
];
if(eavs.length) this._sendEvent(eavs);
}
}
}
_changeEventHandler(tagname:string) {
return (event:Event) => {
let target = event.target as (Instance & HTMLInputElement);
if(!(target instanceof HTMLInputElement)) return;
if(target.type == "checkbox" || target.type == "radio") {
if(this.isInstance(target)) {
let eventId = createId();
let eavs:RawEAV[] = [
[eventId, "tag", "html/event"],
[eventId, "tag", `html/event/${tagname}`],
[eventId, "element", target.__element],
[eventId, "checked", ""+target.checked]
];
let name = target.name;
if(target.type == "radio" && name !== undefined) {
let prev = this._checkedRadios[name];
if(prev && prev !== target.__element) {
// @NOTE: This is two events in one TX, a bit dangerous.
let event2Id = createId();
eavs.push(
[event2Id, "tag", "html/event"],
[event2Id, "tag", `html/event/${tagname}`],
[event2Id, "element", prev],
[event2Id, "checked", "false"]
);
}
this._checkedRadios[name] = target.__element;
}
if(eavs.length) this._sendEvent(eavs);
}
}
}
}
_keyMap:{[key:number]: string|undefined} = { // Overrides to provide sane names for common control codes.
9: "tab",
13: "enter",
16: "shift",
17: "control",
18: "alt",
27: "escape",
32: "space",
37: "left",
38: "up",
39: "right",
40: "down",
91: "meta"
}
_reverseKeyMap:{[name: string]: number|undefined} = Object.keys(this._keyMap).reduce((memo:any, code:string) => {
memo[this._keyMap[+code]!] = +code;
return memo;
}, {});
_keyEventHandler(tagname:string) {
return (event:KeyboardEvent) => {
if(event.repeat) return;
let target:Element|null = event.target as Element;
let code = event.keyCode;
let key = this._keyMap[code];
let eventId = createId();
let eavs:RawEAV[] = [
[eventId, "tag", "html/event"],
[eventId, "tag", `html/event/${tagname}`],
[eventId, "key-code", code]
];
if(key) eavs.push([eventId, "key", key]);
if(this.isInstance(target)) {
eavs.push([eventId, "target", target.__element]);
let current:Element|Instance|null = target;
while(current && current != this._container) {
if(this.isInstance(current)) {
eavs.push([eventId, "element", current.__element]);
if(current.__listeners && current.__listeners["html/listener/key"] && current.__capturedKeys && current.__capturedKeys[code]) {
event.preventDefault();
}
}
current = current.parentElement;
};
} else if ((target as any).__element) {
// If the target belongs to another program, bail.
return;
}
if(eavs.length) this._sendEvent(eavs);
};
}
_focusEventHandler(tagname:string) {
return (event:FocusEvent) => {
let target = event.target as (Instance & HTMLInputElement);
if(this.isInstance(target)) {
let eventId = createId();
let eavs:RawEAV[] = [
[eventId, "tag", "html/event"],
[eventId, "tag", `html/event/${tagname}`],
[eventId, "element", target.__element]
];
if(target.value !== undefined) eavs.push([eventId, "value", target.value]);
if(eavs.length) this._sendEvent(eavs);
}
}
}
_hoverEventHandler(tagname:string) {
return (event:MouseEvent) => {
let {target} = event;
if(!this.isInstance(target)) return;
let eavs:RawEAV[] = [];
let elemId = target.__element!;
if(target.__listeners && target.__listeners["html/listener/hover"]) {
let eventId = createId();
eavs.push(
[eventId, "tag", "html/event"],
[eventId, "tag", `html/event/${tagname}`],
[eventId, "element", elemId]
);
}
if(eavs.length) this._sendEvent(eavs);
};
}
}
Library.register(HTML.id, HTML);
(window as any)["lib"] = Library; | the_stack |
import { SceneNode } from 'scenegraph'
import * as consts from './consts'
import { GlobalVars } from './globals'
import {
getNodeNameAndStyle,
hasContentBounds,
isContentChild,
traverseNode,
} from './node'
import { getStyleFix } from './style'
import { approxEqual, asBool } from './tools'
/**
* nodeからスケールを考慮したglobalBoundsを取得する
* Artboardであった場合の、viewportHeightも考慮する
* ex,eyがつく
* ハッシュをつかわない
* @param node
* @return {{ex: number, ey: number, x: number, width: number, y: number, height: number}}
*/
export function getGlobalBounds(node): BoundsE {
const bounds = node.globalBounds
// Artboardにあるスクロール領域のボーダー
const viewPortHeight = node.viewportHeight
if (viewPortHeight != null) bounds.height = viewPortHeight
return {
x: bounds.x * GlobalVars.scale,
y: bounds.y * GlobalVars.scale,
width: bounds.width * GlobalVars.scale,
height: bounds.height * GlobalVars.scale,
ex: (bounds.x + bounds.width) * GlobalVars.scale,
ey: (bounds.y + bounds.height) * GlobalVars.scale,
}
}
/**
* nodeからスケールを考慮したglobalDrawBoundsを取得する
* Artboardであった場合の、viewportHeightも考慮する
* ex,eyがつく
* ハッシュをつかわないで取得する
* Textのフォントサイズ情報など、描画サイズにかかわるものを取得する
* アートボードの伸縮でサイズが変わってしまうために退避できるように
*/
export function getGlobalDrawBounds(node): BoundsE {
let bounds = node.globalDrawBounds
const viewPortHeight = node.viewportHeight
if (viewPortHeight != null) bounds.height = viewPortHeight
let b = {
x: bounds.x * GlobalVars.scale,
y: bounds.y * GlobalVars.scale,
width: bounds.width * GlobalVars.scale,
height: bounds.height * GlobalVars.scale,
ex: (bounds.x + bounds.width) * GlobalVars.scale,
ey: (bounds.y + bounds.height) * GlobalVars.scale,
}
return b
}
/**
* リサイズされる前のグローバル座標とサイズを取得する
* @param {SceneNode|SceneNodeClass} node
* @return {{ex: number, ey: number, x: number, width: number, y: number, height: number}}
*/
export function getBeforeGlobalBounds(node): BoundsE {
const hashBounds = GlobalVars.responsiveBounds
let bounds = null
if (hashBounds != null) {
const hBounds = hashBounds[node.guid]
if (hBounds && hBounds.before) {
bounds = Object.assign({}, hBounds.before.global_bounds)
}
}
if (bounds) return bounds
console.log(
'**error** リサイズ前のGlobalBoundsの情報がありません' + node.name,
)
return null
}
function getBeforeTextFontSize(node: SceneNode) {
const hBounds = GlobalVars.responsiveBounds[node.guid]
return hBounds.before.text_font_size
}
/**
* GlobalBoundsでのレスポンシブパラメータの取得
* @param {SceneNode|SceneNodeClass} node
*/
export function getRectTransform(node: SceneNode): RectTransform {
const bounds = GlobalVars.responsiveBounds[node.guid]
return bounds ? bounds.responsiveParameterGlobal : null
}
interface Vector2 {
x: number
y: number
}
interface RectTransform {
fix: {
left: number | boolean | null
right: number | boolean | null
top: number | boolean | null
bottom: number | boolean | null
width: number | boolean | null
height: number | boolean | null
}
pivot: Vector2
anchor_min: Vector2
anchor_max: Vector2
offset_min: Vector2
offset_max: Vector2
}
function calcRect(
parentBeforeBounds,
beforeBounds,
horizontalConstraints,
verticalConstraints,
style,
): RectTransform {
// console.log(`----------------------${node.name}----------------------`)
// null:わからない
// true:フィックスで確定
// false:フィックスされていないで確定 いずれ数字に変わる
let styleFixWidth: boolean | null = null
let styleFixHeight: boolean | null = null
let styleFixTop: boolean | null = null
let styleFixBottom: boolean | null = null
let styleFixLeft: boolean | null = null
let styleFixRight: boolean | null = null
const styleFix = style.values(consts.STYLE_FIX)
if (styleFix != null) {
// オプションが設定されたら、全ての設定が決まる(NULLではなくなる)
const fix = getStyleFix(styleFix)
// console.log(node.name, 'のfixが設定されました', fix)
styleFixWidth = fix.width
styleFixHeight = fix.height
styleFixTop = fix.top
styleFixBottom = fix.bottom
styleFixLeft = fix.left
styleFixRight = fix.right
}
if (!horizontalConstraints || !verticalConstraints) {
// BooleanGroupの子供,RepeatGridの子供等、情報がとれないものがある
// console.log(`${node.name} constraints情報がありません`)
}
//console.log(`${node.name} constraints`)
//console.log(horizontalConstraints)
//console.log(verticalConstraints)
if (styleFixLeft == null && horizontalConstraints != null) {
//styleFixLeft = approxEqual(beforeLeft, afterLeft)
styleFixLeft =
horizontalConstraints.position === consts.FIXED_LEFT ||
horizontalConstraints.position === consts.FIXED_BOTH
}
if (styleFixRight == null && horizontalConstraints != null) {
//styleFixRight = approxEqual(beforeRight, afterRight)
styleFixRight =
horizontalConstraints.position === consts.FIXED_RIGHT ||
horizontalConstraints.position === consts.FIXED_BOTH
}
if (styleFixTop == null && verticalConstraints != null) {
// styleFixTop = approxEqual(beforeTop, afterTop)
styleFixTop =
verticalConstraints.position === consts.FIXED_TOP ||
verticalConstraints.position === consts.FIXED_BOTH
}
if (styleFixBottom == null && verticalConstraints != null) {
// styleFixBottom = approxEqual(beforeBottom, afterBottom)
styleFixBottom =
verticalConstraints.position === consts.FIXED_BOTTOM ||
verticalConstraints.position === consts.FIXED_BOTH
}
if (styleFixWidth == null && horizontalConstraints != null) {
//styleFixWidth = approxEqual(beforeBounds.width, afterBounds.width)
styleFixWidth = horizontalConstraints.size === consts.SIZE_FIXED
}
if (styleFixHeight == null && verticalConstraints != null) {
// styleFixHeight = approxEqual(beforeBounds.height, afterBounds.height)
styleFixHeight = verticalConstraints.size === consts.SIZE_FIXED
}
// ここまでに
// fixOptionWidth,fixOptionHeight : boolean
// fixOptionTop,fixOptionBottom : boolean
// fixOptionLeft,fixOptionRight : boolean
// true: 固定されている
// false: 固定されていない
// number: 辺の位置割合
// になっていないといけない
const leftRate =
(beforeBounds.x - parentBeforeBounds.x) / parentBeforeBounds.width
const rightRate =
(parentBeforeBounds.ex - beforeBounds.ex) / parentBeforeBounds.width
const topRate =
(beforeBounds.y - parentBeforeBounds.y) / parentBeforeBounds.height
const bottomRate =
(parentBeforeBounds.ey - beforeBounds.ey) / parentBeforeBounds.height
// anchorの値を決める
// null: 定義されていない widthかheightが固定されている
// number: 親に対しての割合 anchorに割合をいれ、offsetを0
// true: 固定されている anchorを0か1にし、offsetをピクセルで指定
// console.log("left:" + fixOptionLeft, "right:" + fixOptionRight)
// console.log("top:" + fixOptionTop, "bottom:" + fixOptionBottom)
// console.log("width:" + fixOptionWidth, "height:" + fixOptionHeight)
let pivot: Vector2 = { x: 0.5, y: 0.5 }
let offsetMin: Vector2 = {
x: null,
y: null,
} // left(x), bottom(h)
let offsetMax: Vector2 = {
x: null,
y: null,
} // right(w), top(y)
let anchorMin: Vector2 = { x: null, y: null } // left, bottom
let anchorMax: Vector2 = { x: null, y: null } // right, top
// レスポンシブパラメータが不確定のままきた場合
// RepeatGrid以下のコンポーネント,NULLになる
if (styleFixWidth === null || styleFixHeight === null) {
// console.log("fix情報がありませんでした", node.name)
const beforeCenter = beforeBounds.x + beforeBounds.width / 2
const parentBeforeCenter =
parentBeforeBounds.x + parentBeforeBounds.width / 2
anchorMin.x = anchorMax.x =
(beforeCenter - parentBeforeCenter) / parentBeforeBounds.width + 0.5
// サイズを設定 センターからの両端サイズ
offsetMin.x = -beforeBounds.width / 2
offsetMax.x = +beforeBounds.width / 2
const beforeMiddle = beforeBounds.y + beforeBounds.height / 2
const parentBeforeMiddle =
parentBeforeBounds.y + parentBeforeBounds.height / 2
anchorMin.y = anchorMax.y =
-(beforeMiddle - parentBeforeMiddle) / parentBeforeBounds.height + 0.5
offsetMin.y = -beforeBounds.height / 2
offsetMax.y = +beforeBounds.height / 2
return {
fix: {
left: styleFixLeft,
right: styleFixRight,
top: styleFixTop,
bottom: styleFixBottom,
width: styleFixWidth,
height: styleFixHeight,
},
pivot: { x: 0.5, y: 0.5 },
anchor_min: anchorMin,
anchor_max: anchorMax,
offset_min: offsetMin,
offset_max: offsetMax,
}
}
if (styleFixWidth) {
// 横幅が固定されている
// AnchorMin.xとAnchorMax.xは同じ値になる(親の大きさに左右されない)
// <-> これが違う値の場合、横幅は親に依存に、それにoffset値を加算した値になる
// -> pivotでoffsetの値はかわらない
// offsetMin.yとoffsetMax.yの距離がHeight
if (styleFixLeft !== true && styleFixRight !== true) {
//左右共ロックされていない
anchorMin.x = anchorMax.x = (leftRate + 1 - rightRate) / 2
offsetMin.x = -beforeBounds.width / 2
offsetMax.x = beforeBounds.width / 2
} else if (styleFixLeft === true && styleFixRight !== true) {
// 親のX座標から、X座標が固定値できまる
anchorMin.x = 0
anchorMax.x = 0
offsetMin.x = beforeBounds.x - parentBeforeBounds.x
offsetMax.x = offsetMin.x + beforeBounds.width
} else if (styleFixLeft !== true && styleFixRight === true) {
// 親のX座標から、X座標が固定値できまる
anchorMin.x = 1
anchorMax.x = 1
offsetMax.x = beforeBounds.ex - parentBeforeBounds.ex
offsetMin.x = offsetMax.x - beforeBounds.width
} else {
// 不確定な設定
// 1)サイズが固定、左右固定されている
// 2)サイズが固定されているが、どちらも実数
// サイズ固定で、位置が親の中心にたいして、絶対値できまるようにする
// console.log( `${node.name} fix-right(${styleFixRight}) & fix-left(${styleFixLeft}) & fix-width(${styleFixWidth})`)
anchorMin.x = anchorMax.x = 0.5
const parentCenterX = parentBeforeBounds.x + parentBeforeBounds.width / 2
const centerX = beforeBounds.x + beforeBounds.width / 2
const offsetX = centerX - parentCenterX
offsetMin.x = offsetX - beforeBounds.width / 2
offsetMax.x = offsetX + beforeBounds.width / 2
}
} else {
if (styleFixLeft === true) {
// 親のX座標から、X座標が固定値できまる
anchorMin.x = 0
offsetMin.x = beforeBounds.x - parentBeforeBounds.x
} else {
anchorMin.x = leftRate
offsetMin.x = 0
}
if (styleFixRight === true) {
// 親のX座標から、X座標が固定値できまる
anchorMax.x = 1
offsetMax.x = beforeBounds.ex - parentBeforeBounds.ex
} else {
anchorMax.x = 1 - rightRate
offsetMax.x = 0
}
}
// AdobeXD と Unity2D でY軸の向きがことなるため、Top→Max Bottom→Min
if (styleFixHeight) {
// 高さが固定されている
// AnchorMin.yとAnchorMax.yは同じ値になる(親の大きさに左右されない)
// <-> これが違う値の場合、高さは親に依存に、それにoffset値を加算した値になる つまりpivotでoffsetの値はかわらない
// offsetMin.yとoffsetMax.yの距離がHeight
if (styleFixTop !== true && styleFixBottom !== true) {
//両方共ロックされていない
anchorMin.y = anchorMax.y = 1 - (topRate + 1 - bottomRate) / 2
offsetMin.y = -beforeBounds.height / 2
offsetMax.y = beforeBounds.height / 2
} else if (styleFixTop === true && styleFixBottom !== true) {
// 親のY座標から、Y座標が固定値できまる
anchorMax.y = 1
anchorMin.y = 1
offsetMax.y = -(beforeBounds.y - parentBeforeBounds.y)
offsetMin.y = offsetMax.y - beforeBounds.height
} else if (styleFixTop !== true && styleFixBottom === true) {
// 親のY座標から、Y座標が固定値できまる
anchorMin.y = 0
anchorMax.y = anchorMin.y
offsetMin.y = -(beforeBounds.ey - parentBeforeBounds.ey)
offsetMax.y = offsetMin.y + beforeBounds.height
} else {
// 不正な設定
// サイズが固定されて、上下固定されている
// 上下共ロックされていない と同じ設定をする
anchorMin.y = anchorMax.y = 1 - (topRate + 1 - bottomRate) / 2
offsetMin.y = -beforeBounds.height / 2
offsetMax.y = beforeBounds.height / 2
// 不確定な設定
// 1)サイズが固定、左右固定されている
// 2)サイズが固定されているが、どちらも実数
// サイズ固定で、位置が親の中心にたいして、絶対値できまるようにする
// console.log(`${node.name} fix-right(${styleFixRight}) & fix-left(${styleFixLeft}) & fix-width(${styleFixWidth})`)
anchorMin.y = anchorMax.y = 0.5
const parentCenterY = parentBeforeBounds.y + parentBeforeBounds.height / 2
const centerY = beforeBounds.y + beforeBounds.height / 2
const offsetY = -centerY + parentCenterY
offsetMin.y = offsetY - beforeBounds.height / 2
offsetMax.y = offsetY + beforeBounds.height / 2
}
} else {
if (styleFixTop === true) {
// 親のY座標から、Y座標が固定値できまる
anchorMax.y = 1
offsetMax.y = -(beforeBounds.y - parentBeforeBounds.y)
} else {
anchorMax.y = 1 - topRate
offsetMax.y = 0
}
if (styleFixBottom === true) {
// 親のY座標から、Y座標が固定値できまる
anchorMin.y = 0
offsetMin.y = -(beforeBounds.ey - parentBeforeBounds.ey)
} else {
anchorMin.y = bottomRate
offsetMin.y = 0
}
}
if (style.hasValue(consts.STYLE_FIX, 'c', 'center')) {
const beforeCenter = beforeBounds.x + beforeBounds.width / 2
const parentBeforeCenter =
parentBeforeBounds.x + parentBeforeBounds.width / 2
anchorMin.x = anchorMax.x =
(beforeCenter - parentBeforeCenter) / parentBeforeBounds.width + 0.5
// サイズを設定 センターからの両端サイズ
offsetMin.x = -beforeBounds.width / 2
offsetMax.x = +beforeBounds.width / 2
}
if (style.hasValue(consts.STYLE_FIX, 'm', 'middle')) {
const beforeMiddle = beforeBounds.y + beforeBounds.height / 2
const parentBeforeMiddle =
parentBeforeBounds.y + parentBeforeBounds.height / 2
anchorMin.y = anchorMax.y =
-(beforeMiddle - parentBeforeMiddle) / parentBeforeBounds.height + 0.5
offsetMin.y = -beforeBounds.height / 2
offsetMax.y = +beforeBounds.height / 2
}
// pivotの設定 固定されている方向にあわせる
if (styleFixLeft === true && styleFixRight !== true) {
pivot.x = 0
} else if (styleFixLeft !== true && styleFixRight === true) {
pivot.x = 1
}
if (styleFixTop === true && styleFixBottom !== true) {
pivot.y = 1
} else if (styleFixTop !== true && styleFixBottom === true) {
pivot.y = 0
}
return {
fix: {
left: styleFixLeft,
right: styleFixRight,
top: styleFixTop,
bottom: styleFixBottom,
width: styleFixWidth,
height: styleFixHeight,
},
pivot,
anchor_min: anchorMin,
anchor_max: anchorMax,
offset_min: offsetMin,
offset_max: offsetMax,
}
}
/**
* 本当に正確なレスポンシブパラメータは、シャドウなどエフェクトを考慮し、どれだけ元サイズより
大きくなるか最終アウトプットのサイズを踏まえて計算する必要がある
calcResonsiveParameter内で、判断する必要があると思われる
* 自動で取得されたレスポンシブパラメータは、optionの @Pivot @StretchXで上書きされる
fix: {
// ロック true or ピクセル数
left: fixOptionLeft,
right: fixOptionRight,
top: fixOptionTop,
bottom: fixOptionBottom,
width: fixOptionWidth,
height: fixOptionHeight,
},
anchor_min: anchorMin,
anchor_max: anchorMax,
offset_min: offsetMin,
offset_max: offsetMax,
* @param {SceneNode|SceneNodeClass} node
* @param calcDrawBounds
* @return {null}
*/
function calcDrawRectTransform(node, calcDrawBounds = true) {
if (!node || !node.parent) return null
const bounds = GlobalVars.responsiveBounds[node.guid]
if (!bounds || !bounds.before || !bounds.after) return null
const parentBounds = GlobalVars.responsiveBounds[node.parent.guid]
if (!parentBounds || !parentBounds.before || !parentBounds.after) return null
const beforeGlobalBounds = bounds.before.global_bounds
const beforeGlobalDrawBounds = bounds.before.global_draw_bounds
const parentBeforeGlobalBounds =
parentBounds.before.content_global_bounds ||
parentBounds.before.global_bounds
const parentBeforeGlobalDrawBounds =
parentBounds.before.content_global_draw_bounds ||
parentBounds.before.global_draw_bounds
const afterGlobalBounds = bounds.after.global_bounds
const afterGlobalDrawBounds = bounds.after.global_draw_bounds
const parentAfterGlobalBounds =
parentBounds.after.content_global_bounds || parentBounds.after.global_bounds
const parentAfterGlobalDrawBounds =
parentBounds.after.content_global_draw_bounds ||
parentBounds.after.global_draw_bounds
const beforeBounds = calcDrawBounds
? beforeGlobalDrawBounds
: beforeGlobalBounds
const afterBounds = calcDrawBounds ? afterGlobalDrawBounds : afterGlobalBounds
//content_global_boundsは、親がマスク持ちグループである場合、グループ全体のBoundsになる
const parentBeforeBounds = calcDrawBounds
? parentBeforeGlobalDrawBounds
: parentBeforeGlobalBounds
const parentAfterBounds = calcDrawBounds
? parentAfterGlobalDrawBounds
: parentAfterGlobalBounds
// fix を取得するため
// TODO: anchor スタイルのパラメータはとるべきでは
const style = getNodeNameAndStyle(node).style
const horizontalConstraints = node.horizontalConstraints
const verticalConstraints = node.verticalConstraints
return calcRect(
parentBeforeBounds,
beforeBounds,
horizontalConstraints,
verticalConstraints,
style,
)
}
function calcRectTransform(node) {
if (!node || !node.parent) return null
const bounds = GlobalVars.responsiveBounds[node.guid]
if (!bounds || !bounds.before || !bounds.after) return null
const parentBounds = GlobalVars.responsiveBounds[node.parent.guid]
if (!parentBounds || !parentBounds.before || !parentBounds.after) return null
const beforeGlobalBounds = bounds.before.global_bounds
const parentBeforeGlobalBounds =
parentBounds.before.content_global_bounds ||
parentBounds.before.global_bounds
// fix を取得するため
// TODO: anchor スタイルのパラメータはとるべきでは
const style = getNodeNameAndStyle(node).style
const horizontalConstraints = node.horizontalConstraints
const verticalConstraints = node.verticalConstraints
return calcRect(
parentBeforeGlobalBounds,
beforeGlobalBounds,
horizontalConstraints,
verticalConstraints,
style,
)
}
class MinMaxSize {
public minWidth: number | null
public minHeight: number | null
public maxWidth: number | null
public maxHeight: number | null
constructor() {
this.minWidth = null
this.minHeight = null
this.maxWidth = null
this.maxHeight = null
}
addSize(w, h) {
if (this.minWidth == null || this.minWidth > w) {
this.minWidth = w
}
if (this.maxWidth == null || this.maxWidth < w) {
this.maxWidth = w
}
if (this.minHeight == null || this.minHeight > h) {
this.minHeight = h
}
if (this.maxHeight == null || this.maxHeight < h) {
this.maxHeight = h
}
}
}
class CalcBounds {
private sx: number
private sy: number
private ex: number
private ey: number
constructor() {
this.sx = null
this.sy = null
this.ex = null
this.ey = null
}
addBoundsParam(x, y, w, h) {
if (this.sx == null || this.sx > x) {
this.sx = x
}
if (this.sy == null || this.sy > y) {
this.sy = y
}
const ex = x + w
const ey = y + h
if (this.ex == null || this.ex < ex) {
this.ex = ex
}
if (this.ey == null || this.ey < ey) {
this.ey = ey
}
}
/**
* @param {Bounds} bounds
*/
addBounds(bounds) {
this.addBoundsParam(bounds.x, bounds.y, bounds.width, bounds.height)
}
/**
* @returns {Bounds}
*/
get bounds(): BoundsE {
return {
x: this.sx,
y: this.sy,
width: this.ex - this.sx,
height: this.ey - this.sy,
ex: this.ex,
ey: this.ey,
}
}
}
/**
* 子供(コンポーネント化するもの・withoutNodeを除く)の全体サイズと
* 子供の中での最大Width、Heightを取得する
* 注意:保存されたBounds情報をつかわず、現在のサイズを取得する
* @param {SceneNode[]} nodes
* @returns {{node_max_height: number, node_max_width: number, global_bounds: Bounds, global_draw_bounds: Bounds}}
*/
function calcGlobalBounds(nodes) {
// console.log(`calcGlobalBounds(${nodes})`)
if (!nodes || nodes.length === 0)
return {
global_bounds: null,
global_draw_bounds: null,
node_max_width: null,
node_max_height: null,
}
let childrenCalcBounds = new CalcBounds()
let childrenCalcDrawBounds = new CalcBounds()
// セルサイズを決めるため最大サイズを取得する
let childrenMinMaxSize = new MinMaxSize()
function addNode(node) {
/* 以下のコードは、nodeが、親のマスクにはいっているかどうかの判定のためのテストコード
if (!testBounds(viewportBounds, childBounds)) {
console.log(child.name + 'はViewportにはいっていない')
return false // 処理しない
}
*/
const childBounds = node.globalDrawBounds
childrenCalcBounds.addBounds(childBounds)
const childDrawBounds = node.globalDrawBounds
childrenCalcDrawBounds.addBounds(childDrawBounds)
childrenMinMaxSize.addSize(childBounds.width, childBounds.height)
}
for (let node of nodes) {
addNode(node)
}
return {
global_bounds: childrenCalcBounds.bounds,
global_draw_bounds: childrenCalcDrawBounds.bounds,
node_max_width: childrenMinMaxSize.maxWidth * GlobalVars.scale,
node_max_height: childrenMinMaxSize.maxHeight * GlobalVars.scale,
}
}
interface BoundsE {
x: number
y: number
width: number
height: number
ex: number
ey: number
}
class GlobalBounds {
public visible: boolean
public global_bounds: BoundsE
public global_draw_bounds: BoundsE
public content_global_bounds: BoundsE
public content_global_draw_bounds: BoundsE
public viewport_content_global_bounds: BoundsE
public viewport_content_global_draw_bounds: BoundsE
public text_font_size: number | null
/**
* @param {SceneNodeClass} node
*/
constructor(node) {
if (node == null) return
this.visible = node.visible
this.global_bounds = getGlobalBounds(node)
this.global_draw_bounds = getGlobalDrawBounds(node)
// console.log('node.constructor.name:' + node.constructor.name)
if (node.constructor.name === 'Text') {
this.text_font_size = node.fontSize
}
if (hasContentBounds(node)) {
// Mask(もしくはViewport)をふくむ、含まないで、それぞれのBoundsが必要
// マスクありでBoundsが欲しいとき → 全体コンテンツBoundsがほしいとき とくに、Childrenが大幅にかたよっているときなど
// マスク抜きでBoundsが欲しいとき → List内コンテンツのPaddingの計算
const { style } = getNodeNameAndStyle(node)
const contents = node.children.filter(child => {
return isContentChild(child)
})
const contentBounds = calcGlobalBounds(contents)
this.content_global_bounds = contentBounds.global_bounds
this.content_global_draw_bounds = contentBounds.global_draw_bounds
const viewport = getViewport(node)
if (viewport) {
const viewportContents = contents.concat(viewport)
const viewportContentsBounds = calcGlobalBounds(viewportContents)
this.viewport_content_global_bounds =
viewportContentsBounds.global_bounds
this.viewport_content_global_draw_bounds =
viewportContentsBounds.global_draw_bounds
}
}
}
}
export class BoundsToRectTransform {
private readonly node: SceneNode
public before: GlobalBounds
public after: GlobalBounds
private restore: GlobalBounds
public responsiveParameter: RectTransform
public responsiveParameterGlobal: RectTransform
constructor(node) {
this.node = node
}
updateBeforeBounds() {
// Before
this.before = new GlobalBounds(this.node)
}
updateAfterBounds() {
this.after = new GlobalBounds(this.node)
{
const beforeX = this.before.global_bounds.x
const beforeDrawX = this.before.global_draw_bounds.x
const beforeDrawSizeX = beforeDrawX - beforeX
const afterX = this.after.global_bounds.x
const afterDrawX = this.after.global_draw_bounds.x
const afterDrawSizeX = afterDrawX - afterX
// global
if (!approxEqual(beforeDrawSizeX, afterDrawSizeX)) {
console.log(
`${this.node.name} ${beforeDrawSizeX -
afterDrawSizeX}リサイズ後のBounds.x取得が正確ではないようです`,
)
// beforeのサイズ差をもとに、afterを修正する
this.after.global_draw_bounds.x =
this.after.global_bounds.x + beforeDrawSizeX
}
}
{
const beforeY = this.before.global_bounds.y
const beforeDrawY = this.before.global_draw_bounds.y
const beforeDrawSizeY = beforeDrawY - beforeY
const afterY = this.after.global_bounds.y
const afterDrawY = this.after.global_draw_bounds.y
const afterDrawSizeY = afterDrawY - afterY
if (!approxEqual(beforeDrawSizeY, afterDrawSizeY)) {
console.log(
`${this.node.name} ${beforeDrawSizeY -
afterDrawSizeY}リサイズ後のBounds.y取得がうまくいっていないようです`,
)
// beforeのサイズ差をもとに、afterを修正する
this.after.global_draw_bounds.y =
this.after.global_bounds.y + beforeDrawSizeY
}
}
{
const beforeX = this.before.global_bounds.ex
const beforeDrawX = this.before.global_draw_bounds.ex
const beforeDrawSizeX = beforeDrawX - beforeX
const afterX = this.after.global_bounds.ex
const afterDrawX = this.after.global_draw_bounds.ex
const afterDrawSizeX = afterDrawX - afterX
if (!approxEqual(beforeDrawSizeX, afterDrawSizeX)) {
console.log(
`${this.node.name} ${beforeDrawSizeX -
afterDrawSizeX}リサイズ後のBounds.ex取得がうまくいっていないようです`,
)
// beforeのサイズ差をもとに、afterを修正する
this.after.global_draw_bounds.ex =
this.after.global_bounds.ex + beforeDrawSizeX
}
}
{
const beforeY = this.before.global_bounds.ey
const beforeDrawY = this.before.global_draw_bounds.ey
const beforeDrawSizeY = beforeDrawY - beforeY
const afterY = this.after.global_bounds.ey
const afterDrawY = this.after.global_draw_bounds.ey
const afterDrawSizeY = afterDrawY - afterY
if (!approxEqual(beforeDrawSizeY, afterDrawSizeY)) {
console.log(
`${this.node.name} ${beforeDrawSizeY -
afterDrawSizeY}リサイズ後のBounds.ey取得がうまくいっていないようです`,
)
// beforeのサイズ差をもとに、afterを修正する
this.after.global_draw_bounds.ey =
this.after.global_bounds.ey + beforeDrawSizeY
}
}
this.after.global_draw_bounds.width =
this.after.global_draw_bounds.ex - this.after.global_draw_bounds.x
this.after.global_draw_bounds.height =
this.after.global_draw_bounds.ey - this.after.global_draw_bounds.y
}
updateRestoreBounds() {
this.restore = new GlobalBounds(this.node)
}
calcRectTransform() {
// DrawBoundsでのレスポンシブパラメータ(場合によっては不正確)
this.responsiveParameter = calcDrawRectTransform(this.node)
// GlobalBoundsでのレスポンシブパラメータ(場合によっては不正確)
this.responsiveParameterGlobal = calcDrawRectTransform(this.node, false)
}
}
export async function makeGlobalBoundsRectTransform(root) {
// 現在のboundsを取得する
traverseNode(root, node => {
let param = new BoundsToRectTransform(node)
param.updateBeforeBounds()
GlobalVars.responsiveBounds[node.guid] = param
})
const rootWidth = root.globalBounds.width
const rootHeight = root.globalBounds.height
// リサイズは大きくなるほうでする
// リピートグリッドが小さくなったとき、みえなくなるものがでてくる可能性がある
// そうなると、リサイズ前後での比較ができなくなる
const resizePlusWidth = 0
const resizePlusHeight = 0
// rootのリサイズ
const viewportHeight = root.viewportHeight // viewportの高さの保存
// root.resize(rootWidth + resizePlusWidth, rootHeight + resizePlusHeight)
if (viewportHeight) {
// viewportの高さを高さが変わった分の変化に合わせる
root.viewportHeight = viewportHeight + resizePlusHeight
}
// ここでダイアログをだすと、Artboradをひきのばしたところで、どう変化したか見ることができる
// await fs.getFileForSaving('txt', { types: ['txt'] })
// 変更されたboundsを取得する
traverseNode(root, node => {
let bounds =
GlobalVars.responsiveBounds[node.guid] ||
(GlobalVars.responsiveBounds[node.guid] = new BoundsToRectTransform(node))
bounds.updateAfterBounds()
})
// Artboardのサイズを元に戻す
// root.resize(rootWidth, rootHeight)
if (viewportHeight) {
root.viewportHeight = viewportHeight
}
// 元に戻ったときのbounds
traverseNode(root, node => {
GlobalVars.responsiveBounds[node.guid].updateRestoreBounds()
})
// レスポンシブパラメータの生成
for (let key in GlobalVars.responsiveBounds) {
GlobalVars.responsiveBounds[key].calcRectTransform() // ここまでに生成されたデータが必要
}
}
/**
* Viewportの役割をもつノードを返す
* Maskをもっている場合はMask
* @param node
* @return {null|SceneNode|{show_mask_graphic: boolean}|string|*}
*/
function getViewport(node) {
const { style } = getNodeNameAndStyle(node)
const styleViewport = style.first(consts.STYLE_CREATE_CONTENT)
if (asBool(styleViewport)) return node
if (node.mask) return node.mask
if (node.constructor.name === 'RepeatGrid') return node
return null
} | the_stack |
import { Options } from './options'
import { modal } from './tools'
const options = new Options()
let optionsInfo: optionsInfo
const dDiv = <HTMLDivElement>document.querySelector('#ddd')
const loginDiv = <HTMLDivElement>document.querySelector('#login')
const optionDiv = <HTMLDivElement>document.querySelector('#option')
const advOptionDiv = <HTMLDivElement>document.querySelector('#advOption')
const configDiv = <HTMLDivElement>document.querySelector('#config')
const advConfigDiv = <HTMLDivElement>document.querySelector('#advConfig')
const utilDiv = <HTMLDivElement>document.querySelector('#util')
const userDiv = <HTMLDivElement>document.querySelector('#user')
const logDiv = <HTMLDivElement>document.querySelector('#log')
const changeNetkeyDiv = <HTMLDivElement>document.querySelector('#changeNetkey')
const advOptionReturnButton = <HTMLElement>document.querySelector('#optionReturn')
const netkeyReturnButton = <HTMLElement>document.querySelector('#netkeyReturn')
const returnButton = <HTMLElement>document.querySelector('#logreturn')
const template = <HTMLDivElement>document.querySelector('#template')
declare const window: any
$('[data-toggle="tooltip"]').tooltip()
// 3D效果
let firstDiv: HTMLDivElement = loginDiv
let secondDiv: HTMLDivElement
const dddArray = ['top', 'bottom', 'left', 'right']
let dddString: string
function getRandomIntInclusive(min: number, max: number) {
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min + 1)) + min
}
function danimation(toDiv: HTMLDivElement) {
dddString = dddArray[getRandomIntInclusive(0, 3)]
if (firstDiv === logDiv) returnButton.classList.add('d-none')
secondDiv = toDiv
secondDiv.classList.add(`d_${dddString}2`)
secondDiv.classList.remove('d-none')
firstDiv.classList.add(`d_${dddString}1`)
dDiv.className = `ddd_${dddString}`
}
dDiv.addEventListener('animationend', () => {
dDiv.className = ''
firstDiv.classList.remove(`d_${dddString}1`)
firstDiv.classList.add('d-none')
secondDiv.classList.remove(`d_${dddString}2`)
firstDiv = secondDiv
if (firstDiv === logDiv) returnButton.classList.remove('d-none')
})
/**
* 显示登录界面
*
*/
function showLogin() {
const pathInput = <HTMLInputElement>loginDiv.querySelector('#path input')
const protocolInput = <HTMLInputElement>loginDiv.querySelector('#protocol input[type="text"]')
const netkeyInput = <HTMLInputElement>loginDiv.querySelector('#netkey input[name="netkey"]')
const connectButton = <HTMLElement>loginDiv.querySelector('#connect button')
const connectSpan = <HTMLSpanElement>loginDiv.querySelector('#connect span')
if (location.hash !== '') {
const loginInfo = location.hash.match(/path=(.*)&protocol=(.*)/)
if (loginInfo !== null) {
pathInput.value = loginInfo[1]
protocolInput.value = loginInfo[2]
} else {
pathInput.value = localStorage.getItem('path') || pathInput.value
protocolInput.value = localStorage.getItem('protocol') || protocolInput.value
}
} else {
pathInput.value = localStorage.getItem('path') || pathInput.value
protocolInput.value = localStorage.getItem('protocol') || protocolInput.value
}
connectButton.onclick = async () => {
const protocols = [protocolInput.value]
localStorage.setItem('path', pathInput.value)
localStorage.setItem('protocol', protocolInput.value)
window.netkey = netkeyInput.value
const connected = await options.connect(pathInput.value, protocols)
if (connected) login()
else connectSpan.innerText = '连接失败'
}
loginDiv.classList.remove('d-none')
}
/**
* 登录成功
*
*/
async function login() {
const infoMSG = await options.getInfo()
optionsInfo = infoMSG.data
// 处理错误信息
options.onerror = (event) => {
modal({ body: event.data })
}
options.onwserror = () => wsClose('连接发生错误')
options.onwsclose = (event) => {
try {
const msg: message = JSON.parse(event.reason)
wsClose('连接已关闭 ' + msg.msg)
} catch (error) {
wsClose('连接已关闭')
}
}
danimation(optionDiv)
await showConfig()
await showAdvOption()
await showUser()
await showUtil()
showLog()
showChangeNetkey()
}
/**
* 加载全局设置
*
*/
async function showConfig() {
const saveConfigButton = <HTMLElement>document.querySelector('#saveConfig')
const addUserButton = <HTMLElement>document.querySelector('#addUser')
const showAdvButton = <HTMLElement>document.querySelector('#showAdvOption')
const showLogButton = <HTMLElement>document.querySelector('#showLog')
const showChangeNetkeyButton = <HTMLElement>document.querySelector('#showChangeNetkey')
const configMSG = await options.getConfig()
let config = configMSG.data
const configDF = getConfigTemplate(config)
// 保存全局设置
saveConfigButton.onclick = async () => {
modal()
const configMSG = await options.setConfig(config)
if (configMSG.msg != null) modal({ body: configMSG.msg })
else {
config = configMSG.data
const configDF = getConfigTemplate(config)
configDiv.innerText = ''
configDiv.appendChild(configDF)
modal({ body: '保存成功' })
}
}
// 添加新用户
addUserButton.onclick = async () => {
modal()
const userDataMSG = await options.newUserData()
const uid = userDataMSG.uid
const userData = userDataMSG.data
const userDF = getUserDF(uid, userData)
userDiv.appendChild(userDF)
modal({ body: '添加成功' })
}
// 显示日志
showAdvButton.onclick = () => {
danimation(advOptionDiv)
}
// 显示日志
showLogButton.onclick = () => {
danimation(logDiv)
}
// 显示密钥修改
showChangeNetkeyButton.onclick = () => {
danimation(changeNetkeyDiv)
}
configDiv.appendChild(configDF)
}
/**
* 加载高级设置
*
*/
async function showAdvOption() {
const saveAdvConfigButton = <HTMLElement>document.querySelector('#saveAdvConfig')
const configMSG = await options.getAdvConfig()
let config = configMSG.data
const advConfigDF = getConfigTemplate(config)
// 保存高级设置
saveAdvConfigButton.onclick = async () => {
modal()
const configMSG = await options.setAdvConfig(config)
if (configMSG.msg != null) modal({ body: configMSG.msg })
else {
config = configMSG.data
const advConfigDF = getConfigTemplate(config)
advConfigDiv.innerText = ''
advConfigDiv.appendChild(advConfigDF)
modal({ body: '保存成功' })
}
}
advOptionReturnButton.onclick = () => {
danimation(optionDiv)
}
advConfigDiv.appendChild(advConfigDF)
}
/**
* 修改密钥
*
*/
async function showChangeNetkey() {
const saveNewNetkeyButton = <HTMLElement>document.querySelector('#saveNewNetkey')
const newNetkey1Input = <HTMLInputElement>document.querySelector('input[name="newNetkey1"]')
const newNetkey2Input = <HTMLInputElement>document.querySelector('input[name="newNetkey2"]')
// 保存高级设置
saveNewNetkeyButton.onclick = async () => {
modal()
if(newNetkey1Input.value === newNetkey2Input.value) {
window.newNetkey = newNetkey1Input.value
await options.setNewNetKey({netkey: window.newNetkey})
newNetkey1Input.value = ''
newNetkey2Input.value = ''
modal({ body: '修改成功!' })
} else {
modal({ body: '两次输入的密钥请保持一致!' })
}
}
netkeyReturnButton.onclick = () => {
danimation(optionDiv)
}
}
/**
* 加载Log
*
*/
async function showLog() {
const logMSG = await options.getLog()
const logs = logMSG.data
const logDF = document.createDocumentFragment()
logs.forEach(log => {
const div = document.createElement('div')
div.innerHTML = log.replace(/房间 (\d+) /, '房间 <a href="https://live.bilibili.com/$1" target="_blank" rel="noreferrer">$1</a> ')
logDF.appendChild(div)
})
options.onlog = data => {
const div = document.createElement('div')
div.innerHTML = data.replace(/房间 (\d+) /, '房间 <a href="https://live.bilibili.com/$1" target="_blank" rel="noreferrer">$1</a> ')
logDiv.appendChild(div)
if (logDiv.scrollHeight - logDiv.clientHeight - logDiv.scrollTop < 2 * div.offsetHeight) logDiv.scrollTop = logDiv.scrollHeight
}
returnButton.onclick = () => {
danimation(optionDiv)
}
logDiv.appendChild(logDF)
}
/**
* 加载用户设置
*
*/
async function showUser() {
const userMSG = await options.getAllUID()
const uidArray = userMSG.data
const df = document.createDocumentFragment()
for (const uid of uidArray) {
const userDataMSG = await options.getUserData(uid)
const userData = userDataMSG.data
const userDF = getUserDF(uid, userData)
df.appendChild(userDF)
}
userDiv.appendChild(df)
}
/**
* 加载额外功能
*
*/
async function showUtil() {
const utilMSG = await options.getAllUtilID()
if (utilMSG.msg === '未知命令') return
const utilArray = utilMSG.data
const df = document.createDocumentFragment()
for (const utilID of utilArray) {
const utilMSG = await options.getUtil(utilID)
const utilData = utilMSG.data
const utilDF = getUtilDF(utilID, utilData)
df.appendChild(utilDF)
}
utilDiv.appendChild(df)
}
/**
* 新建用户模板
*
* @param {string} uid
* @param {userData} userData
* @returns {DocumentFragment}
*/
function getUserDF(uid: string, userData: userData): DocumentFragment {
const userTemplate = <HTMLTemplateElement>template.querySelector('#userTemplate')
const clone = document.importNode(userTemplate.content, true)
const userDataDiv = <HTMLDivElement>clone.querySelector('.userData')
const userConfigDiv = <HTMLDivElement>clone.querySelector('.userConfig')
const saveUserButton = <HTMLElement>clone.querySelector('.saveUser')
const deleteUserButton = <HTMLElement>clone.querySelector('.deleteUser')
const userConfigDF = getConfigTemplate(userData)
userConfigDiv.appendChild(userConfigDF)
// 保存用户设置
let captcha: string | undefined = undefined
saveUserButton.onclick = async () => {
modal()
const userDataMSG = await options.setUserData(uid, userData, captcha)
captcha = undefined
if (userDataMSG.msg == null) {
modal({ body: '保存成功' })
userData = userDataMSG.data
const userConfigDF = getConfigTemplate(userData)
userConfigDiv.innerText = ''
userConfigDiv.appendChild(userConfigDF)
}
else if (userDataMSG.msg === 'captcha' && userDataMSG.captcha != null) {
const captchaTemplate = <HTMLTemplateElement>template.querySelector('#captchaTemplate')
const clone = document.importNode(captchaTemplate.content, true)
const captchaImg = <HTMLImageElement>clone.querySelector('img')
const captchaInput = <HTMLInputElement>clone.querySelector('input')
captchaImg.src = userDataMSG.captcha
modal({
body: clone,
showOK: true,
onOK: () => {
captcha = captchaInput.value
saveUserButton.click()
}
})
}
else modal({ body: userDataMSG.msg })
}
// 删除用户设置
deleteUserButton.onclick = async () => {
modal()
const userDataMSG = await options.delUserData(uid)
if (userDataMSG.msg != null) modal({ body: userDataMSG.msg })
else {
modal({ body: '删除成功' })
userDataDiv.remove()
}
}
return clone
}
/**
* 新建功能插件模板
*
* @param {string} utilID
* @param {utilData} utilData
* @returns {DocumentFragment}
*/
function getUtilDF(utilID: string, utilData: utilData): DocumentFragment {
const utilTemplate = <HTMLTemplateElement>template.querySelector('#utilTemplate')
const clone = document.importNode(utilTemplate.content, true)
const utilConfigDiv = <HTMLDivElement>clone.querySelector('.utilConfigClass')
const utilPostButton = <HTMLElement>clone.querySelector('.utilPost')
const userConfigDF = getUtilConfigTemplate(utilData)
utilConfigDiv.appendChild(userConfigDF)
// 前端功能插件 数据提交
utilPostButton.onclick = async () => {
modal()
const sendUtilCallback = await options.sendUtil(utilID, utilData)
if (sendUtilCallback.msg !== undefined) modal({ body: sendUtilCallback.msg })
}
return clone
}
/**
* 设置模板
*
* @param {(config | userData)} config
* @returns {DocumentFragment}
*/
function getConfigTemplate(config: config | userData): DocumentFragment {
const df = document.createDocumentFragment()
for (const key in config) {
const info = optionsInfo[key]
if (info == null) continue
const configValue = config[key]
let configTemplate: HTMLTemplateElement
if (info.type === 'boolean') configTemplate = <HTMLTemplateElement>template.querySelector('#configCheckboxTemplate')
else configTemplate = <HTMLTemplateElement>template.querySelector('#configTextTemplate')
const clone = document.importNode(configTemplate.content, true)
const descriptionDiv = <HTMLDivElement>clone.querySelector('._description')
const inputInput = <HTMLInputElement>clone.querySelector('.form-control')
const checkboxInput = <HTMLInputElement>clone.querySelector('.form-check-input')
switch (info.type) {
case 'number':
inputInput.value = (<number>configValue).toString()
inputInput.oninput = () => config[key] = parseInt(inputInput.value)
break
case 'numberArray':
inputInput.value = (<number[]>configValue).join(',')
inputInput.oninput = () => config[key] = inputInput.value.split(',').map(value => parseInt(value))
break
case 'string':
inputInput.value = <string>configValue
inputInput.oninput = () => config[key] = inputInput.value
break
case 'stringArray':
inputInput.value = (<string[]>configValue).join(',')
inputInput.oninput = () => config[key] = inputInput.value.split(',')
break
case 'boolean':
checkboxInput.checked = <boolean>configValue
checkboxInput.onchange = () => config[key] = checkboxInput.checked
break
default:
break
}
descriptionDiv.innerText = info.description
descriptionDiv.title = info.tip
$(descriptionDiv).tooltip()
df.appendChild(clone)
}
return df
}
/**
* 设置util模板
*
* @param {utilData} utilData
* @returns {DocumentFragment}
*/
function getUtilConfigTemplate(utilData: utilData): DocumentFragment {
const df = document.createDocumentFragment()
for (const key in utilData) {
const info = utilData[key].info
const itemValue = utilData[key].value
let configTemplate: HTMLTemplateElement
if (info.type === 'boolean') configTemplate = <HTMLTemplateElement>template.querySelector('#configCheckboxTemplate')
else if (info.type === 'user') configTemplate = <HTMLTemplateElement>template.querySelector('#utilUserListTemplate')
else configTemplate = <HTMLTemplateElement>template.querySelector('#configTextTemplate')
const clone = document.importNode(configTemplate.content, true)
const descriptionDiv = <HTMLDivElement>clone.querySelector('._description')
const inputInput = <HTMLInputElement>clone.querySelector('.form-control')
const checkboxInput = <HTMLInputElement>clone.querySelector('.form-check-input')
switch (info.type) {
case 'number':
inputInput.value = (<number>itemValue).toString()
inputInput.oninput = () => utilData[key].value = parseInt(inputInput.value)
break
case 'string':
inputInput.value = <string>itemValue
inputInput.oninput = () => utilData[key].value = inputInput.value
break
case 'boolean':
checkboxInput.checked = <boolean>itemValue
checkboxInput.onchange = () => utilData[key].value = checkboxInput.checked
break
case 'user':
for (let i = 0; i < (<string[]>utilData[key].list).length; i++) {
let option = document.createElement("option")
const userStr = (<string[]>utilData[key].list)[i]
option.setAttribute("label", userStr)
option.setAttribute("value", userStr)
inputInput.appendChild(option)
}
inputInput.value = <string>itemValue
inputInput.onchange = () => utilData[key].value = inputInput.value
break
default:
break
}
descriptionDiv.innerText = info.description
descriptionDiv.title = info.tip
$(descriptionDiv).tooltip()
df.appendChild(clone)
}
return df
}
/**
* 处理连接中断
*
* @param {string} data
*/
function wsClose(data: string) {
const connectSpan = <HTMLSpanElement>loginDiv.querySelector('#connect span')
configDiv.innerText = ''
advConfigDiv.innerHTML = ''
logDiv.innerText = ''
userDiv.innerText = ''
utilDiv.innerText = ''
connectSpan.innerText = data
danimation(loginDiv)
}
showLogin() | the_stack |
import { Theme } from "../../theme";
import type { Renderer } from "../../renderer";
import {
Reflection,
ReflectionKind,
ProjectReflection,
ContainerReflection,
DeclarationReflection,
} from "../../../models/reflections/index";
import type { ReflectionGroup } from "../../../models/ReflectionGroup";
import { RenderTemplate, UrlMapping } from "../../models/UrlMapping";
import { PageEvent, RendererEvent } from "../../events";
import type { MarkedPlugin } from "../../plugins";
import { DefaultThemeRenderContext } from "./DefaultThemeRenderContext";
import { JSX } from "../../../utils";
/**
* Defines a mapping of a {@link Models.Kind} to a template file.
*
* Used by {@link DefaultTheme} to map reflections to output files.
*/
interface TemplateMapping {
/**
* {@link DeclarationReflection.kind} this rule applies to.
*/
kind: ReflectionKind[];
/**
* Can this mapping have children or should all further reflections be rendered
* to the defined output page?
*/
isLeaf: boolean;
/**
* The name of the directory the output files should be written to.
*/
directory: string;
/**
* The name of the template that should be used to render the reflection.
*/
template: RenderTemplate<PageEvent<any>>;
}
/**
* Default theme implementation of TypeDoc. If a theme does not provide a custom
* {@link Theme} implementation, this theme class will be used.
*/
export class DefaultTheme extends Theme {
/** @internal */
markedPlugin: MarkedPlugin;
private _renderContext?: DefaultThemeRenderContext;
getRenderContext(_pageEvent: PageEvent<any>) {
if (!this._renderContext) {
this._renderContext = new DefaultThemeRenderContext(this, this.application.options);
}
return this._renderContext;
}
reflectionTemplate = (pageEvent: PageEvent<ContainerReflection>) => {
return this.getRenderContext(pageEvent).reflectionTemplate(pageEvent);
};
indexTemplate = (pageEvent: PageEvent<ProjectReflection>) => {
return this.getRenderContext(pageEvent).indexTemplate(pageEvent);
};
defaultLayoutTemplate = (pageEvent: PageEvent<Reflection>) => {
return this.getRenderContext(pageEvent).defaultLayout(pageEvent);
};
/**
* Mappings of reflections kinds to templates used by this theme.
*/
private mappings: TemplateMapping[] = [
{
kind: [ReflectionKind.Class],
isLeaf: false,
directory: "classes",
template: this.reflectionTemplate,
},
{
kind: [ReflectionKind.Interface],
isLeaf: false,
directory: "interfaces",
template: this.reflectionTemplate,
},
{
kind: [ReflectionKind.Enum],
isLeaf: false,
directory: "enums",
template: this.reflectionTemplate,
},
{
kind: [ReflectionKind.Namespace, ReflectionKind.Module],
isLeaf: false,
directory: "modules",
template: this.reflectionTemplate,
},
];
static URL_PREFIX = /^(http|ftp)s?:\/\//;
/**
* Create a new DefaultTheme instance.
*
* @param renderer The renderer this theme is attached to.
* @param basePath The base path of this theme.
*/
constructor(renderer: Renderer) {
super(renderer);
this.markedPlugin = renderer.getComponent("marked") as MarkedPlugin;
this.listenTo(renderer, RendererEvent.BEGIN, this.onRendererBegin, 1024);
}
/**
* Map the models of the given project to the desired output files.
*
* @param project The project whose urls should be generated.
* @returns A list of {@link UrlMapping} instances defining which models
* should be rendered to which files.
*/
getUrls(project: ProjectReflection): UrlMapping[] {
const urls: UrlMapping[] = [];
if (false == hasReadme(this.application.options.getValue("readme"))) {
project.url = "index.html";
urls.push(new UrlMapping<ContainerReflection>("index.html", project, this.reflectionTemplate));
} else {
project.url = "modules.html";
urls.push(new UrlMapping<ContainerReflection>("modules.html", project, this.reflectionTemplate));
urls.push(new UrlMapping("index.html", project, this.indexTemplate));
}
project.children?.forEach((child: Reflection) => {
if (child instanceof DeclarationReflection) {
this.buildUrls(child, urls);
}
});
return urls;
}
/**
* Triggered before the renderer starts rendering a project.
*
* @param event An event object describing the current render operation.
*/
private onRendererBegin(event: RendererEvent) {
if (event.project.groups) {
event.project.groups.forEach(DefaultTheme.applyGroupClasses);
}
for (const id in event.project.reflections) {
const reflection = event.project.reflections[id];
if (reflection instanceof DeclarationReflection) {
DefaultTheme.applyReflectionClasses(reflection);
}
if (reflection instanceof ContainerReflection && reflection.groups) {
reflection.groups.forEach(DefaultTheme.applyGroupClasses);
}
}
}
/**
* Return a url for the given reflection.
*
* @param reflection The reflection the url should be generated for.
* @param relative The parent reflection the url generation should stop on.
* @param separator The separator used to generate the url.
* @returns The generated url.
*/
static getUrl(reflection: Reflection, relative?: Reflection, separator = "."): string {
let url = reflection.getAlias();
if (reflection.parent && reflection.parent !== relative && !(reflection.parent instanceof ProjectReflection)) {
url = DefaultTheme.getUrl(reflection.parent, relative, separator) + separator + url;
}
return url;
}
/**
* Return the template mapping for the given reflection.
*
* @param reflection The reflection whose mapping should be resolved.
* @returns The found mapping or undefined if no mapping could be found.
*/
private getMapping(reflection: DeclarationReflection): TemplateMapping | undefined {
return this.mappings.find((mapping) => reflection.kindOf(mapping.kind));
}
/**
* Build the url for the the given reflection and all of its children.
*
* @param reflection The reflection the url should be created for.
* @param urls The array the url should be appended to.
* @returns The altered urls array.
*/
buildUrls(reflection: DeclarationReflection, urls: UrlMapping[]): UrlMapping[] {
const mapping = this.getMapping(reflection);
if (mapping) {
if (!reflection.url || !DefaultTheme.URL_PREFIX.test(reflection.url)) {
const url = [mapping.directory, DefaultTheme.getUrl(reflection) + ".html"].join("/");
urls.push(new UrlMapping(url, reflection, mapping.template));
reflection.url = url;
reflection.hasOwnDocument = true;
}
for (const child of reflection.children || []) {
if (mapping.isLeaf) {
DefaultTheme.applyAnchorUrl(child, reflection);
} else {
this.buildUrls(child, urls);
}
}
} else if (reflection.parent) {
DefaultTheme.applyAnchorUrl(reflection, reflection.parent);
}
return urls;
}
render(page: PageEvent<Reflection>): string {
const templateOutput = this.defaultLayoutTemplate(page);
return "<!DOCTYPE html>" + JSX.renderElement(templateOutput);
}
/**
* Generate an anchor url for the given reflection and all of its children.
*
* @param reflection The reflection an anchor url should be created for.
* @param container The nearest reflection having an own document.
*/
static applyAnchorUrl(reflection: Reflection, container: Reflection) {
if (!reflection.url || !DefaultTheme.URL_PREFIX.test(reflection.url)) {
const anchor = DefaultTheme.getUrl(reflection, container, ".");
reflection.url = container.url + "#" + anchor;
reflection.anchor = anchor;
reflection.hasOwnDocument = false;
}
reflection.traverse((child) => {
if (child instanceof DeclarationReflection) {
DefaultTheme.applyAnchorUrl(child, container);
}
return true;
});
}
/**
* Generate the css classes for the given reflection and apply them to the
* {@link DeclarationReflection.cssClasses} property.
*
* @param reflection The reflection whose cssClasses property should be generated.
*/
static applyReflectionClasses(reflection: DeclarationReflection) {
const classes: string[] = [];
let kind: string;
if (reflection.kind === ReflectionKind.Accessor) {
if (!reflection.getSignature) {
classes.push("tsd-kind-set-signature");
} else if (!reflection.setSignature) {
classes.push("tsd-kind-get-signature");
} else {
classes.push("tsd-kind-accessor");
}
} else {
kind = ReflectionKind[reflection.kind];
classes.push(DefaultTheme.toStyleClass("tsd-kind-" + kind));
}
if (reflection.parent && reflection.parent instanceof DeclarationReflection) {
kind = ReflectionKind[reflection.parent.kind];
classes.push(DefaultTheme.toStyleClass(`tsd-parent-kind-${kind}`));
}
let hasTypeParameters = !!reflection.typeParameters;
reflection.getAllSignatures().forEach((signature) => {
hasTypeParameters = hasTypeParameters || !!signature.typeParameters;
});
if (hasTypeParameters) {
classes.push("tsd-has-type-parameter");
}
if (reflection.overwrites) {
classes.push("tsd-is-overwrite");
}
if (reflection.inheritedFrom) {
classes.push("tsd-is-inherited");
}
if (reflection.flags.isPrivate) {
classes.push("tsd-is-private");
}
if (reflection.flags.isProtected) {
classes.push("tsd-is-protected");
}
if (reflection.flags.isStatic) {
classes.push("tsd-is-static");
}
if (reflection.flags.isExternal) {
classes.push("tsd-is-external");
}
reflection.cssClasses = classes.join(" ");
}
/**
* Generate the css classes for the given reflection group and apply them to the
* {@link ReflectionGroup.cssClasses} property.
*
* @param group The reflection group whose cssClasses property should be generated.
*/
static applyGroupClasses(group: ReflectionGroup) {
const classes: string[] = [];
if (group.allChildrenAreInherited) {
classes.push("tsd-is-inherited");
}
if (group.allChildrenArePrivate) {
classes.push("tsd-is-private");
}
if (group.allChildrenAreProtectedOrPrivate) {
classes.push("tsd-is-private-protected");
}
if (group.allChildrenAreExternal) {
classes.push("tsd-is-external");
}
group.cssClasses = classes.join(" ");
}
/**
* Transform a space separated string into a string suitable to be used as a
* css class, e.g. "constructor method" > "Constructor-method".
*/
static toStyleClass(str: string) {
return str.replace(/(\w)([A-Z])/g, (_m, m1, m2) => m1 + "-" + m2).toLowerCase();
}
}
function hasReadme(readme: string) {
return !readme.endsWith("none");
} | the_stack |
import * as ts from "typescript";
import * as lua from "../../LuaAST";
import { assert, assertNever } from "../../utils";
import { FunctionVisitor, TransformationContext } from "../context";
import { validateAssignment } from "../utils/assignment-validation";
import { unsupportedVarDeclaration } from "../utils/diagnostics";
import { addExportToIdentifier } from "../utils/export";
import { createLocalOrExportedOrGlobalDeclaration, createUnpackCall, wrapInTable } from "../utils/lua-ast";
import { LuaLibFeature, transformLuaLibFunction } from "../utils/lualib";
import { transformIdentifier } from "./identifier";
import { isMultiReturnCall } from "./language-extensions/multi";
import { transformPropertyName } from "./literal";
export function transformArrayBindingElement(
context: TransformationContext,
name: ts.ArrayBindingElement
): lua.Identifier {
if (ts.isOmittedExpression(name)) {
return lua.createAnonymousIdentifier(name);
} else if (ts.isIdentifier(name)) {
return transformIdentifier(context, name);
} else if (ts.isBindingElement(name)) {
// TODO: It should always be true when called from `transformVariableDeclaration`,
// but could be false from `transformForOfLuaIteratorStatement`.
assert(ts.isIdentifier(name.name));
return transformIdentifier(context, name.name);
} else {
assertNever(name);
}
}
export function transformBindingPattern(
context: TransformationContext,
pattern: ts.BindingPattern,
table: lua.Identifier,
propertyAccessStack: ts.PropertyName[] = []
): lua.Statement[] {
const result: lua.Statement[] = [];
for (const [index, element] of pattern.elements.entries()) {
if (ts.isOmittedExpression(element)) continue;
if (ts.isArrayBindingPattern(element.name) || ts.isObjectBindingPattern(element.name)) {
// nested binding pattern
const propertyName = ts.isObjectBindingPattern(pattern)
? element.propertyName
: ts.factory.createNumericLiteral(String(index + 1));
if (propertyName !== undefined) {
propertyAccessStack.push(propertyName);
}
result.push(...transformBindingPattern(context, element.name, table, propertyAccessStack));
continue;
}
// Build the path to the table
const tableExpression = propertyAccessStack.reduce<lua.Expression>(
(path, property) => lua.createTableIndexExpression(path, transformPropertyName(context, property)),
table
);
// The identifier of the new variable
const variableName = transformIdentifier(context, element.name);
// The field to extract
const propertyName = transformPropertyName(context, element.propertyName ?? element.name);
let expression: lua.Expression;
if (element.dotDotDotToken) {
if (index !== pattern.elements.length - 1) {
// TypeScript error
continue;
}
if (ts.isObjectBindingPattern(pattern)) {
const excludedProperties: ts.Identifier[] = [];
for (const element of pattern.elements) {
// const { ...x } = ...;
// ~~~~
if (element.dotDotDotToken) continue;
// const { x } = ...;
// ~
if (ts.isIdentifier(element.name) && !element.propertyName) {
excludedProperties.push(element.name);
}
// const { x: ... } = ...;
// ~~~~~~
if (element.propertyName && element.name && ts.isIdentifier(element.propertyName)) {
excludedProperties.push(element.propertyName);
}
}
const excludedPropertiesTable = excludedProperties.map(e =>
lua.createTableFieldExpression(lua.createBooleanLiteral(true), lua.createStringLiteral(e.text, e))
);
expression = transformLuaLibFunction(
context,
LuaLibFeature.ObjectRest,
undefined,
tableExpression,
lua.createTableExpression(excludedPropertiesTable)
);
} else {
expression = transformLuaLibFunction(
context,
LuaLibFeature.ArraySlice,
undefined,
tableExpression,
lua.createNumericLiteral(index)
);
}
} else {
expression = lua.createTableIndexExpression(
tableExpression,
ts.isObjectBindingPattern(pattern) ? propertyName : lua.createNumericLiteral(index + 1)
);
}
result.push(...createLocalOrExportedOrGlobalDeclaration(context, variableName, expression));
if (element.initializer) {
const identifier = addExportToIdentifier(context, variableName);
result.push(
lua.createIfStatement(
lua.createBinaryExpression(identifier, lua.createNilLiteral(), lua.SyntaxKind.EqualityOperator),
lua.createBlock([
lua.createAssignmentStatement(identifier, context.transformExpression(element.initializer)),
])
)
);
}
}
propertyAccessStack.pop();
return result;
}
export function transformBindingVariableDeclaration(
context: TransformationContext,
bindingPattern: ts.BindingPattern,
initializer?: ts.Expression
): lua.Statement[] {
const statements: lua.Statement[] = [];
// For object, nested or rest bindings fall back to transformBindingPattern
const isComplexBindingElement = (e: ts.ArrayBindingElement) =>
ts.isBindingElement(e) && (!ts.isIdentifier(e.name) || e.dotDotDotToken);
if (ts.isObjectBindingPattern(bindingPattern) || bindingPattern.elements.some(isComplexBindingElement)) {
let table: lua.Identifier;
if (initializer !== undefined && ts.isIdentifier(initializer)) {
table = transformIdentifier(context, initializer);
} else {
// Contain the expression in a temporary variable
table = lua.createAnonymousIdentifier();
if (initializer) {
let expression = context.transformExpression(initializer);
if (isMultiReturnCall(context, initializer)) {
expression = wrapInTable(expression);
}
statements.push(lua.createVariableDeclarationStatement(table, expression));
}
}
statements.push(...transformBindingPattern(context, bindingPattern, table));
return statements;
}
const vars =
bindingPattern.elements.length > 0
? bindingPattern.elements.map(e => transformArrayBindingElement(context, e))
: lua.createAnonymousIdentifier();
if (initializer) {
if (isMultiReturnCall(context, initializer)) {
// Don't unpack LuaMultiReturn functions
statements.push(
...createLocalOrExportedOrGlobalDeclaration(
context,
vars,
context.transformExpression(initializer),
initializer
)
);
} else if (ts.isArrayLiteralExpression(initializer)) {
// Don't unpack array literals
const values =
initializer.elements.length > 0
? initializer.elements.map(e => context.transformExpression(e))
: lua.createNilLiteral();
statements.push(...createLocalOrExportedOrGlobalDeclaration(context, vars, values, initializer));
} else {
// local vars = this.transpileDestructingAssignmentValue(node.initializer);
const unpackedInitializer = createUnpackCall(
context,
context.transformExpression(initializer),
initializer
);
statements.push(
...createLocalOrExportedOrGlobalDeclaration(context, vars, unpackedInitializer, initializer)
);
}
} else {
statements.push(
...createLocalOrExportedOrGlobalDeclaration(context, vars, lua.createNilLiteral(), initializer)
);
}
for (const element of bindingPattern.elements) {
if (!ts.isOmittedExpression(element) && element.initializer) {
const variableName = transformIdentifier(context, element.name as ts.Identifier);
const identifier = addExportToIdentifier(context, variableName);
statements.push(
lua.createIfStatement(
lua.createBinaryExpression(identifier, lua.createNilLiteral(), lua.SyntaxKind.EqualityOperator),
lua.createBlock([
lua.createAssignmentStatement(identifier, context.transformExpression(element.initializer)),
])
)
);
}
}
return statements;
}
// TODO: FunctionVisitor<ts.VariableDeclaration>
export function transformVariableDeclaration(
context: TransformationContext,
statement: ts.VariableDeclaration
): lua.Statement[] {
if (statement.initializer && statement.type) {
const initializerType = context.checker.getTypeAtLocation(statement.initializer);
const varType = context.checker.getTypeFromTypeNode(statement.type);
validateAssignment(context, statement.initializer, initializerType, varType);
}
if (ts.isIdentifier(statement.name)) {
// Find variable identifier
const identifierName = transformIdentifier(context, statement.name);
const value = statement.initializer && context.transformExpression(statement.initializer);
return createLocalOrExportedOrGlobalDeclaration(context, identifierName, value, statement);
} else if (ts.isArrayBindingPattern(statement.name) || ts.isObjectBindingPattern(statement.name)) {
return transformBindingVariableDeclaration(context, statement.name, statement.initializer);
} else {
return assertNever(statement.name);
}
}
export function checkVariableDeclarationList(context: TransformationContext, node: ts.VariableDeclarationList): void {
if ((node.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const)) === 0) {
const token = node.getFirstToken();
assert(token);
context.diagnostics.push(unsupportedVarDeclaration(token));
}
}
export const transformVariableStatement: FunctionVisitor<ts.VariableStatement> = (node, context) => {
checkVariableDeclarationList(context, node.declarationList);
return node.declarationList.declarations.flatMap(declaration => transformVariableDeclaration(context, declaration));
}; | the_stack |
import {StaffLine} from "./StaffLine";
import {Instrument} from "../Instrument";
import {BoundingBox} from "./BoundingBox";
import {Fraction} from "../../Common/DataObjects/Fraction";
import {SourceMeasure} from "../VoiceData/SourceMeasure";
import {InstrumentalGroup} from "../InstrumentalGroup";
import {TextAlignmentEnum} from "../../Common/Enums/TextAlignment";
import {GraphicalMusicPage} from "./GraphicalMusicPage";
import {GraphicalLabel} from "./GraphicalLabel";
import {GraphicalMeasure} from "./GraphicalMeasure";
import {GraphicalObject} from "./GraphicalObject";
import {EngravingRules} from "./EngravingRules";
import {PointF2D} from "../../Common/DataObjects/PointF2D";
import {GraphicalStaffEntry} from "./GraphicalStaffEntry";
import {SystemLinesEnum} from "./SystemLinesEnum";
import { Dictionary } from "typescript-collections";
import {GraphicalComment} from "./GraphicalComment";
import {GraphicalMarkedArea} from "./GraphicalMarkedArea";
import {SystemLine} from "./SystemLine";
import {SystemLinePosition} from "./SystemLinePosition";
import {Staff} from "../VoiceData/Staff";
import { Label } from "../Label";
/**
* A MusicSystem contains the [[StaffLine]]s for all instruments, until a line break
*/
export abstract class MusicSystem extends GraphicalObject {
public needsToBeRedrawn: boolean = true;
public rules: EngravingRules;
protected parent: GraphicalMusicPage;
protected id: number;
protected staffLines: StaffLine[] = [];
protected graphicalMeasures: GraphicalMeasure[][] = [];
/** Dictionary of (Instruments and) labels.
* note that the key needs to be unique, GraphicalLabel is not unique yet.
* That is why the labels are labels.values() and not labels.keys().
*/
protected labels: Dictionary<Instrument, GraphicalLabel> = new Dictionary<Instrument, GraphicalLabel>();
protected measureNumberLabels: GraphicalLabel[] = [];
protected maxLabelLength: number;
protected objectsToRedraw: [Object[], Object][] = [];
protected instrumentBrackets: GraphicalObject[] = [];
protected groupBrackets: GraphicalObject[] = [];
protected graphicalMarkedAreas: GraphicalMarkedArea[] = [];
protected graphicalComments: GraphicalComment[] = [];
protected systemLines: SystemLine[] = [];
public breaksPage: boolean = false;
constructor(id: number) {
super();
this.id = id;
this.boundingBox = new BoundingBox(this);
this.maxLabelLength = 0.0;
}
public get Parent(): GraphicalMusicPage {
return this.parent;
}
public set Parent(value: GraphicalMusicPage) {
// remove from old page
if (this.parent) {
const index: number = this.parent.MusicSystems.indexOf(this, 0);
if (index > -1) {
this.parent.MusicSystems.splice(index, 1);
}
}
this.parent = value;
this.boundingBox.Parent = value.PositionAndShape;
}
public get NextSystem(): MusicSystem {
const idxInParent: number = this.Parent.MusicSystems.indexOf(this);
return idxInParent !== this.Parent.MusicSystems.length ? this.Parent.MusicSystems[idxInParent + 1] : undefined;
}
public get StaffLines(): StaffLine[] {
return this.staffLines;
}
public get GraphicalMeasures(): GraphicalMeasure[][] {
return this.graphicalMeasures;
}
public get MeasureNumberLabels(): GraphicalLabel[] {
return this.measureNumberLabels;
}
public get Labels(): GraphicalLabel[] {
return this.labels.values();
}
public get ObjectsToRedraw(): [Object[], Object][] {
return this.objectsToRedraw;
}
public get InstrumentBrackets(): GraphicalObject[] {
return this.instrumentBrackets;
}
public get GroupBrackets(): GraphicalObject[] {
return this.groupBrackets;
}
public get GraphicalMarkedAreas(): GraphicalMarkedArea[] {
return this.graphicalMarkedAreas;
}
public get GraphicalComments(): GraphicalComment[] {
return this.graphicalComments;
}
public get SystemLines(): SystemLine[] {
return this.systemLines;
}
public get Id(): number {
return this.id;
}
/**
* Create the left vertical Line connecting all staves of the [[MusicSystem]].
* @param lineWidth
* @param systemLabelsRightMargin
*/
public createSystemLeftLine(lineWidth: number, systemLabelsRightMargin: number, isFirstSystem: boolean): void {
let xPosition: number = -lineWidth / 2;
if (isFirstSystem) {
xPosition = this.maxLabelLength + systemLabelsRightMargin - lineWidth / 2;
}
const top: GraphicalMeasure = this.staffLines[0].Measures[0];
let bottom: GraphicalMeasure = undefined;
if (this.staffLines.length > 1) {
bottom = this.staffLines[this.staffLines.length - 1].Measures[0];
}
const leftSystemLine: SystemLine = this.createSystemLine(xPosition, lineWidth, SystemLinesEnum.SingleThin,
SystemLinePosition.MeasureBegin, this, top, bottom);
this.SystemLines.push(leftSystemLine);
leftSystemLine.PositionAndShape.RelativePosition = new PointF2D(xPosition, 0);
leftSystemLine.PositionAndShape.BorderLeft = 0;
leftSystemLine.PositionAndShape.BorderRight = lineWidth;
leftSystemLine.PositionAndShape.BorderTop = 0;
leftSystemLine.PositionAndShape.BorderBottom = this.boundingBox.Size.height;
this.createLinesForSystemLine(leftSystemLine);
}
/**
* Create the vertical Lines after the End of all [[StaffLine]]'s Measures
* @param xPosition
* @param lineWidth
* @param lineType
* @param linePosition indicates if the line belongs to start or end of measure
* @param measureIndex the measure index within the staffline
* @param measure
*/
public createVerticalLineForMeasure(xPosition: number, lineWidth: number, lineType: SystemLinesEnum, linePosition: SystemLinePosition,
measureIndex: number, measure: GraphicalMeasure): void {
//return; // TODO check why there's a bold line here for the double barline sample
const staffLine: StaffLine = measure.ParentStaffLine;
const staffLineRelative: PointF2D = new PointF2D(staffLine.PositionAndShape.RelativePosition.x,
staffLine.PositionAndShape.RelativePosition.y);
const staves: Staff[] = staffLine.ParentStaff.ParentInstrument.Staves;
if (staffLine.ParentStaff === staves[0]) {
let bottomMeasure: GraphicalMeasure = undefined;
if (staves.length > 1) {
bottomMeasure = this.getBottomStaffLine(staffLine).Measures[measureIndex];
}
const singleVerticalLineAfterMeasure: SystemLine = this.createSystemLine(xPosition, lineWidth, lineType,
linePosition, this, measure, bottomMeasure);
const systemXPosition: number = staffLineRelative.x + xPosition;
singleVerticalLineAfterMeasure.PositionAndShape.RelativePosition = new PointF2D(systemXPosition, 0);
singleVerticalLineAfterMeasure.PositionAndShape.BorderLeft = 0;
singleVerticalLineAfterMeasure.PositionAndShape.BorderRight = lineWidth;
this.SystemLines.push(singleVerticalLineAfterMeasure);
}
}
/**
* Set the y-Positions of all the system lines in the system and creates the graphical Lines and dots within.
* @param rules
*/
public setYPositionsToVerticalLineObjectsAndCreateLines(rules: EngravingRules): void {
// empty
}
public calculateBorders(rules: EngravingRules): void {
// empty
}
public alignBeginInstructions(): void {
// empty
}
public GetLeftBorderAbsoluteXPosition(): number {
return this.StaffLines[0].PositionAndShape.AbsolutePosition.x + this.StaffLines[0].Measures[0].beginInstructionsWidth;
}
public GetRightBorderAbsoluteXPosition(): number {
return this.StaffLines[0].PositionAndShape.AbsolutePosition.x + this.StaffLines[0].StaffLines[0].End.x;
}
public AddGraphicalMeasures(graphicalMeasures: GraphicalMeasure[]): void {
for (let idx: number = 0, len: number = graphicalMeasures.length; idx < len; ++idx) {
const graphicalMeasure: GraphicalMeasure = graphicalMeasures[idx];
graphicalMeasure.ParentMusicSystem = this;
}
this.graphicalMeasures.push(graphicalMeasures);
}
public GetSystemsFirstTimeStamp(): Fraction {
return this.graphicalMeasures[0][0].parentSourceMeasure.AbsoluteTimestamp;
}
public GetSystemsLastTimeStamp(): Fraction {
const m: SourceMeasure = this.graphicalMeasures[this.graphicalMeasures.length - 1][0].parentSourceMeasure;
return Fraction.plus(m.AbsoluteTimestamp, m.Duration);
}
/**
* Create an InstrumentBracket for each multiStave Instrument.
* @param instruments
* @param staffHeight
*/
public createInstrumentBrackets(instruments: Instrument[], staffHeight: number): void {
for (let idx: number = 0, len: number = instruments.length; idx < len; ++idx) {
const instrument: Instrument = instruments[idx];
if (instrument.Staves.length > 1) {
let firstStaffLine: StaffLine = undefined, lastStaffLine: StaffLine = undefined;
for (let idx2: number = 0, len2: number = this.staffLines.length; idx2 < len2; ++idx2) {
const staffLine: StaffLine = this.staffLines[idx2];
if (staffLine.ParentStaff === instrument.Staves[0]) {
firstStaffLine = staffLine;
}
if (staffLine.ParentStaff === instrument.Staves[instrument.Staves.length - 1]) {
lastStaffLine = staffLine;
}
}
if (firstStaffLine && lastStaffLine) {
this.createInstrumentBracket(firstStaffLine, lastStaffLine);
}
}
}
}
/**
* Create a GroupBracket for an [[InstrumentalGroup]].
* @param instrumentGroups
* @param staffHeight
* @param recursionDepth
*/
public createGroupBrackets(instrumentGroups: InstrumentalGroup[], staffHeight: number, recursionDepth: number): void {
for (let idx: number = 0, len: number = instrumentGroups.length; idx < len; ++idx) {
const instrumentGroup: InstrumentalGroup = instrumentGroups[idx];
if (instrumentGroup.InstrumentalGroups.length < 1) {
continue;
}
const instrument1: Instrument = this.findFirstVisibleInstrumentInInstrumentalGroup(instrumentGroup);
const instrument2: Instrument = this.findLastVisibleInstrumentInInstrumentalGroup(instrumentGroup);
if (!instrument1 || !instrument2) {
continue;
}
let firstStaffLine: StaffLine = undefined;
let lastStaffLine: StaffLine = undefined;
for (let idx2: number = 0, len2: number = this.staffLines.length; idx2 < len2; ++idx2) {
const staffLine: StaffLine = this.staffLines[idx2];
if (staffLine.ParentStaff === instrument1.Staves[0]) {
firstStaffLine = staffLine;
}
if (staffLine.ParentStaff === instrument2.Staves[0]) {
lastStaffLine = staffLine;
}
}
if (firstStaffLine && lastStaffLine) {
this.createGroupBracket(firstStaffLine, lastStaffLine, recursionDepth);
}
if (instrumentGroup.InstrumentalGroups.length < 1) {
continue;
}
this.createGroupBrackets(instrumentGroup.InstrumentalGroups, staffHeight, recursionDepth + 1);
}
}
/**
* Create the Instrument's Labels (only for the first [[MusicSystem]] of the first MusicPage).
* @param instrumentLabelTextHeight
* @param systemLabelsRightMargin
* @param labelMarginBorderFactor
*/
public createMusicSystemLabel( instrumentLabelTextHeight: number, systemLabelsRightMargin: number,
labelMarginBorderFactor: number, isFirstSystem: boolean = false): void {
const originalSystemLabelsRightMargin: number = systemLabelsRightMargin;
for (let idx: number = 0, len: number = this.staffLines.length; idx < len; ++idx) {
const instrument: Instrument = this.staffLines[idx].ParentStaff.ParentInstrument;
let instrNameLabel: Label;
if (isFirstSystem) {
instrNameLabel = instrument.NameLabel;
if (!this.rules.RenderPartNames || !instrNameLabel?.print) {
instrNameLabel = new Label("", instrument.NameLabel.textAlignment, instrument.NameLabel.font);
systemLabelsRightMargin = 0; // might affect lyricist/tempo placement. but without this there's still some extra x-spacing.
}
} else {
if (!this.rules.RenderPartAbbreviations || !this.rules.RenderPartNames // don't render abbreviations if we don't render part names
|| this.staffLines.length === 1 // don't render part abbreviations if there's only one instrument/part (could be an option in the future)
|| !instrument.PartAbbreviation
|| instrument.PartAbbreviation === "") {
return;
}
const labelText: string = instrument.PartAbbreviation;
// const labelText: string = instrument.NameLabel.text[0] + ".";
instrNameLabel = new Label(labelText, instrument.NameLabel.textAlignment, instrument.NameLabel.font);
}
if (instrument?.NameLabel?.print) {
const graphicalLabel: GraphicalLabel = new GraphicalLabel(
instrNameLabel, instrumentLabelTextHeight, TextAlignmentEnum.LeftCenter, this.rules, this.boundingBox
);
graphicalLabel.setLabelPositionAndShapeBorders();
this.labels.setValue(instrument, graphicalLabel);
// X-Position will be 0 (Label starts at the same PointF_2D with MusicSystem)
// Y-Position will be calculated after the y-Spacing
// graphicalLabel.PositionAndShape.RelativePosition = new PointF2D(0.0, 0.0);
} else {
systemLabelsRightMargin = 0;
}
}
// calculate maxLabelLength (needed for X-Spacing)
this.maxLabelLength = 0.0;
const labels: GraphicalLabel[] = this.labels.values();
for (let idx: number = 0, len: number = labels.length; idx < len; ++idx) {
const label: GraphicalLabel = labels[idx];
if (!label.Label.print) {
continue;
}
if (label.PositionAndShape.Size.width > this.maxLabelLength) {
this.maxLabelLength = label.PositionAndShape.Size.width;
systemLabelsRightMargin = originalSystemLabelsRightMargin;
}
}
this.updateMusicSystemStaffLineXPosition(systemLabelsRightMargin);
}
/**
* Set the Y-Positions for the MusicSystem's Labels.
*/
public setMusicSystemLabelsYPosition(): void {
this.labels.forEach((key: Instrument, value: GraphicalLabel): void => {
let ypositionSum: number = 0;
let staffCounter: number = 0;
for (let i: number = 0; i < this.staffLines.length; i++) {
if (this.staffLines[i].ParentStaff.ParentInstrument === key) {
for (let j: number = i; j < this.staffLines.length; j++) {
const staffLine: StaffLine = this.staffLines[j];
if (staffLine.ParentStaff.ParentInstrument !== key) {
break;
}
ypositionSum += staffLine.PositionAndShape.RelativePosition.y;
staffCounter++;
}
break;
}
}
if (staffCounter > 0) {
value.PositionAndShape.RelativePosition = new PointF2D(0.0, ypositionSum / staffCounter + 2.0);
}
});
}
/**
* Check if two "adjacent" StaffLines have BOTH a StaffEntry with a StaffEntryLink.
* This is needed for the y-spacing algorithm.
* @returns {boolean}
*/
public checkStaffEntriesForStaffEntryLink(): boolean {
let first: boolean = false;
let second: boolean = false;
for (let i: number = 0; i < this.staffLines.length - 1; i++) {
for (let idx: number = 0, len: number = this.staffLines[i].Measures.length; idx < len; ++idx) {
const measure: GraphicalMeasure = this.staffLines[i].Measures[idx];
for (let idx2: number = 0, len2: number = measure.staffEntries.length; idx2 < len2; ++idx2) {
const staffEntry: GraphicalStaffEntry = measure.staffEntries[idx2];
if (staffEntry.sourceStaffEntry.Link) {
first = true;
}
}
}
for (let idx: number = 0, len: number = this.staffLines[i + 1].Measures.length; idx < len; ++idx) {
const measure: GraphicalMeasure = this.staffLines[i + 1].Measures[idx];
for (let idx2: number = 0, len2: number = measure.staffEntries.length; idx2 < len2; ++idx2) {
const staffEntry: GraphicalStaffEntry = measure.staffEntries[idx2];
if (staffEntry.sourceStaffEntry.Link) {
second = true;
}
}
}
}
if (first && second) {
return true;
}
return false;
}
public getBottomStaffLine(topStaffLine: StaffLine): StaffLine {
const staves: Staff[] = topStaffLine.ParentStaff.ParentInstrument.Staves;
const last: Staff = staves[staves.length - 1];
for (const line of topStaffLine.ParentMusicSystem.staffLines) {
if (line.ParentStaff === last) {
return line;
}
}
return undefined;
}
/**
* Here the system line is generated, which acts as the container of graphical lines and dots that will be finally rendered.
* It holds al the logical parameters of the system line.
* @param xPosition The x position within the system
* @param lineWidth The total x width
* @param lineType The line type enum
* @param linePosition indicates if the line belongs to start or end of measure
* @param musicSystem
* @param topMeasure
* @param bottomMeasure
*/
protected createSystemLine(xPosition: number, lineWidth: number, lineType: SystemLinesEnum, linePosition: SystemLinePosition,
musicSystem: MusicSystem, topMeasure: GraphicalMeasure, bottomMeasure: GraphicalMeasure = undefined): SystemLine {
throw new Error("not implemented");
}
/**
* Create all the graphical lines and dots needed to render a system line (e.g. bold-thin-dots..).
* @param systemLine
*/
protected createLinesForSystemLine(systemLine: SystemLine): void {
//Empty
}
/**
* Calculates the summed x-width of a possibly given Instrument Brace and/or Group Bracket(s).
* @returns {number} the x-width
*/
protected calcBracketsWidth(): number {
let width: number = 0;
for (let idx: number = 0, len: number = this.GroupBrackets.length; idx < len; ++idx) {
const groupBracket: GraphicalObject = this.GroupBrackets[idx];
width = Math.max(width, groupBracket.PositionAndShape.Size.width);
}
for (let idx2: number = 0, len2: number = this.InstrumentBrackets.length; idx2 < len2; ++idx2) {
const instrumentBracket: GraphicalObject = this.InstrumentBrackets[idx2];
width = Math.max(width, instrumentBracket.PositionAndShape.Size.width);
}
return width;
}
protected createInstrumentBracket(firstStaffLine: StaffLine, lastStaffLine: StaffLine): void {
// no impl here
}
protected createGroupBracket(firstStaffLine: StaffLine, lastStaffLine: StaffLine, recursionDepth: number): void {
// no impl here
}
private findFirstVisibleInstrumentInInstrumentalGroup(instrumentalGroup: InstrumentalGroup): Instrument {
for (let idx: number = 0, len: number = instrumentalGroup.InstrumentalGroups.length; idx < len; ++idx) {
const groupOrInstrument: InstrumentalGroup = instrumentalGroup.InstrumentalGroups[idx];
if (groupOrInstrument instanceof Instrument) {
if ((<Instrument>groupOrInstrument).Visible === true) {
return <Instrument>groupOrInstrument;
}
continue;
}
return this.findFirstVisibleInstrumentInInstrumentalGroup(groupOrInstrument);
}
return undefined;
}
private findLastVisibleInstrumentInInstrumentalGroup(instrumentalGroup: InstrumentalGroup): Instrument {
let groupOrInstrument: InstrumentalGroup;
for (let i: number = instrumentalGroup.InstrumentalGroups.length - 1; i >= 0; i--) {
groupOrInstrument = instrumentalGroup.InstrumentalGroups[i];
if (groupOrInstrument instanceof Instrument) {
if ((<Instrument>groupOrInstrument).Visible === true) {
return <Instrument>groupOrInstrument;
}
continue;
}
return this.findLastVisibleInstrumentInInstrumentalGroup(groupOrInstrument);
}
return undefined;
}
/**
* Update the xPosition of the [[MusicSystem]]'s [[StaffLine]]'s due to [[Label]] positioning.
* @param systemLabelsRightMargin
*/
private updateMusicSystemStaffLineXPosition(systemLabelsRightMargin: number): void {
for (let idx: number = 0, len: number = this.StaffLines.length; idx < len; ++idx) {
const staffLine: StaffLine = this.StaffLines[idx];
const relative: PointF2D = staffLine.PositionAndShape.RelativePosition;
relative.x = this.maxLabelLength + systemLabelsRightMargin;
staffLine.PositionAndShape.RelativePosition = relative;
staffLine.PositionAndShape.BorderRight = this.boundingBox.Size.width - this.maxLabelLength - systemLabelsRightMargin;
for (let i: number = 0; i < staffLine.StaffLines.length; i++) {
const lineEnd: PointF2D = new PointF2D(staffLine.PositionAndShape.Size.width, staffLine.StaffLines[i].End.y);
staffLine.StaffLines[i].End = lineEnd;
}
}
}
} | the_stack |
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types";
/**
* An exception thrown when a bulk publish operation is requested less than 24 hours after a previous bulk publish operation completed successfully.
*/
export interface AlreadyStreamedException extends __SmithyException, $MetadataBearer {
name: "AlreadyStreamedException";
$fault: "client";
/**
* The message associated with the AlreadyStreamedException exception.
*/
message: string | undefined;
}
export namespace AlreadyStreamedException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AlreadyStreamedException): any => ({
...obj,
});
}
/**
* The input for the BulkPublish operation.
*/
export interface BulkPublishRequest {
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityPoolId: string | undefined;
}
export namespace BulkPublishRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: BulkPublishRequest): any => ({
...obj,
});
}
/**
* The output for the BulkPublish operation.
*/
export interface BulkPublishResponse {
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityPoolId?: string;
}
export namespace BulkPublishResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: BulkPublishResponse): any => ({
...obj,
});
}
/**
* An exception thrown when there is an IN_PROGRESS bulk publish operation for the given identity pool.
*/
export interface DuplicateRequestException extends __SmithyException, $MetadataBearer {
name: "DuplicateRequestException";
$fault: "client";
/**
* The message associated with the DuplicateRequestException exception.
*/
message: string | undefined;
}
export namespace DuplicateRequestException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DuplicateRequestException): any => ({
...obj,
});
}
/**
* Indicates an internal service
* error.
*/
export interface InternalErrorException extends __SmithyException, $MetadataBearer {
name: "InternalErrorException";
$fault: "server";
/**
* Message returned by
* InternalErrorException.
*/
message: string | undefined;
}
export namespace InternalErrorException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InternalErrorException): any => ({
...obj,
});
}
/**
* Thrown when a request parameter does not comply
* with the associated constraints.
*/
export interface InvalidParameterException extends __SmithyException, $MetadataBearer {
name: "InvalidParameterException";
$fault: "client";
/**
* Message returned by
* InvalidParameterException.
*/
message: string | undefined;
}
export namespace InvalidParameterException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InvalidParameterException): any => ({
...obj,
});
}
/**
* Thrown when a user is not authorized to access the
* requested resource.
*/
export interface NotAuthorizedException extends __SmithyException, $MetadataBearer {
name: "NotAuthorizedException";
$fault: "client";
/**
* The message returned by a
* NotAuthorizedException.
*/
message: string | undefined;
}
export namespace NotAuthorizedException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: NotAuthorizedException): any => ({
...obj,
});
}
/**
* Thrown if the resource doesn't
* exist.
*/
export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer {
name: "ResourceNotFoundException";
$fault: "client";
/**
* Message returned by a
* ResourceNotFoundException.
*/
message: string | undefined;
}
export namespace ResourceNotFoundException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({
...obj,
});
}
/**
* A request to delete the specific
* dataset.
*/
export interface DeleteDatasetRequest {
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityPoolId: string | undefined;
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityId: string | undefined;
/**
* A string of up to 128 characters.
* Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.'
* (dot).
*/
DatasetName: string | undefined;
}
export namespace DeleteDatasetRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteDatasetRequest): any => ({
...obj,
});
}
/**
* A collection of data for an identity pool. An identity pool can
* have multiple datasets. A dataset is per identity and can be general or associated with a
* particular entity in an application (like a saved game). Datasets are automatically created if
* they don't exist. Data is synced by dataset, and a dataset can hold up to 1MB of key-value
* pairs.
*/
export interface Dataset {
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityId?: string;
/**
* A string of up to 128 characters. Allowed characters
* are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).
*/
DatasetName?: string;
/**
* Date on which the dataset was
* created.
*/
CreationDate?: Date;
/**
* Date when the dataset was last
* modified.
*/
LastModifiedDate?: Date;
/**
* The device that made the last change to this
* dataset.
*/
LastModifiedBy?: string;
/**
* Total size in bytes of the records in this
* dataset.
*/
DataStorage?: number;
/**
* Number of records in this dataset.
*/
NumRecords?: number;
}
export namespace Dataset {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Dataset): any => ({
...obj,
});
}
/**
* Response to a successful DeleteDataset
* request.
*/
export interface DeleteDatasetResponse {
/**
* A collection of data for an identity pool.
* An identity pool can have multiple datasets. A dataset is per identity and can be general or
* associated with a particular entity in an application (like a saved game). Datasets are
* automatically created if they don't exist. Data is synced by dataset, and a dataset can hold
* up to 1MB of key-value pairs.
*/
Dataset?: Dataset;
}
export namespace DeleteDatasetResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteDatasetResponse): any => ({
...obj,
});
}
/**
* Thrown if an update can't be applied because
* the resource was changed by another call and this would result in a conflict.
*/
export interface ResourceConflictException extends __SmithyException, $MetadataBearer {
name: "ResourceConflictException";
$fault: "client";
/**
* The message returned by a
* ResourceConflictException.
*/
message: string | undefined;
}
export namespace ResourceConflictException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceConflictException): any => ({
...obj,
});
}
/**
* Thrown if the request is
* throttled.
*/
export interface TooManyRequestsException extends __SmithyException, $MetadataBearer {
name: "TooManyRequestsException";
$fault: "client";
/**
* Message returned by a
* TooManyRequestsException.
*/
message: string | undefined;
}
export namespace TooManyRequestsException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TooManyRequestsException): any => ({
...obj,
});
}
/**
* A request for meta data about a dataset (creation
* date, number of records, size) by owner and dataset name.
*/
export interface DescribeDatasetRequest {
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityPoolId: string | undefined;
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityId: string | undefined;
/**
* A string of up to 128 characters.
* Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.'
* (dot).
*/
DatasetName: string | undefined;
}
export namespace DescribeDatasetRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeDatasetRequest): any => ({
...obj,
});
}
/**
* Response to a successful DescribeDataset
* request.
*/
export interface DescribeDatasetResponse {
/**
* Meta data for a collection of data for an
* identity. An identity can have multiple datasets. A dataset can be general or associated with
* a particular entity in an application (like a saved game). Datasets are automatically created
* if they don't exist. Data is synced by dataset, and a dataset can hold up to 1MB of key-value
* pairs.
*/
Dataset?: Dataset;
}
export namespace DescribeDatasetResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeDatasetResponse): any => ({
...obj,
});
}
/**
* A request for usage information about
* the identity pool.
*/
export interface DescribeIdentityPoolUsageRequest {
/**
* A name-spaced GUID (for
* example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID
* generation is unique within a region.
*/
IdentityPoolId: string | undefined;
}
export namespace DescribeIdentityPoolUsageRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeIdentityPoolUsageRequest): any => ({
...obj,
});
}
/**
* Usage information for the identity
* pool.
*/
export interface IdentityPoolUsage {
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityPoolId?: string;
/**
* Number of sync sessions for the
* identity pool.
*/
SyncSessionsCount?: number;
/**
* Data storage information for the identity
* pool.
*/
DataStorage?: number;
/**
* Date on which the identity pool was
* last modified.
*/
LastModifiedDate?: Date;
}
export namespace IdentityPoolUsage {
/**
* @internal
*/
export const filterSensitiveLog = (obj: IdentityPoolUsage): any => ({
...obj,
});
}
/**
* Response to a successful
* DescribeIdentityPoolUsage request.
*/
export interface DescribeIdentityPoolUsageResponse {
/**
* Information about the
* usage of the identity pool.
*/
IdentityPoolUsage?: IdentityPoolUsage;
}
export namespace DescribeIdentityPoolUsageResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeIdentityPoolUsageResponse): any => ({
...obj,
});
}
/**
* A request for information about the usage of
* an identity pool.
*/
export interface DescribeIdentityUsageRequest {
/**
* A name-spaced GUID (for
* example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID
* generation is unique within a region.
*/
IdentityPoolId: string | undefined;
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityId: string | undefined;
}
export namespace DescribeIdentityUsageRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeIdentityUsageRequest): any => ({
...obj,
});
}
/**
* Usage information for the identity.
*/
export interface IdentityUsage {
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityId?: string;
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityPoolId?: string;
/**
* Date on which the identity was last
* modified.
*/
LastModifiedDate?: Date;
/**
* Number of datasets for the
* identity.
*/
DatasetCount?: number;
/**
* Total data storage for this
* identity.
*/
DataStorage?: number;
}
export namespace IdentityUsage {
/**
* @internal
*/
export const filterSensitiveLog = (obj: IdentityUsage): any => ({
...obj,
});
}
/**
* The response to a successful
* DescribeIdentityUsage request.
*/
export interface DescribeIdentityUsageResponse {
/**
* Usage information for the
* identity.
*/
IdentityUsage?: IdentityUsage;
}
export namespace DescribeIdentityUsageResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeIdentityUsageResponse): any => ({
...obj,
});
}
/**
* The input for the GetBulkPublishDetails operation.
*/
export interface GetBulkPublishDetailsRequest {
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityPoolId: string | undefined;
}
export namespace GetBulkPublishDetailsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetBulkPublishDetailsRequest): any => ({
...obj,
});
}
export enum BulkPublishStatus {
FAILED = "FAILED",
IN_PROGRESS = "IN_PROGRESS",
NOT_STARTED = "NOT_STARTED",
SUCCEEDED = "SUCCEEDED",
}
/**
* The output for the GetBulkPublishDetails operation.
*/
export interface GetBulkPublishDetailsResponse {
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityPoolId?: string;
/**
* The date/time at which the last bulk publish was initiated.
*/
BulkPublishStartTime?: Date;
/**
* If BulkPublishStatus is SUCCEEDED, the time the last bulk publish operation completed.
*/
BulkPublishCompleteTime?: Date;
/**
* Status of the last bulk publish operation, valid values are:
* <p>NOT_STARTED - No bulk publish has been requested for this identity pool</p>
* <p>IN_PROGRESS - Data is being published to the configured stream</p>
* <p>SUCCEEDED - All data for the identity pool has been published to the configured stream</p>
* <p>FAILED - Some portion of the data has failed to publish, check FailureMessage for the cause.</p>
*/
BulkPublishStatus?: BulkPublishStatus | string;
/**
* If BulkPublishStatus is FAILED this field will contain the error message that caused the bulk publish to fail.
*/
FailureMessage?: string;
}
export namespace GetBulkPublishDetailsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetBulkPublishDetailsResponse): any => ({
...obj,
});
}
/**
* <p>A request for a list of the configured Cognito Events</p>
*/
export interface GetCognitoEventsRequest {
/**
* <p>The Cognito Identity Pool ID for the request</p>
*/
IdentityPoolId: string | undefined;
}
export namespace GetCognitoEventsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetCognitoEventsRequest): any => ({
...obj,
});
}
/**
* <p>The response from the GetCognitoEvents request</p>
*/
export interface GetCognitoEventsResponse {
/**
* <p>The Cognito Events returned from the GetCognitoEvents request</p>
*/
Events?: { [key: string]: string };
}
export namespace GetCognitoEventsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetCognitoEventsResponse): any => ({
...obj,
});
}
/**
* <p>The input for the GetIdentityPoolConfiguration operation.</p>
*/
export interface GetIdentityPoolConfigurationRequest {
/**
* <p>A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by
* Amazon Cognito. This is the ID of the pool for which to return a configuration.</p>
*/
IdentityPoolId: string | undefined;
}
export namespace GetIdentityPoolConfigurationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetIdentityPoolConfigurationRequest): any => ({
...obj,
});
}
export type StreamingStatus = "DISABLED" | "ENABLED";
/**
* Configuration options for configure Cognito streams.
*/
export interface CognitoStreams {
/**
* The name of the Cognito stream to receive updates. This stream must be in the developers account and in the same region as the identity pool.
*/
StreamName?: string;
/**
* The ARN of the role Amazon Cognito can assume in order to publish to the stream. This role must grant access to Amazon Cognito (cognito-sync) to invoke PutRecord on your Cognito stream.
*/
RoleArn?: string;
/**
* Status of the Cognito streams. Valid values are:
* <p>ENABLED - Streaming of updates to identity pool is enabled.</p>
* <p>DISABLED - Streaming of updates to identity pool is disabled. Bulk publish will also fail if StreamingStatus is DISABLED.</p>
*/
StreamingStatus?: StreamingStatus | string;
}
export namespace CognitoStreams {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CognitoStreams): any => ({
...obj,
});
}
/**
* <p>Configuration options to be applied to the identity pool.</p>
*/
export interface PushSync {
/**
* <p>List of SNS platform application ARNs that could be used by clients.</p>
*/
ApplicationArns?: string[];
/**
* <p>A role configured to allow Cognito to call SNS on behalf of the developer.</p>
*/
RoleArn?: string;
}
export namespace PushSync {
/**
* @internal
*/
export const filterSensitiveLog = (obj: PushSync): any => ({
...obj,
});
}
/**
* <p>The output for the GetIdentityPoolConfiguration operation.</p>
*/
export interface GetIdentityPoolConfigurationResponse {
/**
* <p>A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by
* Amazon Cognito.</p>
*/
IdentityPoolId?: string;
/**
* <p>Options to apply to this identity pool for push synchronization.</p>
*/
PushSync?: PushSync;
/**
* Options to apply to this identity pool for Amazon Cognito streams.
*/
CognitoStreams?: CognitoStreams;
}
export namespace GetIdentityPoolConfigurationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetIdentityPoolConfigurationResponse): any => ({
...obj,
});
}
/**
* Request for a list of datasets for an
* identity.
*/
export interface ListDatasetsRequest {
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityPoolId: string | undefined;
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityId: string | undefined;
/**
* A pagination token for obtaining the next
* page of results.
*/
NextToken?: string;
/**
* The maximum number of results to be
* returned.
*/
MaxResults?: number;
}
export namespace ListDatasetsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDatasetsRequest): any => ({
...obj,
});
}
/**
* Returned for a successful ListDatasets
* request.
*/
export interface ListDatasetsResponse {
/**
* A set of datasets.
*/
Datasets?: Dataset[];
/**
* Number of datasets returned.
*/
Count?: number;
/**
* A pagination token for obtaining the next
* page of results.
*/
NextToken?: string;
}
export namespace ListDatasetsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDatasetsResponse): any => ({
...obj,
});
}
/**
* A request for usage information on an
* identity pool.
*/
export interface ListIdentityPoolUsageRequest {
/**
* A pagination token for obtaining
* the next page of results.
*/
NextToken?: string;
/**
* The maximum number of results to
* be returned.
*/
MaxResults?: number;
}
export namespace ListIdentityPoolUsageRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListIdentityPoolUsageRequest): any => ({
...obj,
});
}
/**
* Returned for a successful
* ListIdentityPoolUsage request.
*/
export interface ListIdentityPoolUsageResponse {
/**
* Usage information for
* the identity pools.
*/
IdentityPoolUsages?: IdentityPoolUsage[];
/**
* The maximum number of results to
* be returned.
*/
MaxResults?: number;
/**
* Total number of identities for the
* identity pool.
*/
Count?: number;
/**
* A pagination token for obtaining
* the next page of results.
*/
NextToken?: string;
}
export namespace ListIdentityPoolUsageResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListIdentityPoolUsageResponse): any => ({
...obj,
});
}
/**
* A request for a list of records.
*/
export interface ListRecordsRequest {
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityPoolId: string | undefined;
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityId: string | undefined;
/**
* A string of up to 128 characters. Allowed
* characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).
*/
DatasetName: string | undefined;
/**
* The last server sync count for this
* record.
*/
LastSyncCount?: number;
/**
* A pagination token for obtaining the next
* page of results.
*/
NextToken?: string;
/**
* The maximum number of results to be
* returned.
*/
MaxResults?: number;
/**
* A token containing a session ID,
* identity ID, and expiration.
*/
SyncSessionToken?: string;
}
export namespace ListRecordsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListRecordsRequest): any => ({
...obj,
});
}
/**
* The basic data structure of a dataset.
*/
export interface _Record {
/**
* The key for the record.
*/
Key?: string;
/**
* The value for the record.
*/
Value?: string;
/**
* The server sync count for this record.
*/
SyncCount?: number;
/**
* The date on which the record was last
* modified.
*/
LastModifiedDate?: Date;
/**
* The user/device that made the last change to this
* record.
*/
LastModifiedBy?: string;
/**
* The last modified date of the client
* device.
*/
DeviceLastModifiedDate?: Date;
}
export namespace _Record {
/**
* @internal
*/
export const filterSensitiveLog = (obj: _Record): any => ({
...obj,
});
}
/**
* Returned for a successful
* ListRecordsRequest.
*/
export interface ListRecordsResponse {
/**
* A list of all records.
*/
Records?: _Record[];
/**
* A pagination token for obtaining the next
* page of results.
*/
NextToken?: string;
/**
* Total number of records.
*/
Count?: number;
/**
* Server sync count for this
* dataset.
*/
DatasetSyncCount?: number;
/**
* The user/device that made the last
* change to this record.
*/
LastModifiedBy?: string;
/**
* Names of merged
* datasets.
*/
MergedDatasetNames?: string[];
/**
* Indicates whether the dataset
* exists.
*/
DatasetExists?: boolean;
/**
* A boolean value
* specifying whether to delete the dataset locally.
*/
DatasetDeletedAfterRequestedSyncCount?: boolean;
/**
* A token containing a session ID,
* identity ID, and expiration.
*/
SyncSessionToken?: string;
}
export namespace ListRecordsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListRecordsResponse): any => ({
...obj,
});
}
export interface InvalidConfigurationException extends __SmithyException, $MetadataBearer {
name: "InvalidConfigurationException";
$fault: "client";
/**
* Message returned by
* InvalidConfigurationException.
*/
message: string | undefined;
}
export namespace InvalidConfigurationException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InvalidConfigurationException): any => ({
...obj,
});
}
export type Platform = "ADM" | "APNS" | "APNS_SANDBOX" | "GCM";
/**
* <p>A request to RegisterDevice.</p>
*/
export interface RegisterDeviceRequest {
/**
* <p>A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by
* Amazon Cognito. Here, the ID of the pool that the identity belongs to.</p>
*/
IdentityPoolId: string | undefined;
/**
* <p>The unique ID for this identity.</p>
*/
IdentityId: string | undefined;
/**
* <p>The SNS platform type (e.g. GCM, SDM, APNS, APNS_SANDBOX).</p>
*/
Platform: Platform | string | undefined;
/**
* <p>The push token.</p>
*/
Token: string | undefined;
}
export namespace RegisterDeviceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: RegisterDeviceRequest): any => ({
...obj,
});
}
/**
* <p>Response to a RegisterDevice request.</p>
*/
export interface RegisterDeviceResponse {
/**
* <p>The unique ID generated for this device by Cognito.</p>
*/
DeviceId?: string;
}
export namespace RegisterDeviceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: RegisterDeviceResponse): any => ({
...obj,
});
}
/**
* <p>A request to configure Cognito Events"</p>"
*/
export interface SetCognitoEventsRequest {
/**
* <p>The Cognito Identity Pool to use when configuring Cognito Events</p>
*/
IdentityPoolId: string | undefined;
/**
* <p>The events to configure</p>
*/
Events: { [key: string]: string } | undefined;
}
export namespace SetCognitoEventsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SetCognitoEventsRequest): any => ({
...obj,
});
}
/**
* <p>Thrown if there are parallel requests to modify a resource.</p>
*/
export interface ConcurrentModificationException extends __SmithyException, $MetadataBearer {
name: "ConcurrentModificationException";
$fault: "client";
/**
* <p>The message returned by a ConcurrentModicationException.</p>
*/
message: string | undefined;
}
export namespace ConcurrentModificationException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ConcurrentModificationException): any => ({
...obj,
});
}
/**
* <p>The input for the SetIdentityPoolConfiguration operation.</p>
*/
export interface SetIdentityPoolConfigurationRequest {
/**
* <p>A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by
* Amazon Cognito. This is the ID of the pool to modify.</p>
*/
IdentityPoolId: string | undefined;
/**
* <p>Options to apply to this identity pool for push synchronization.</p>
*/
PushSync?: PushSync;
/**
* Options to apply to this identity pool for Amazon Cognito streams.
*/
CognitoStreams?: CognitoStreams;
}
export namespace SetIdentityPoolConfigurationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SetIdentityPoolConfigurationRequest): any => ({
...obj,
});
}
/**
* <p>The output for the SetIdentityPoolConfiguration operation</p>
*/
export interface SetIdentityPoolConfigurationResponse {
/**
* <p>A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by
* Amazon Cognito.</p>
*/
IdentityPoolId?: string;
/**
* <p>Options to apply to this identity pool for push synchronization.</p>
*/
PushSync?: PushSync;
/**
* Options to apply to this identity pool for Amazon Cognito streams.
*/
CognitoStreams?: CognitoStreams;
}
export namespace SetIdentityPoolConfigurationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SetIdentityPoolConfigurationResponse): any => ({
...obj,
});
}
/**
* <p>A request to SubscribeToDatasetRequest.</p>
*/
export interface SubscribeToDatasetRequest {
/**
* <p>A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by
* Amazon Cognito. The ID of the pool to which the identity belongs.</p>
*/
IdentityPoolId: string | undefined;
/**
* <p>Unique ID for this identity.</p>
*/
IdentityId: string | undefined;
/**
* <p>The name of the dataset to subcribe to.</p>
*/
DatasetName: string | undefined;
/**
* <p>The unique ID generated for this device by Cognito.</p>
*/
DeviceId: string | undefined;
}
export namespace SubscribeToDatasetRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SubscribeToDatasetRequest): any => ({
...obj,
});
}
/**
* <p>Response to a SubscribeToDataset request.</p>
*/
export interface SubscribeToDatasetResponse {}
export namespace SubscribeToDatasetResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SubscribeToDatasetResponse): any => ({
...obj,
});
}
/**
* <p>A request to UnsubscribeFromDataset.</p>
*/
export interface UnsubscribeFromDatasetRequest {
/**
* <p>A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by
* Amazon Cognito. The ID of the pool to which this identity belongs.</p>
*/
IdentityPoolId: string | undefined;
/**
* <p>Unique ID for this identity.</p>
*/
IdentityId: string | undefined;
/**
* <p>The name of the dataset from which to unsubcribe.</p>
*/
DatasetName: string | undefined;
/**
* <p>The unique ID generated for this device by Cognito.</p>
*/
DeviceId: string | undefined;
}
export namespace UnsubscribeFromDatasetRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UnsubscribeFromDatasetRequest): any => ({
...obj,
});
}
/**
* <p>Response to an UnsubscribeFromDataset request.</p>
*/
export interface UnsubscribeFromDatasetResponse {}
export namespace UnsubscribeFromDatasetResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UnsubscribeFromDatasetResponse): any => ({
...obj,
});
}
/**
* <p>The AWS Lambda function returned invalid output or an exception.</p>
*/
export interface InvalidLambdaFunctionOutputException extends __SmithyException, $MetadataBearer {
name: "InvalidLambdaFunctionOutputException";
$fault: "client";
/**
* <p>A message returned when an InvalidLambdaFunctionOutputException occurs</p>
*/
message: string | undefined;
}
export namespace InvalidLambdaFunctionOutputException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InvalidLambdaFunctionOutputException): any => ({
...obj,
});
}
/**
* <p>AWS Lambda throttled your account, please contact AWS Support</p>
*/
export interface LambdaThrottledException extends __SmithyException, $MetadataBearer {
name: "LambdaThrottledException";
$fault: "client";
/**
* <p>A message returned when an LambdaThrottledException is thrown</p>
*/
message: string | undefined;
}
export namespace LambdaThrottledException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: LambdaThrottledException): any => ({
...obj,
});
}
/**
* Thrown when the limit on the number of objects or
* operations has been exceeded.
*/
export interface LimitExceededException extends __SmithyException, $MetadataBearer {
name: "LimitExceededException";
$fault: "client";
/**
* Message returned by
* LimitExceededException.
*/
message: string | undefined;
}
export namespace LimitExceededException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: LimitExceededException): any => ({
...obj,
});
}
export type Operation = "remove" | "replace";
/**
* An update operation for a record.
*/
export interface RecordPatch {
/**
* An operation, either replace or remove.
*/
Op: Operation | string | undefined;
/**
* The key associated with the record patch.
*/
Key: string | undefined;
/**
* The value associated with the record
* patch.
*/
Value?: string;
/**
* Last known server sync count for this record. Set
* to 0 if unknown.
*/
SyncCount: number | undefined;
/**
* The last modified date of the client
* device.
*/
DeviceLastModifiedDate?: Date;
}
export namespace RecordPatch {
/**
* @internal
*/
export const filterSensitiveLog = (obj: RecordPatch): any => ({
...obj,
});
}
/**
* A request to post updates to records or add and
* delete records for a dataset and user.
*/
export interface UpdateRecordsRequest {
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityPoolId: string | undefined;
/**
* A name-spaced GUID (for example,
* us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is
* unique within a region.
*/
IdentityId: string | undefined;
/**
* A string of up to 128 characters.
* Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.'
* (dot).
*/
DatasetName: string | undefined;
/**
* <p>The unique ID generated for this device by Cognito.</p>
*/
DeviceId?: string;
/**
* A list of patch
* operations.
*/
RecordPatches?: RecordPatch[];
/**
* The SyncSessionToken returned by a
* previous call to ListRecords for this dataset and identity.
*/
SyncSessionToken: string | undefined;
/**
* Intended to supply a device ID that
* will populate the lastModifiedBy field referenced in other methods. The
* ClientContext field is not yet implemented.
*/
ClientContext?: string;
}
export namespace UpdateRecordsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateRecordsRequest): any => ({
...obj,
});
}
/**
* Returned for a successful
* UpdateRecordsRequest.
*/
export interface UpdateRecordsResponse {
/**
* A list of records that have been
* updated.
*/
Records?: _Record[];
}
export namespace UpdateRecordsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateRecordsResponse): any => ({
...obj,
});
} | the_stack |
declare module 'steam-user' {
import { EventEmitter } from 'events';
import SteamID from 'steamid';
interface Events {
loggedOn: () => void;
webSession: (sessionID: string, cookies: string) => void;
accountLimitations: (
limited: boolean,
communityBanned: boolean,
locked: boolean,
canInviteFriends: boolean
) => void;
friendMessage: (senderID: SteamID, message: string) => void;
friendRelationship: (steamID: SteamID, relationship: number) => void;
groupRelationship: (groupID: SteamID, relationship: number) => void;
steamGuard: (domain: string, callback: (authCode: string) => void, lastCodeWrong: boolean) => void;
loginKey: (loginKey: string) => void;
newItems: (count: number) => void;
error: (err: Error) => void;
}
interface GameIdAndExtra {
game_id: number;
game_extra_info: string;
}
type GameId = number;
type GameInfo = string;
type GamePlayed = GameId | GameInfo | GameIdAndExtra;
type GamesPlayed = GamePlayed[];
type Apps = GamePlayed | GamesPlayed;
export enum EResult {
Invalid = 0,
OK = 1,
Fail = 2,
NoConnection = 3,
InvalidPassword = 5,
LoggedInElsewhere = 6,
InvalidProtocolVer = 7,
InvalidParam = 8,
FileNotFound = 9,
Busy = 10,
InvalidState = 11,
InvalidName = 12,
InvalidEmail = 13,
DuplicateName = 14,
AccessDenied = 15,
Timeout = 16,
Banned = 17,
AccountNotFound = 18,
InvalidSteamID = 19,
ServiceUnavailable = 20,
NotLoggedOn = 21,
Pending = 22,
EncryptionFailure = 23,
InsufficientPrivilege = 24,
LimitExceeded = 25,
Revoked = 26,
Expired = 27,
AlreadyRedeemed = 28,
DuplicateRequest = 29,
AlreadyOwned = 30,
IPNotFound = 31,
PersistFailed = 32,
LockingFailed = 33,
LogonSessionReplaced = 34,
ConnectFailed = 35,
HandshakeFailed = 36,
IOFailure = 37,
RemoteDisconnect = 38,
ShoppingCartNotFound = 39,
Blocked = 40,
Ignored = 41,
NoMatch = 42,
AccountDisabled = 43,
ServiceReadOnly = 44,
AccountNotFeatured = 45,
AdministratorOK = 46,
ContentVersion = 47,
TryAnotherCM = 48,
PasswordRequiredToKickSession = 49,
AlreadyLoggedInElsewhere = 50,
Suspended = 51,
Cancelled = 52,
DataCorruption = 53,
DiskFull = 54,
RemoteCallFailed = 55,
PasswordNotSet = 56, // removed "renamed to PasswordUnset"
PasswordUnset = 56,
ExternalAccountUnlinked = 57,
PSNTicketInvalid = 58,
ExternalAccountAlreadyLinked = 59,
RemoteFileConflict = 60,
IllegalPassword = 61,
SameAsPreviousValue = 62,
AccountLogonDenied = 63,
CannotUseOldPassword = 64,
InvalidLoginAuthCode = 65,
AccountLogonDeniedNoMailSent = 66, // removed "renamed to AccountLogonDeniedNoMail"
AccountLogonDeniedNoMail = 66,
HardwareNotCapableOfIPT = 67,
IPTInitError = 68,
ParentalControlRestricted = 69,
FacebookQueryError = 70,
ExpiredLoginAuthCode = 71,
IPLoginRestrictionFailed = 72,
AccountLocked = 73, // removed "renamed to AccountLockedDown"
AccountLockedDown = 73,
AccountLogonDeniedVerifiedEmailRequired = 74,
NoMatchingURL = 75,
BadResponse = 76,
RequirePasswordReEntry = 77,
ValueOutOfRange = 78,
UnexpectedError = 79,
Disabled = 80,
InvalidCEGSubmission = 81,
RestrictedDevice = 82,
RegionLocked = 83,
RateLimitExceeded = 84,
AccountLogonDeniedNeedTwoFactorCode = 85, // removed "renamed to AccountLoginDeniedNeedTwoFactor"
AccountLoginDeniedNeedTwoFactor = 85,
ItemOrEntryHasBeenDeleted = 86, // removed "renamed to ItemDeleted"
ItemDeleted = 86,
AccountLoginDeniedThrottle = 87,
TwoFactorCodeMismatch = 88,
TwoFactorActivationCodeMismatch = 89,
AccountAssociatedToMultiplePlayers = 90, // removed "renamed to AccountAssociatedToMultiplePartners"
AccountAssociatedToMultiplePartners = 90,
NotModified = 91,
NoMobileDeviceAvailable = 92, // removed "renamed to NoMobileDevice"
NoMobileDevice = 92,
TimeIsOutOfSync = 93, // removed "renamed to TimeNotSynced"
TimeNotSynced = 93,
SMSCodeFailed = 94,
TooManyAccountsAccessThisResource = 95, // removed "renamed to AccountLimitExceeded"
AccountLimitExceeded = 95,
AccountActivityLimitExceeded = 96,
PhoneActivityLimitExceeded = 97,
RefundToWallet = 98,
EmailSendFailure = 99,
NotSettled = 100,
NeedCaptcha = 101,
GSLTDenied = 102,
GSOwnerDenied = 103,
InvalidItemType = 104,
IPBanned = 105,
GSLTExpired = 106,
InsufficientFunds = 107,
TooManyPending = 108,
NoSiteLicensesFound = 109,
WGNetworkSendExceeded = 110,
AccountNotFriends = 111,
LimitedUserAccount = 112,
CantRemoveItem = 113,
AccountHasBeenDeleted = 114,
AccountHasAnExistingUserCancelledLicense = 115,
DeniedDueToCommunityCooldown = 116,
NoLauncherSpecified = 117,
MustAgreeToSSA = 118,
ClientNoLongerSupported = 119
}
export enum EPersonaState {
Offline = 0,
Online = 1,
Busy = 2,
Away = 3,
Snooze = 4,
LookingToTrade = 5,
LookingToPlay = 6,
Max = 7
}
export enum EClanRelationship {
None = 0,
Blocked = 1,
Invited = 2,
Member = 3,
Kicked = 4,
KickAcknowledged = 5
}
export enum EFriendRelationship {
None = 0,
Blocked = 1,
RequestRecipient = 2,
Friend = 3,
RequestInitiator = 4,
Ignored = 5,
IgnoredFriend = 6,
SuggestedFriend = 7,
Max = 8
}
export enum EGameIdType {
App = '0',
GameMod = '1',
Shortcut = '2',
P2P = '3'
}
export enum EPersonaStateFlag {
HasRichPresence = 1,
InJoinableGame = 2,
Golden = 4, // removed "no longer has any effect"
OnlineUsingWeb = 256, // removed "renamed to ClientTypeWeb"
ClientTypeWeb = 256,
OnlineUsingMobile = 512, // removed "renamed to ClientTypeMobile"
ClientTypeMobile = 512,
OnlineUsingBigPicture = 1024, // removed "renamed to ClientTypeTenfoot"
ClientTypeTenfoot = 1024,
OnlineUsingVR = 2048, // removed "renamed to ClientTypeVR"
ClientTypeVR = 2048,
LaunchTypeGamepad = 4096
}
// https://github.com/DoctorMcKay/node-steam-user/wiki/SteamChatRoomClient
enum EChatRoomJoinState {
Default = 0,
None = 1,
Joined = 2
}
enum EChatRoomGroupRank {
Default = 0,
Viewer = 10,
Guest = 15,
Member = 20,
Moderator = 30,
Officer = 40,
Owner = 50
}
enum EChatRoomNotificationLevel {
Invalid = 0,
None = 1,
MentionMe = 2,
MentionAll = 3,
AllMessages = 4
}
interface ChatRoomGroupSummary {
chat_rooms: ChatRoomState;
top_members: SteamID[];
chat_group_id: string;
chat_group_name: string;
active_member_count: number;
active_voice_member_count: number;
default_chat_id: string;
chat_group_tagline: string;
appid: GameId | null;
steamid_owner: SteamID;
watching_broadcast_steamid: SteamID;
chat_group_avatar_sha: Buffer | null;
chat_group_avatar_url: string | null;
}
interface ChatRoomGroupState {
members: ChatRoomMember[];
chat_rooms: ChatRoomState[];
kicked: ChatRoomMember[];
default_chat_id: string;
header_state: ChatRoomGroupHeaderState;
}
interface UserChatRoomGroupState {
chat_group_id: string;
time_joined: Date;
user_chat_room_state: UserChatRoomState[];
desktop_notification_level: EChatRoomNotificationLevel;
mobile_notification_level: EChatRoomNotificationLevel;
time_last_group_ack: Date | null;
unread_indicator_muted: boolean;
}
interface UserChatRoomState {
chat_id: string;
time_joined: Date;
time_last_ack: Date;
desktop_notification_level: EChatRoomNotificationLevel;
mobile_notification_level: EChatRoomNotificationLevel;
time_last_mention: Date;
unread_indicator_muted: boolean;
time_first_unread: Date;
}
interface ChatRoomGroupHeaderState {
chat_group_id: string;
chat_name: string;
clanid: SteamID | null;
steamid_owner: SteamID;
appid: GameId | null;
tagline: string;
avatar_sha: Buffer | null;
avatar_url: string | null;
default_role_id: string;
roles: ChatRole[];
role_actions: ChatRoleAction[];
}
interface ChatRoomMember {
steamid: SteamID;
state: EChatRoomJoinState;
rank: EChatRoomGroupRank;
time_kick_expire: Date | null;
role_ids: string[];
}
interface ChatRoomState {
chat_id: string;
chat_name: string;
voice_allowed: boolean;
members_in_voice: SteamID[];
time_last_message: Date;
sort_order: number;
last_message: string;
steamid_last_message: SteamID;
}
interface ChatRole {
role_id: number;
name: string;
ordinal: number;
}
interface ChatRoleAction {
role_id: number;
can_create_rename_delete_channel: boolean;
can_kick: boolean;
can_ban: boolean;
can_invite: boolean;
can_change_tagline_avatar_name: boolean;
can_chat: boolean;
can_view_history: boolean;
can_change_group_roles: boolean;
can_change_user_roles: boolean;
can_mention_all: boolean;
can_set_watching_broadcast: boolean;
}
interface ChatRoomGroup {
[chat_room_group_id: string]: {
group_summary?: ChatRoomGroupSummary;
group_state: ChatRoomGroupState;
};
}
export enum EChatEntryType {
Invalid = 0,
ChatMsg = 1,
Typing = 2,
InviteGame = 3,
Emote = 4, // removed "No longer supported by clients"
LobbyGameStart = 5, // removed "Listen for LobbyGameCreated_t callback instead"
LeftConversation = 6,
Entered = 7,
WasKicked = 8,
WasBanned = 9,
Disconnected = 10,
HistoricalChat = 11,
Reserved1 = 12,
Reserved2 = 13,
LinkBlocked = 14
}
interface BBCodes {
tag: string;
attrs: any;
content: any[];
}
interface IncomingFriendMessage {
steamid_friend: SteamID;
chat_entry_type: EChatEntryType;
from_limited_account: boolean;
message: string;
message_no_bbcode: string;
message_bbcode_parsed: (BBCodes | string)[];
server_timestamp: Date;
ordinal: number;
local_echo: boolean;
low_priority: boolean;
}
interface IncomingChatMessage {
chat_group_id: string;
chat_id: string;
steamid_sender: SteamID;
message: string;
message_no_bbcode: string;
server_timestamp: Date;
ordinal: number;
mentions: ChatMentions | null;
server_message: ServerMessage | null;
chat_name: string;
}
interface ChatMentions {
mention_all: boolean;
mention_here: boolean;
mention_steamids: SteamID[];
}
enum EChatRoomServerMessage {
Invalid = 0,
RenameChatRoom = 1,
Joined = 2,
Parted = 3,
Kicked = 4,
Invited = 5,
InviteDismissed = 8,
ChatRoomTaglineChanged = 9,
ChatRoomAvatarChanged = 10,
AppCustom = 11
}
interface ServerMessage {
message: EChatRoomServerMessage;
string_param: any;
steamid_param: SteamID;
}
export default class SteamUser extends EventEmitter {
steamID: SteamID;
limitations: {
limited: boolean;
communityBanned: boolean;
locked: boolean;
canInviteFriends: boolean;
};
users: Map<
SteamID | string,
{
rich_presence: any[];
player_name: string;
avater_hash: Buffer;
last_logoff: Date;
last_logon: Date;
last_seen_online: Date;
avatar_url_icon: string;
avatar_url_medium: string;
avatar_url_full: string;
persona_state: EPersonaState;
games_played_app_id: number;
game_server_ip: number;
game_server_port: number;
persona_state_flags: number;
online_session_instances: number;
query_port: number;
steamid_source: string;
game_name: string;
gameid: string;
game_data_blob: Buffer;
breadcast_id: string;
game_lobby_id: string;
rich_presence_string: string;
}
>;
myGroups: Map<SteamID | string, EClanRelationship>;
myFriends: Map<SteamID | string, EFriendRelationship>;
chat: {
// getGroups(callback: (err?: Error | null, response?: ChatRoomGroup) => void): void;
// setSessionActiveGroups(groupIDs: string[], callback: (err?: Error, response?: ChatRoomGroup) => void): void;
sendFriendMessage(
steamID: SteamID | string,
message: string,
options?: { chatEntryType?: number; containsBbCode?: boolean },
callback?: (
err: Error,
response?: { modified_message: string; server_timestamp: Date; ordinal: number }
) => void
): void;
};
autoRelogin: boolean;
_playingAppIds: number[];
logOn(details: {
accountName: string;
password?: string;
loginKey?: string;
twoFactorCode?: string;
rememberPassword?: boolean;
}): void;
webLogOn(): void;
setPersona(state: number, name?: string): void;
gamesPlayed(apps: Apps, force?: boolean): void;
chatMessage(recipient: SteamID | string, message: string): void;
addFriend(steamID: SteamID | string, callback?: (err?: Error, personaName?: string) => void): void;
removeFriend(steamID: SteamID | string): void;
blockUser(steamID: SteamID | string, callback?: (err?: Error) => void): void;
unblockUser(steamID: SteamID | string, callback?: (err?: Error) => void): void;
respondToGroupInvite(groupSteamID: SteamID | string, accept: boolean): void;
logOff(): void;
}
} | the_stack |
import * as THREE from 'three';
import {Polyline} from '../internal_types';
import {assertSvgPathD} from '../testing';
import {ThreeCoordinator} from '../threejs_coordinator';
import {SvgRenderer} from './svg_renderer';
import {ThreeRenderer} from './threejs_renderer';
describe('line_chart_v2/lib/renderer test', () => {
const SVG_NS = 'http://www.w3.org/2000/svg';
const DEFAULT_LINE_OPTIONS = {visible: true, color: '#f00', width: 6};
describe('svg renderer', () => {
let renderer: SvgRenderer;
let el: SVGElement;
beforeEach(() => {
el = document.createElementNS(SVG_NS, 'svg');
renderer = new SvgRenderer(el);
});
it('creates a line', () => {
expect(el.children.length).toBe(0);
renderer.createOrUpdateLineObject(
null,
new Float32Array([0, 10, 10, 100]),
{visible: true, color: '#f00', width: 6}
);
expect(el.children.length).toBe(1);
const path = el.children[0] as SVGPathElement;
expect(path.tagName).toBe('path');
expect(path.getAttribute('d')).toBe('M0,10L10,100');
expect(path.style.stroke).toBe('rgb(255, 0, 0)');
expect(path.style.strokeWidth).toBe('6');
expect(path.style.display).toBe('');
});
it('updates a cached path and styles', () => {
const cacheObject = renderer.createOrUpdateLineObject(
null,
new Float32Array([0, 10, 10, 100]),
{visible: true, color: '#f00', width: 6}
);
renderer.createOrUpdateLineObject(
cacheObject,
new Float32Array([0, 5, 5, 50]),
{visible: true, color: '#0f0', width: 3}
);
expect(el.children.length).toBe(1);
const path = el.children[0] as SVGPathElement;
expect(path.tagName).toBe('path');
expect(path.getAttribute('d')).toBe('M0,5L5,50');
expect(path.style.stroke).toBe('rgb(0, 255, 0)');
expect(path.style.strokeWidth).toBe('3');
expect(path.style.display).toBe('');
});
it('updates a cached path to an empty polyline', () => {
const cacheObject = renderer.createOrUpdateLineObject(
null,
new Float32Array([0, 10, 10, 100]),
{visible: true, color: '#f00', width: 6}
);
renderer.createOrUpdateLineObject(cacheObject, new Float32Array(0), {
visible: true,
color: '#0f0',
width: 3,
});
expect(el.children.length).toBe(1);
const path = el.children[0] as SVGPathElement;
expect(path.tagName).toBe('path');
expect(path.getAttribute('d')).toBe('');
// While it is possible to update minimally and only change the path or visibility,
// such optimization is a bit too premature without a clear benefit.
expect(path.style.stroke).toBe('rgb(0, 255, 0)');
expect(path.style.strokeWidth).toBe('3');
expect(path.style.display).toBe('');
});
it('skips updating path and color if visibility goes from true to false', () => {
const cacheObject = renderer.createOrUpdateLineObject(
null,
new Float32Array([0, 10, 10, 100]),
{visible: true, color: '#f00', width: 6}
);
renderer.createOrUpdateLineObject(
cacheObject,
new Float32Array([0, 5, 5, 50]),
{visible: false, color: '#0f0', width: 3}
);
expect(el.children.length).toBe(1);
const path = el.children[0] as SVGPathElement;
expect(path.tagName).toBe('path');
expect(path.style.display).toBe('none');
expect(path.getAttribute('d')).toBe('M0,10L10,100');
expect(path.style.stroke).toBe('rgb(255, 0, 0)');
});
it('skips rendering DOM when a new cacheId starts with visible=false', () => {
renderer.createOrUpdateLineObject(
null,
new Float32Array([0, 10, 10, 100]),
{visible: false, color: '#f00', width: 6}
);
expect(el.children.length).toBe(0);
});
describe('triangle', () => {
it('creates a path with fill', () => {
renderer.createOrUpdateTriangleObject(
null,
{x: 10, y: 100},
{visible: true, color: '#f00', size: 6}
);
expect(el.children.length).toBe(1);
const path = el.children[0] as SVGPathElement;
expect(path.tagName).toBe('path');
expect(path.style.display).toBe('');
assertSvgPathD(path, [
[7, 102],
[13, 102],
[10, 97],
]);
expect(path.style.fill).toBe('rgb(255, 0, 0)');
});
it('updates path and styles', () => {
const object = renderer.createOrUpdateTriangleObject(
null,
{x: 10, y: 100},
{visible: true, color: '#f00', size: 6}
);
renderer.createOrUpdateTriangleObject(
object,
{x: 20, y: 50},
{visible: true, color: '#0f0', size: 10}
);
expect(el.children.length).toBe(1);
const path = el.children[0] as SVGPathElement;
expect(path.tagName).toBe('path');
expect(path.style.display).toBe('');
assertSvgPathD(path, [
[15, 53],
[25, 53],
[20, 44],
]);
expect(path.style.fill).toBe('rgb(0, 255, 0)');
});
it('does not create an object if previously null object is invisible', () => {
const object = renderer.createOrUpdateTriangleObject(
null,
{x: 10, y: 100},
{visible: false, color: '#f00', size: 6}
);
expect(object).toBeNull();
expect(el.children.length).toBe(0);
});
});
describe('circle', () => {
it('creates a circle with fill', () => {
renderer.createOrUpdateCircleObject(
null,
{x: 10, y: 100},
{visible: true, color: '#f00', radius: 5}
);
expect(el.children.length).toBe(1);
const path = el.children[0] as SVGPathElement;
expect(path.tagName).toBe('circle');
expect(path.style.display).toBe('');
expect(path.getAttribute('cx')).toBe('10');
expect(path.getAttribute('cy')).toBe('100');
expect(path.getAttribute('r')).toBe('5');
expect(path.style.fill).toBe('rgb(255, 0, 0)');
});
it('updates a circle', () => {
const obj = renderer.createOrUpdateCircleObject(
null,
{x: 10, y: 100},
{visible: true, color: '#f00', radius: 5}
);
renderer.createOrUpdateCircleObject(
obj,
{x: 100, y: 1},
{visible: true, color: '#00f', radius: 1}
);
expect(el.children.length).toBe(1);
const path = el.children[0] as SVGPathElement;
expect(path.tagName).toBe('circle');
expect(path.style.display).toBe('');
expect(path.getAttribute('cx')).toBe('100');
expect(path.getAttribute('cy')).toBe('1');
expect(path.getAttribute('r')).toBe('1');
expect(path.style.fill).toBe('rgb(0, 0, 255)');
});
});
describe('trapezoid', () => {
it('creates a path with the right shape', () => {
renderer.createOrUpdateTrapezoidObject(
null,
{x: 10, y: 100},
{x: 30, y: 100},
{visible: true, color: '#f00', altitude: 6}
);
expect(el.children.length).toBe(1);
const path = el.children[0] as SVGPathElement;
expect(path.tagName).toBe('path');
expect(path.style.display).toBe('');
assertSvgPathD(path, [
[7, 103],
[10, 97],
[30, 97],
[33, 103],
]);
expect(path.style.fill).toBe('rgb(255, 0, 0)');
});
it('updates the path', () => {
const obj = renderer.createOrUpdateTrapezoidObject(
null,
{x: 10, y: 100},
{x: 30, y: 100},
{visible: true, color: '#f00', altitude: 6}
);
renderer.createOrUpdateTrapezoidObject(
obj,
{x: 10, y: 100},
{x: 50, y: 100},
{visible: true, color: '#00f', altitude: 6}
);
expect(el.children.length).toBe(1);
const path = el.children[0] as SVGPathElement;
expect(path.tagName).toBe('path');
expect(path.style.display).toBe('');
assertSvgPathD(path, [
[7, 103],
[10, 97],
[50, 97],
[53, 103],
]);
expect(path.style.fill).toBe('rgb(0, 0, 255)');
});
});
});
describe('threejs renderer', () => {
let renderer: ThreeRenderer;
let scene: THREE.Scene;
function assertLine(line: THREE.Mesh, polyline: Polyline) {
const geometry = line.geometry as THREE.BufferGeometry;
const positions = geometry.getAttribute(
'position'
) as THREE.BufferAttribute;
// Each segment has 2 triangles, each with 3 vertices, each with 3
// coordinates.
const expectedNumSegments = Math.max(polyline.length / 2 - 1, 0);
const expectedNumCoordinates = expectedNumSegments * 2 * 3 * 3;
expect(positions.array.length).toBe(expectedNumCoordinates);
for (let i = 2; i < positions.array.length; i += 3) {
const actualZ = positions.array[i];
expect(actualZ).toBe(0);
}
}
function assertPositions(
geometry: THREE.BufferGeometry,
rounded: Float32Array
) {
const position = geometry.getAttribute(
'position'
) as THREE.BufferAttribute;
expect(position.array.length).toBe(rounded.length);
for (const [index, val] of rounded.entries()) {
expect(position.array[index]).toBeCloseTo(val, 0);
}
}
function assertMaterial(
obj: THREE.Mesh | THREE.Line,
longHexString: string,
visibility: boolean
) {
const material = obj.material as THREE.MeshBasicMaterial;
expect(material.visible).toBe(visibility);
expect(material.color.getHexString()).toBe(longHexString.slice(1));
}
beforeEach(() => {
scene = new THREE.Scene();
spyOn(THREE, 'Scene').and.returnValue(scene);
const canvas = document.createElement('canvas');
const coordinator = new ThreeCoordinator();
renderer = new ThreeRenderer(canvas, coordinator, 2);
});
it('creates a line', () => {
renderer.createOrUpdateLineObject(
null,
new Float32Array([0, 10, 10, 100]),
{visible: true, color: '#f00', width: 6}
);
expect(scene.children.length).toBe(1);
const lineObject = scene.children[0] as THREE.Mesh;
expect(lineObject).toBeInstanceOf(THREE.Mesh);
assertLine(lineObject, new Float32Array([0, 10, 10, 100]));
assertMaterial(lineObject, '#ff0000', true);
});
it('updates cached path and styles', () => {
const cacheObject = renderer.createOrUpdateLineObject(
null,
new Float32Array([0, 10, 10, 100]),
{visible: true, color: '#f00', width: 6}
);
renderer.createOrUpdateLineObject(
cacheObject,
new Float32Array([0, 5, 5, 50, 10, 100]),
{visible: true, color: '#0f0', width: 3}
);
const lineObject = scene.children[0] as THREE.Mesh;
assertLine(lineObject, new Float32Array([0, 5, 5, 50, 10, 100]));
assertMaterial(lineObject, '#00ff00', true);
});
describe('opacity support', () => {
it('sets opacity adjusted color against #fff when using light mode', () => {
renderer.setUseDarkMode(false);
renderer.createOrUpdateLineObject(
null,
new Float32Array([0, 5, 5, 50]),
{visible: true, color: '#0f0', width: 3, opacity: 0.2}
);
const lineObject = scene.children[0] as THREE.Mesh;
assertMaterial(lineObject, '#ccffcc', true);
});
it('sets opacity adjusted color against dark when using dark mode', () => {
renderer.setUseDarkMode(true);
renderer.createOrUpdateLineObject(
null,
new Float32Array([0, 5, 5, 50]),
{visible: true, color: '#0f0', width: 3, opacity: 0.2}
);
const lineObject = scene.children[0] as THREE.Mesh;
assertMaterial(lineObject, '#334d33', true);
});
it('updates color when tweaking opacity', () => {
const object1 = renderer.createOrUpdateLineObject(
null,
new Float32Array([0, 10, 10, 100]),
{visible: true, color: '#f00', width: 6, opacity: 0.1}
);
const object2 = renderer.createOrUpdateLineObject(
object1,
new Float32Array(0),
{
visible: true,
color: '#f00',
width: 6,
opacity: 0.5,
}
);
const lineObject2 = scene.children[0] as THREE.Mesh;
assertMaterial(lineObject2, '#ff8080', true);
renderer.createOrUpdateLineObject(object2, new Float32Array(0), {
visible: true,
color: '#f00',
width: 6,
opacity: 1,
});
const lineObject3 = scene.children[0] as THREE.Mesh;
assertMaterial(lineObject3, '#ff0000', true);
});
});
it('updates object when going from non-emtpy polyline to an empty one', () => {
const cacheObject = renderer.createOrUpdateLineObject(
null,
new Float32Array([0, 10, 10, 100]),
{visible: true, color: '#f00', width: 6}
);
renderer.createOrUpdateLineObject(cacheObject, new Float32Array(0), {
visible: true,
color: '#0f0',
width: 3,
});
const lineObject = scene.children[0] as THREE.Mesh;
assertLine(lineObject, new Float32Array(0));
assertMaterial(lineObject, '#00ff00', true);
});
it('does not update color and paths when visibility go from true to false', () => {
const cachedObject = renderer.createOrUpdateLineObject(
null,
new Float32Array([0, 10, 10, 100]),
{visible: true, color: '#f00', width: 6}
);
renderer.createOrUpdateLineObject(
cachedObject,
new Float32Array([0, 5, 5, 50, 10, 100]),
{visible: false, color: '#0f0', width: 3}
);
const lineObject = scene.children[0] as THREE.Mesh;
assertLine(lineObject, new Float32Array([0, 10, 10, 100]));
assertMaterial(lineObject, '#ff0000', false);
});
it('skips rendering if render starts with visibility=false ', () => {
renderer.createOrUpdateLineObject(null, new Float32Array([0, 1, 0, 1]), {
...DEFAULT_LINE_OPTIONS,
visible: false,
});
expect(scene.children.length).toBe(0);
});
describe('triangle', () => {
it('creates a Mesh object with path', () => {
renderer.createOrUpdateTriangleObject(
null,
{x: 100, y: 50},
{visible: true, color: '#0f0', size: 10}
);
const obj = scene.children[0] as THREE.Mesh;
assertPositions(
obj.geometry as THREE.BufferGeometry,
new Float32Array([95, 47, 0, 105, 47, 0, 100, 56, 0])
);
assertMaterial(obj, '#00ff00', true);
});
it('updates mesh', () => {
const cache = renderer.createOrUpdateTriangleObject(
null,
{x: 100, y: 50},
{visible: true, color: '#0f0', size: 10}
);
renderer.createOrUpdateTriangleObject(
cache,
{x: 50, y: 100},
{visible: true, color: '#f00', size: 20}
);
const obj = scene.children[0] as THREE.Mesh;
assertPositions(
obj.geometry as THREE.BufferGeometry,
new Float32Array([40, 94, 0, 60, 94, 0, 50, 112, 0])
);
assertMaterial(obj, '#ff0000', true);
});
});
describe('circle', () => {
it('creates a Mesh object with position prop', () => {
renderer.createOrUpdateCircleObject(
null,
{x: 100, y: 50},
{visible: true, color: '#0f0', radius: 10}
);
// Positions are set by CircleBufferGeometry and details do not matter.
const obj = scene.children[0] as THREE.Mesh;
expect(obj.position.x).toBe(100);
expect(obj.position.y).toBe(50);
assertMaterial(obj, '#00ff00', true);
});
it('updates mesh', () => {
const cache = renderer.createOrUpdateCircleObject(
null,
{x: 100, y: 50},
{visible: true, color: '#0f0', radius: 10}
);
renderer.createOrUpdateCircleObject(
cache,
{x: 50, y: 100},
{visible: true, color: '#f00', radius: 20}
);
const obj = scene.children[0] as THREE.Mesh;
expect(obj.position.x).toBe(50);
expect(obj.position.y).toBe(100);
assertMaterial(obj, '#ff0000', true);
});
});
describe('trapezoid', () => {
it('creates a Mesh object with path', () => {
renderer.createOrUpdateTrapezoidObject(
null,
{x: 100, y: 50},
{x: 200, y: 50},
{visible: true, color: '#0f0', altitude: 10}
);
const obj = scene.children[0] as THREE.Mesh;
assertPositions(
obj.geometry as THREE.BufferGeometry,
new Float32Array([94, 45, 0, 100, 55, 0, 200, 55, 0, 206, 45, 0])
);
assertMaterial(obj, '#00ff00', true);
});
it('updates mesh', () => {
const cache = renderer.createOrUpdateTrapezoidObject(
null,
{x: 100, y: 50},
{x: 200, y: 50},
{visible: true, color: '#0f0', altitude: 10}
);
renderer.createOrUpdateTrapezoidObject(
cache,
{x: 100, y: 50},
{x: 300, y: 50},
{visible: true, color: '#f00', altitude: 10}
);
const obj = scene.children[0] as THREE.Mesh;
assertPositions(
obj.geometry as THREE.BufferGeometry,
new Float32Array([94, 45, 0, 100, 55, 0, 300, 55, 0, 306, 45, 0])
);
assertMaterial(obj, '#ff0000', true);
});
});
});
}); | the_stack |
import { alert } from 'vs/base/browser/ui/aria/aria';
import { IdleValue, raceCancellation } from 'vs/base/common/async';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { onUnexpectedError } from 'vs/base/common/errors';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { assertType } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { CodeEditorStateFlag, EditorStateCancellationTokenSource } from 'vs/editor/browser/core/editorState';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorAction, EditorCommand, registerEditorAction, registerEditorCommand, registerEditorContribution, registerModelAndPositionCommand, ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { IBulkEditService, ResourceEdit } from 'vs/editor/browser/services/bulkEditService';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { IPosition, Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { ITextModel } from 'vs/editor/common/model';
import { Rejection, RenameLocation, RenameProvider, RenameProviderRegistry, WorkspaceEdit } from 'vs/editor/common/modes';
import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfigurationService';
import { MessageController } from 'vs/editor/contrib/message/messageController';
import * as nls from 'vs/nls';
import { ConfigurationScope, Extensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ILogService } from 'vs/platform/log/common/log';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IEditorProgressService } from 'vs/platform/progress/common/progress';
import { Registry } from 'vs/platform/registry/common/platform';
import { CONTEXT_RENAME_INPUT_VISIBLE, RenameInputField } from './renameInputField';
class RenameSkeleton {
private readonly _providers: RenameProvider[];
private _providerRenameIdx: number = 0;
constructor(
private readonly model: ITextModel,
private readonly position: Position
) {
this._providers = RenameProviderRegistry.ordered(model);
}
hasProvider() {
return this._providers.length > 0;
}
async resolveRenameLocation(token: CancellationToken): Promise<RenameLocation & Rejection | undefined> {
const rejects: string[] = [];
for (this._providerRenameIdx = 0; this._providerRenameIdx < this._providers.length; this._providerRenameIdx++) {
const provider = this._providers[this._providerRenameIdx];
if (!provider.resolveRenameLocation) {
break;
}
let res = await provider.resolveRenameLocation(this.model, this.position, token);
if (!res) {
continue;
}
if (res.rejectReason) {
rejects.push(res.rejectReason);
continue;
}
return res;
}
const word = this.model.getWordAtPosition(this.position);
if (!word) {
return {
range: Range.fromPositions(this.position),
text: '',
rejectReason: rejects.length > 0 ? rejects.join('\n') : undefined
};
}
return {
range: new Range(this.position.lineNumber, word.startColumn, this.position.lineNumber, word.endColumn),
text: word.word,
rejectReason: rejects.length > 0 ? rejects.join('\n') : undefined
};
}
async provideRenameEdits(newName: string, token: CancellationToken): Promise<WorkspaceEdit & Rejection> {
return this._provideRenameEdits(newName, this._providerRenameIdx, [], token);
}
private async _provideRenameEdits(newName: string, i: number, rejects: string[], token: CancellationToken): Promise<WorkspaceEdit & Rejection> {
const provider = this._providers[i];
if (!provider) {
return {
edits: [],
rejectReason: rejects.join('\n')
};
}
const result = await provider.provideRenameEdits(this.model, this.position, newName, token);
if (!result) {
return this._provideRenameEdits(newName, i + 1, rejects.concat(nls.localize('no result', "No result.")), token);
} else if (result.rejectReason) {
return this._provideRenameEdits(newName, i + 1, rejects.concat(result.rejectReason), token);
}
return result;
}
}
export async function rename(model: ITextModel, position: Position, newName: string): Promise<WorkspaceEdit & Rejection> {
const skeleton = new RenameSkeleton(model, position);
const loc = await skeleton.resolveRenameLocation(CancellationToken.None);
if (loc?.rejectReason) {
return { edits: [], rejectReason: loc.rejectReason };
}
return skeleton.provideRenameEdits(newName, CancellationToken.None);
}
// --- register actions and commands
class RenameController implements IEditorContribution {
public static readonly ID = 'editor.contrib.renameController';
static get(editor: ICodeEditor): RenameController {
return editor.getContribution<RenameController>(RenameController.ID);
}
private readonly _renameInputField: IdleValue<RenameInputField>;
private readonly _dispoableStore = new DisposableStore();
private _cts: CancellationTokenSource = new CancellationTokenSource();
constructor(
private readonly editor: ICodeEditor,
@IInstantiationService private readonly _instaService: IInstantiationService,
@INotificationService private readonly _notificationService: INotificationService,
@IBulkEditService private readonly _bulkEditService: IBulkEditService,
@IEditorProgressService private readonly _progressService: IEditorProgressService,
@ILogService private readonly _logService: ILogService,
@ITextResourceConfigurationService private readonly _configService: ITextResourceConfigurationService,
) {
this._renameInputField = this._dispoableStore.add(new IdleValue(() => this._dispoableStore.add(this._instaService.createInstance(RenameInputField, this.editor, ['acceptRenameInput', 'acceptRenameInputWithPreview']))));
}
dispose(): void {
this._dispoableStore.dispose();
this._cts.dispose(true);
}
async run(): Promise<void> {
this._cts.dispose(true);
if (!this.editor.hasModel()) {
return undefined;
}
const position = this.editor.getPosition();
const skeleton = new RenameSkeleton(this.editor.getModel(), position);
if (!skeleton.hasProvider()) {
return undefined;
}
this._cts = new EditorStateCancellationTokenSource(this.editor, CodeEditorStateFlag.Position | CodeEditorStateFlag.Value);
// resolve rename location
let loc: RenameLocation & Rejection | undefined;
try {
const resolveLocationOperation = skeleton.resolveRenameLocation(this._cts.token);
this._progressService.showWhile(resolveLocationOperation, 250);
loc = await resolveLocationOperation;
} catch (e) {
MessageController.get(this.editor).showMessage(e || nls.localize('resolveRenameLocationFailed', "An unknown error occurred while resolving rename location"), position);
return undefined;
}
if (!loc) {
return undefined;
}
if (loc.rejectReason) {
MessageController.get(this.editor).showMessage(loc.rejectReason, position);
return undefined;
}
if (this._cts.token.isCancellationRequested) {
return undefined;
}
this._cts.dispose();
this._cts = new EditorStateCancellationTokenSource(this.editor, CodeEditorStateFlag.Position | CodeEditorStateFlag.Value, loc.range);
// do rename at location
let selection = this.editor.getSelection();
let selectionStart = 0;
let selectionEnd = loc.text.length;
if (!Range.isEmpty(selection) && !Range.spansMultipleLines(selection) && Range.containsRange(loc.range, selection)) {
selectionStart = Math.max(0, selection.startColumn - loc.range.startColumn);
selectionEnd = Math.min(loc.range.endColumn, selection.endColumn) - loc.range.startColumn;
}
const supportPreview = this._bulkEditService.hasPreviewHandler() && this._configService.getValue<boolean>(this.editor.getModel().uri, 'editor.rename.enablePreview');
const inputFieldResult = await this._renameInputField.value.getInput(loc.range, loc.text, selectionStart, selectionEnd, supportPreview, this._cts.token);
// no result, only hint to focus the editor or not
if (typeof inputFieldResult === 'boolean') {
if (inputFieldResult) {
this.editor.focus();
}
return undefined;
}
this.editor.focus();
const renameOperation = raceCancellation(skeleton.provideRenameEdits(inputFieldResult.newName, this._cts.token), this._cts.token).then(async renameResult => {
if (!renameResult || !this.editor.hasModel()) {
return;
}
if (renameResult.rejectReason) {
this._notificationService.info(renameResult.rejectReason);
return;
}
// collapse selection to active end
this.editor.setSelection(Range.fromPositions(this.editor.getSelection().getPosition()));
this._bulkEditService.apply(ResourceEdit.convert(renameResult), {
editor: this.editor,
showPreview: inputFieldResult.wantsPreview,
label: nls.localize('label', "Renaming '{0}'", loc?.text),
quotableLabel: nls.localize('quotableLabel', "Renaming {0}", loc?.text),
}).then(result => {
if (result.ariaSummary) {
alert(nls.localize('aria', "Successfully renamed '{0}' to '{1}'. Summary: {2}", loc!.text, inputFieldResult.newName, result.ariaSummary));
}
}).catch(err => {
this._notificationService.error(nls.localize('rename.failedApply', "Rename failed to apply edits"));
this._logService.error(err);
});
}, err => {
this._notificationService.error(nls.localize('rename.failed', "Rename failed to compute edits"));
this._logService.error(err);
});
this._progressService.showWhile(renameOperation, 250);
return renameOperation;
}
acceptRenameInput(wantsPreview: boolean): void {
this._renameInputField.value.acceptInput(wantsPreview);
}
cancelRenameInput(): void {
this._renameInputField.value.cancelInput(true);
}
}
// ---- action implementation
export class RenameAction extends EditorAction {
constructor() {
super({
id: 'editor.action.rename',
label: nls.localize('rename.label', "Rename Symbol"),
alias: 'Rename Symbol',
precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasRenameProvider),
kbOpts: {
kbExpr: EditorContextKeys.editorTextFocus,
primary: KeyCode.F2,
weight: KeybindingWeight.EditorContrib
},
contextMenuOpts: {
group: '1_modification',
order: 1.1
}
});
}
override runCommand(accessor: ServicesAccessor, args: [URI, IPosition]): void | Promise<void> {
const editorService = accessor.get(ICodeEditorService);
const [uri, pos] = Array.isArray(args) && args || [undefined, undefined];
if (URI.isUri(uri) && Position.isIPosition(pos)) {
return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then(editor => {
if (!editor) {
return;
}
editor.setPosition(pos);
editor.invokeWithinContext(accessor => {
this.reportTelemetry(accessor, editor);
return this.run(accessor, editor);
});
}, onUnexpectedError);
}
return super.runCommand(accessor, args);
}
run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> {
const controller = RenameController.get(editor);
if (controller) {
return controller.run();
}
return Promise.resolve();
}
}
registerEditorContribution(RenameController.ID, RenameController);
registerEditorAction(RenameAction);
const RenameCommand = EditorCommand.bindToContribution<RenameController>(RenameController.get);
registerEditorCommand(new RenameCommand({
id: 'acceptRenameInput',
precondition: CONTEXT_RENAME_INPUT_VISIBLE,
handler: x => x.acceptRenameInput(false),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 99,
kbExpr: EditorContextKeys.focus,
primary: KeyCode.Enter
}
}));
registerEditorCommand(new RenameCommand({
id: 'acceptRenameInputWithPreview',
precondition: ContextKeyExpr.and(CONTEXT_RENAME_INPUT_VISIBLE, ContextKeyExpr.has('config.editor.rename.enablePreview')),
handler: x => x.acceptRenameInput(true),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 99,
kbExpr: EditorContextKeys.focus,
primary: KeyMod.Shift + KeyCode.Enter
}
}));
registerEditorCommand(new RenameCommand({
id: 'cancelRenameInput',
precondition: CONTEXT_RENAME_INPUT_VISIBLE,
handler: x => x.cancelRenameInput(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 99,
kbExpr: EditorContextKeys.focus,
primary: KeyCode.Escape,
secondary: [KeyMod.Shift | KeyCode.Escape]
}
}));
// ---- api bridge command
registerModelAndPositionCommand('_executeDocumentRenameProvider', function (model, position, ...args) {
const [newName] = args;
assertType(typeof newName === 'string');
return rename(model, position, newName);
});
registerModelAndPositionCommand('_executePrepareRename', async function (model, position) {
const skeleton = new RenameSkeleton(model, position);
const loc = await skeleton.resolveRenameLocation(CancellationToken.None);
if (loc?.rejectReason) {
throw new Error(loc.rejectReason);
}
return loc;
});
//todo@jrieken use editor options world
Registry.as<IConfigurationRegistry>(Extensions.Configuration).registerConfiguration({
id: 'editor',
properties: {
'editor.rename.enablePreview': {
scope: ConfigurationScope.LANGUAGE_OVERRIDABLE,
description: nls.localize('enablePreview', "Enable/disable the ability to preview changes before renaming"),
default: true,
type: 'boolean'
}
}
}); | the_stack |
import {
window, commands, ViewColumn, Disposable,
Event, Uri, CancellationToken, TextDocumentContentProvider,
EventEmitter, workspace, CompletionItemProvider, ProviderResult,
TextDocument, Position, CompletionItem, CompletionList, CompletionItemKind,
SnippetString, Range
} from 'vscode';
import Resource from './resource';
import * as kebabCaseTAGS from 'element-helper-json-new/element-tags.json';
import * as kebabCaseATTRS from 'element-helper-json-new/element-attributes.json';
const prettyHTML = require('pretty');
const Path = require('path');
const fs = require('fs');
let TAGS = {};
for (const key in kebabCaseTAGS) {
if (kebabCaseTAGS.hasOwnProperty(key)) {
const tag = kebabCaseTAGS[key];
let subtags:Array<string>|undefined = tag.subtags;
TAGS[key] = tag;
let camelCase = toUpperCase(key);
TAGS[camelCase] = JSON.parse(JSON.stringify(kebabCaseTAGS[key]));
if(subtags) {
subtags = subtags.map(item => toUpperCase(item));
TAGS[camelCase].subtags = subtags;
}
}
}
let ATTRS = {};
for (const key in kebabCaseATTRS) {
if (kebabCaseATTRS.hasOwnProperty(key)) {
const element = kebabCaseATTRS[key];
ATTRS[key] = element;
const tagAttrs = key.split('/');
const hasTag = tagAttrs.length > 1;
let tag = '';
let attr = '';
if (hasTag) {
tag = toUpperCase(tagAttrs[0]) + '/';
attr = tagAttrs[1];
ATTRS[tag + attr] = JSON.parse(JSON.stringify(element));
}
}
}
function toUpperCase(key: string): string {
let camelCase = key.replace(/\-(\w)/g, function(all, letter) {
return letter.toUpperCase();
});
camelCase = camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
return camelCase;
}
export const SCHEME = 'element-helper';
export interface Query {
keyword: string
};
export interface TagObject{
text: string,
offset: number
};
export function encodeDocsUri(query?: Query): Uri {
return Uri.parse(`${SCHEME}://search?${JSON.stringify(query)}`);
}
export function decodeDocsUri(uri: Uri): Query {
return <Query>JSON.parse(uri.query);
}
export class App {
private _disposable: Disposable;
public WORD_REG: RegExp = /(-?\d*\.\d\w*)|([^\`\~\!\@\$\^\&\*\(\)\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\s]+)/gi;
getSeletedText() {
let editor = window.activeTextEditor;
if (!editor) {return;}
let selection = editor.selection;
if (selection.isEmpty) {
let text = [];
let range = editor.document.getWordRangeAtPosition(selection.start, this.WORD_REG);
return editor.document.getText(range);
} else {
return editor.document.getText(selection);
}
}
setConfig() {
// https://github.com/Microsoft/vscode/issues/24464
const config = workspace.getConfiguration('editor');
const quickSuggestions = config.get('quickSuggestions');
if(!quickSuggestions["strings"]) {
config.update("quickSuggestions", { "strings": true }, true);
}
}
openHtml(uri: Uri, title) {
return commands.executeCommand('vscode.previewHtml', uri, ViewColumn.Two, title)
.then((success) => {
}, (reason) => {
window.showErrorMessage(reason);
});
}
openDocs(query?: Query, title = 'Element-helper', editor = window.activeTextEditor){
this.openHtml(encodeDocsUri(query), title)
}
dispose() {
this._disposable.dispose();
}
}
const HTML_CONTENT = (query: Query) => {
const filename = Path.join(__dirname, '..', '..', 'package.json');
const data = fs.readFileSync(filename, 'utf8');
const content = JSON.parse(data);
const versions = content.contributes.configuration.properties['element-helper.version']['enum'];
const lastVersion = versions[versions.length - 1];
const config = workspace.getConfiguration('element-helper');
const language = <string>config.get('language');
const version = config.get('version');
let versionText = `${version}/`;
// if (version === lastVersion) {
// versionText = '';
// }
let opts = ['<select class="docs-version">'];
let selected = '';
versions.forEach(item => {
selected = item === version ? ' selected="selected"' : '';
// if language is spanish, verison < 2.0 no documents
if (language === 'es' && item < '2.0') {
} else {
opts.push(`<option${selected} value ="${item}">${item}</option>`);
}
});
opts.push('</select>');
const html = opts.join('');
const path = query.keyword;
const style = fs.readFileSync(Path.join(Resource.RESOURCE_PATH, 'style.css'), 'utf-8');
const componentPath = `${versionText}main.html#/${language}/component/${path}`;
const href = Resource.ELEMENT_HOME_URL + componentPath.replace('main.html', 'index.html');
const iframeSrc = 'file://' + Path.join(Resource.ELEMENT_PATH, componentPath).split(Path.sep).join('/');
const notice = ({
'zh-CN': `版本:${html},在线示例请在浏览器中<a href="${href}">查看</a>`,
'en-US': `Version: ${html}, view online examples in <a href="${href}">browser</a>`,
'es': `Versión: ${html}, ejemplo en línea en la <a href="${href}">vista</a> del navegador`
})[language];
return `
<style type="text/css">${style}</style>
<body class="element-helper-docs-container">
<div class="element-helper-move-mask"></div>
<div class="element-helper-loading-mask">
<div class="element-helper-loading-spinner">
<svg viewBox="25 25 50 50" class="circular">
<circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
</svg>
</div>
</div>
<div class="docs-notice">${notice}</div>
<iframe id="docs-frame" src="${iframeSrc}"></iframe>
<script>
var iframe = document.querySelector('#docs-frame');
var link = document.querySelector('.docs-notice a');
window.addEventListener('message', (e) => {
e.data.loaded && (document.querySelector('.element-helper-loading-mask').style.display = 'none');
if(e.data.hash) {
var pathArr = link.href.split('#');
pathArr.pop();
pathArr.push(e.data.hash);
link.href = pathArr.join('#');
var srcArr = iframe.src.split('#');
srcArr.pop();
srcArr.push(e.data.hash);
iframe.src = srcArr.join('#');
}
}, false);
document.querySelector('.docs-version').addEventListener('change', function() {
var version = this.options[this.selectedIndex].value;
var originalSrc = iframe.src;
var arr = originalSrc.split(new RegExp('/?[0-9.]*/main.html'));
iframe.src = arr.join('/' + version + '/main.html');
link.href = link.href.replace(new RegExp('/?[0-9.]*/index.html'), '/' + version + '/index.html');
}, false);
</script>
</body>`;
};
export class ElementDocsContentProvider implements TextDocumentContentProvider {
private _onDidChange = new EventEmitter<Uri>();
get onDidChange(): Event<Uri> {
return this._onDidChange.event;
}
public update(uri: Uri) {
this._onDidChange.fire(uri);
}
provideTextDocumentContent(uri: Uri, token: CancellationToken): string | Thenable<string> {
return HTML_CONTENT(decodeDocsUri(uri));
}
}
export class ElementCompletionItemProvider implements CompletionItemProvider {
private _document: TextDocument;
private _position: Position;
private tagReg: RegExp = /<([\w-]+)\s*/g;
private attrReg: RegExp = /(?:\(|\s*)(\w+)=['"][^'"]*/;
private tagStartReg: RegExp = /<([\w-]*)$/;
private pugTagStartReg: RegExp = /^\s*[\w-]*$/;
private size: number;
private quotes: string;
getPreTag(): TagObject | undefined {
let line = this._position.line;
let tag: TagObject | string;
let txt = this.getTextBeforePosition(this._position);
while (this._position.line - line < 10 && line >= 0) {
if (line !== this._position.line) {
txt = this._document.lineAt(line).text;
}
tag = this.matchTag(this.tagReg, txt, line);
if (tag === 'break') return;
if (tag) return <TagObject>tag;
line--;
}
return;
}
getPreAttr(): string | undefined {
let txt = this.getTextBeforePosition(this._position).replace(/"[^'"]*(\s*)[^'"]*$/, '');
let end = this._position.character;
let start = txt.lastIndexOf(' ', end) + 1;
let parsedTxt = this._document.getText(new Range(this._position.line, start, this._position.line, end));
return this.matchAttr(this.attrReg, parsedTxt);
}
matchAttr(reg: RegExp, txt: string): string {
let match: RegExpExecArray;
match = reg.exec(txt);
return !/"[^"]*"/.test(txt) && match && match[1];
}
matchTag(reg: RegExp, txt: string, line: number): TagObject | string {
let match: RegExpExecArray;
let arr: TagObject[] = [];
if (/<\/?[-\w]+[^<>]*>[\s\w]*<?\s*[\w-]*$/.test(txt) || (this._position.line === line && (/^\s*[^<]+\s*>[^<\/>]*$/.test(txt) || /[^<>]*<$/.test(txt[txt.length - 1])))) {
return 'break';
}
while((match = reg.exec(txt))) {
arr.push({
text: match[1],
offset: this._document.offsetAt(new Position(line, match.index))
});
}
return arr.pop();
}
getTextBeforePosition(position: Position): string {
var start = new Position(position.line, 0);
var range = new Range(start, position);
return this._document.getText(range);
}
getTagSuggestion() {
let suggestions = [];
let id = 100;
for (let tag in TAGS) {
suggestions.push(this.buildTagSuggestion(tag, TAGS[tag], id));
id++;
}
return suggestions;
}
getAttrValueSuggestion(tag: string, attr: string): CompletionItem[] {
let suggestions = [];
const values = this.getAttrValues(tag, attr);
values.forEach(value => {
suggestions.push({
label: value,
kind: CompletionItemKind.Value
});
});
return suggestions;
}
getAttrSuggestion(tag: string) {
let suggestions = [];
let tagAttrs = this.getTagAttrs(tag);
let preText = this.getTextBeforePosition(this._position);
let prefix = preText.replace(/['"]([^'"]*)['"]$/, '').split(/\s|\(+/).pop();
// method attribute
const method = prefix[0] === '@';
// bind attribute
const bind = prefix[0] === ':';
prefix = prefix.replace(/[:@]/, '');
if(/[^@:a-zA-z\s]/.test(prefix[0])) {
return suggestions;
}
tagAttrs.forEach(attr => {
const attrItem = this.getAttrItem(tag, attr);
if (attrItem && (!prefix.trim() || this.firstCharsEqual(attr, prefix))) {
const sug = this.buildAttrSuggestion({attr, tag, bind, method}, attrItem);
sug && suggestions.push(sug);
}
});
for (let attr in ATTRS) {
const attrItem = this.getAttrItem(tag, attr);
if (attrItem && attrItem.global && (!prefix.trim() || this.firstCharsEqual(attr, prefix))) {
const sug = this.buildAttrSuggestion({attr, tag: null, bind, method}, attrItem);
sug && suggestions.push(sug);
}
}
return suggestions;
}
buildTagSuggestion(tag, tagVal, id) {
const snippets = [];
let index = 0;
let that = this;
function build(tag, {subtags, defaults}, snippets) {
let attrs = '';
defaults && defaults.forEach((item, i) => {
attrs += ` ${item}=${that.quotes}$${index + i + 1}${that.quotes}`;
});
snippets.push(`${index > 0 ? '<':''}${tag}${attrs}>`);
index++;
subtags && subtags.forEach(item => build(item, TAGS[item], snippets));
snippets.push(`</${tag}>`);
};
build(tag, tagVal, snippets);
return {
label: tag,
sortText: `0${id}${tag}`,
insertText: new SnippetString(prettyHTML('<' + snippets.join(''), {indent_size: this.size}).substr(1)),
kind: CompletionItemKind.Snippet,
detail: `element-ui ${tagVal.version ? `(version: ${tagVal.version})` : ''}`,
documentation: tagVal.description
};
}
buildAttrSuggestion({attr, tag, bind, method}, {description, type, version}) {
if ((method && type === "method") || (bind && type !== "method") || (!method && !bind)) {
return {
label: attr,
insertText: (type && (type === 'flag')) ? `${attr} ` : new SnippetString(`${attr}=${this.quotes}$1${this.quotes}$0`),
kind: (type && (type === 'method')) ? CompletionItemKind.Method : CompletionItemKind.Property,
detail: tag ? `<${tag}> ${version ? `(version: ${version})`: ''}` : `element-ui ${version ? `(version: ${version})`: ''}`,
documentation: description
};
} else { return; }
}
getAttrValues(tag, attr) {
let attrItem = this.getAttrItem(tag, attr);
let options = attrItem && attrItem.options;
if (!options && attrItem) {
if (attrItem.type === 'boolean') {
options = ['true', 'false'];
} else if (attrItem.type === 'icon') {
options = ATTRS['icons'];
} else if (attrItem.type === 'shortcut-icon') {
options = [];
ATTRS['icons'].forEach(icon => {
options.push(icon.replace(/^el-icon-/, ''));
});
}
}
return options || [];
}
getTagAttrs(tag: string) {
return (TAGS[tag] && TAGS[tag].attributes) || [];
}
getAttrItem(tag: string | undefined, attr: string | undefined) {
return ATTRS[`${tag}/${attr}`] || ATTRS[attr];
}
isAttrValueStart(tag: Object | string | undefined, attr) {
return tag && attr;
}
isAttrStart(tag: TagObject | undefined) {
return tag;
}
isTagStart() {
let txt = this.getTextBeforePosition(this._position);
return this.isPug() ? this.pugTagStartReg.test(txt) : this.tagStartReg.test(txt);
}
firstCharsEqual(str1: string, str2: string) {
if (str2 && str1) {
return str1[0].toLowerCase() === str2[0].toLowerCase();
}
return false;
}
// tentative plan for vue file
notInTemplate(): boolean {
let line = this._position.line;
while(line) {
if (/^\s*<script.*>\s*$/.test(<string>this._document.lineAt(line).text)) {
return true;
}
line--;
}
return false;
}
provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<CompletionItem[] | CompletionList> {
this._document = document;
this._position = position;
const config = workspace.getConfiguration('element-helper');
this.size = config.get('indent-size');
const normalQuotes = config.get('quotes') === 'double' ? '"': "'";
const pugQuotes = config.get('pug-quotes') === 'double' ? '"': "'";
this.quotes = this.isPug() ? pugQuotes : normalQuotes;
let tag: TagObject | string | undefined = this.isPug() ? this.getPugTag() : this.getPreTag();
let attr = this.getPreAttr();
if (this.isAttrValueStart(tag, attr)) {
return this.getAttrValueSuggestion(tag.text, attr);
} else if(this.isAttrStart(tag)) {
return this.getAttrSuggestion(tag.text);
} else if (this.isTagStart()) {
switch(document.languageId) {
case 'jade':
case 'pug':
return this.getPugTagSuggestion();
case 'vue':
if (this.isPug()) {
return this.getPugTagSuggestion();
}
return this.notInTemplate() ? [] : this.getTagSuggestion();
case 'html':
// todo
return this.getTagSuggestion();
}
} else {return [];}
}
isPug(): boolean {
if (['pug', 'jade'].includes(this._document.languageId)) {
return true;
} else {
var range = new Range(new Position(0, 0), this._position);
let txt = this._document.getText(range);
return /<template[^>]*\s+lang=['"](jade|pug)['"].*/.test(txt);
}
}
getPugTagSuggestion() {
let suggestions = [];
for (let tag in TAGS) {
suggestions.push(this.buildPugTagSuggestion(tag, TAGS[tag]));
}
return suggestions;
}
buildPugTagSuggestion(tag, tagVal) {
const snippets = [];
let index = 0;
let that = this;
function build(tag, {subtags, defaults}, snippets) {
let attrs = [];
defaults && defaults.forEach((item, i) => {
attrs.push(`${item}=${that.quotes}$${index + i + 1}${that.quotes}`);
});
snippets.push(`${' '.repeat(index * that.size)}${tag}(${attrs.join(' ')})`);
index++;
subtags && subtags.forEach(item => build(item, TAGS[item], snippets));
};
build(tag, tagVal, snippets);
return {
label: tag,
insertText: new SnippetString(snippets.join('\n')),
kind: CompletionItemKind.Snippet,
detail: 'element-ui',
documentation: tagVal.description
};
}
getPugTag(): TagObject | undefined {
let line = this._position.line;
let tag: TagObject | string;
let txt = '';
while (this._position.line - line < 10 && line >=0) {
txt = this._document.lineAt(line).text;
let match = /^\s*([\w-]+)[.#-\w]*\(/.exec(txt);
if (match) {
return {
text: match[1],
offset: this._document.offsetAt(new Position(line, match.index))
};
}
line--;
}
return;
}
} | the_stack |
import {H5Config, InstantiateConfig} from '../options/config';
import {RoutesRule, routesMapRule, routesMapKeysRule, Router, totalNextRoute, objectAny, navErrorRule, NAVTYPE, navRoute, uniBackApiRule, uniBackRule} from '../options/base';
import {baseConfig} from '../helpers/config';
import {ERRORHOOK} from '../public/hooks'
import {warnLock} from '../helpers/warn'
import { createRoute, navjump } from '../public/methods';
const Regexp = require('path-to-regexp');
export function voidFun(...args:any):void{}
export function def(
defObject:objectAny,
key:string,
getValue:Function
) {
Object.defineProperty(defObject, key, {
get() {
return getValue();
}
})
}
export function timeOut(time:number):Promise<void> {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, time)
})
}
export function mergeConfig<T extends InstantiateConfig>(baseConfig: T, userConfig: T): T {
const config: {[key: string]: any} = Object.create(null);
const baseConfigKeys: Array<string> = Object.keys(baseConfig).concat(['resolveQuery', 'parseQuery']);
for (let i = 0; i < baseConfigKeys.length; i += 1) {
const key = baseConfigKeys[i];
if (userConfig[key] != null) {
if (userConfig[key].constructor === Object) {
config[key] = {
...baseConfig[key],
...userConfig[key]
};
} else if (key === 'routes') {
config[key] = [
...baseConfig[key],
...userConfig[key]
];
} else {
config[key] = userConfig[key];
}
} else {
config[key] = baseConfig[key];
}
}
return config as T;
}
export function notDeepClearNull<T>(object:T):T {
for (const key in object) {
if (object[key] == null) {
delete object[key];
}
}
return object;
}
export function getRoutePath(route: RoutesRule, router:Router): {
finallyPath: string | string[];
aliasPath: string;
path: string;
alias: string | string[] | undefined;
} {
let finallyPath = route.aliasPath || route.alias || route.path;
if (router.options.platform !== 'h5') {
finallyPath = route.path
}
return {
finallyPath,
aliasPath: route.aliasPath || route.path,
path: route.path,
alias: route.alias
}
}
export function assertNewOptions<T extends InstantiateConfig>(
options: T
): T | never {
const {platform, routes} = options;
if (platform == null) {
throw new Error(`你在实例化路由时必须传递 'platform'`);
}
if (routes == null || routes.length === 0) {
throw new Error(`你在实例化路由时必须传递 routes 为空,这是无意义的。`);
}
if (options.platform === 'h5') {
if (options.h5?.vueRouterDev) {
baseConfig.routes = [];
}
}
const mergeOptions = mergeConfig<T>(baseConfig as T, options);
return mergeOptions;
}
export function getWildcardRule(
router:Router,
msg?:navErrorRule
):RoutesRule|never {
const routesMap = (router.routesMap as routesMapRule);
const route = routesMap.finallyPathMap['*'];
if (route) { // 有写通配符
return route
}
if (msg) {
ERRORHOOK[0](msg, router);
}
throw new Error(`当前路由表匹配规则已全部匹配完成,未找到满足的匹配规则。你可以使用 '*' 通配符捕捉最后的异常`);
}
export function notRouteTo404(
router:Router,
toRoute:RoutesRule|{
redirect:any;
path:string
},
parseToRule:totalNextRoute,
navType:NAVTYPE
):RoutesRule|totalNextRoute|never {
if (toRoute.path !== '*') { // 不是通配符 正常匹配成功
return (toRoute as RoutesRule);
}
const redirect = toRoute.redirect;
if (typeof redirect === 'undefined') {
throw new Error(` * 通配符必须配合 redirect 使用。redirect: string | Location | Function`);
}
let newRoute = redirect;
if (typeof newRoute === 'function') {
newRoute = newRoute(parseToRule) as totalNextRoute;
}
const redirectRule = navjump(newRoute as totalNextRoute, router, navType, undefined, undefined, undefined, false);
return (redirectRule as totalNextRoute);
}
export function routesForMapRoute(
router: Router,
path: string,
mapArrayKey:Array<routesMapKeysRule>,
deepFind:boolean|undefined = false
):RoutesRule|never {
if (router.options.h5?.vueRouterDev) {
return {path}
}
// 【Fixe】 https://github.com/SilurianYang/uni-simple-router/issues/252
const startPath = path.split('?')[0];
let wildcard = '';
const routesMap = (router.routesMap as routesMapRule);
for (let i = 0; i < mapArrayKey.length; i++) {
const mapKey = mapArrayKey[i];
const mapList = routesMap[mapKey];
for (const [key, value] of Object.entries(mapList)) {
if (key === '*') {
if (wildcard === '') {
wildcard = '*'
}
continue;
}
const route:string|RoutesRule = value;
let rule:string = key;
if (getDataType<Array<string>|objectAny>(mapList) === '[object Array]') {
rule = (route as string);
}
const pathRule:RegExp = Regexp(rule);
const result = pathRule.exec(startPath);
if (result != null) {
if (getDataType<string|RoutesRule>(route) === '[object String]') {
return routesMap.finallyPathMap[(route as string)];
}
return (route as RoutesRule);
}
}
}
// 【Fixe】 https://github.com/SilurianYang/uni-simple-router/issues/302 2021-8-4 16:38:44
if (deepFind) {
return ({} as RoutesRule);
}
if (routesMap['aliasPathMap']) {
const results = routesForMapRoute(router, path, ['aliasPathMap'], true);
if (Object.keys(results).length > 0) {
return results;
}
}
if (wildcard !== '') {
return getWildcardRule(router);
}
throw new Error(`${path} 路径无法在路由表中找到!检查跳转路径及路由表`);
}
export function getDataType<T>(data:T):string {
return Object.prototype.toString.call(data)
}
export function copyData<T>(object:T): T {
return JSON.parse(JSON.stringify(object))
}
export function getUniCachePage<T extends objectAny>(pageIndex?:number):T|[] {
const pages:T = getCurrentPages();
if (pageIndex == null) {
return pages
}
if (pages.length === 0) {
return pages;
}
const page = pages.reverse()[pageIndex];
if (page == null) {
return []
}
return page;
}
export function urlToJson(url :string):{
path:string;
query:objectAny
} {
const query:objectAny = {};
const [path, params] = url.split('?');
if (params != null) {
const parr = params.split('&');
for (const i of parr) {
const arr = i.split('=');
query[arr[0]] = arr[1];
}
}
return {
path,
query
}
}
export function forMatNextToFrom<T extends totalNextRoute>(
router:Router,
to:T,
from:T
):{
matTo:T;
matFrom: T;
} {
let [matTo, matFrom] = [to, from];
if (router.options.platform === 'h5') {
const {vueNext, vueRouterDev} = (router.options.h5 as H5Config);
if (!vueNext && !vueRouterDev) {
matTo = createRoute(router, undefined, matTo) as T;
matFrom = createRoute(router, undefined, matFrom) as T;
}
} else {
matTo = createRoute(router, undefined, deepClone<T>(matTo)) as T;
matFrom = createRoute(router, undefined, deepClone<T>(matFrom)) as T;
}
return {
matTo: matTo,
matFrom: matFrom
}
}
export function paramsToQuery(
router:Router,
toRule:totalNextRoute|string
):totalNextRoute|string {
if (router.options.platform === 'h5' && !router.options.h5?.paramsToQuery) {
return toRule;
}
if (getDataType<totalNextRoute|string>(toRule) === '[object Object]') {
const {name, params, ...moreToRule} = (toRule as totalNextRoute);
let paramsQuery = params;
if (router.options.platform !== 'h5' && paramsQuery == null) {
paramsQuery = {};
}
if (name != null && paramsQuery != null) {
let route = (router.routesMap as routesMapRule).nameMap[name];
if (route == null) {
route = getWildcardRule(router, { type: 2, msg: `命名路由为:${name} 的路由,无法在路由表中找到!`, toRule});
}
const {finallyPath} = getRoutePath(route, router);
if (finallyPath.includes(':')) { // 动态路由无法使用 paramsToQuery
ERRORHOOK[0]({ type: 2, msg: `动态路由:${finallyPath} 无法使用 paramsToQuery!`, toRule}, router);
} else {
return {
...moreToRule,
path: finallyPath as string,
query: paramsQuery
}
}
}
}
return toRule
}
export function assertDeepObject(object:objectAny):boolean {
let arrMark = null;
try {
arrMark = JSON.stringify(object).match(/\{|\[|\}|\]/g);
} catch (error) {
warnLock(`传递的参数解析对象失败。` + error)
}
if (arrMark == null) {
return false
}
if (arrMark.length > 3) {
return true;
}
return false
}
export function baseClone<
T extends {
[key:string]:any
}, K extends keyof T
>(
source:T,
target:Array<any>|objectAny
):Array<any>|objectAny|null {
// 【Fixe】 https://github.com/SilurianYang/uni-simple-router/issues/292
// 小程序会将null解析为字符串 undefined 建议不要在参数中传递 null
if (source == null) {
target = source;
} else {
for (const key of Object.keys(source)) {
const dyKey = key as T[K];
if (source[key] === source) continue
if (typeof source[key] === 'object') {
target[dyKey] = getDataType<T>(source[key]) === '[object Array]' ? ([] as Array<any>) : ({} as objectAny)
target[dyKey] = baseClone(source[key], target[dyKey])
} else {
target[dyKey] = source[key]
}
}
}
return target;
}
export function deepClone<T>(source:T):T {
const __ob__ = getDataType<T>(source) === '[object Array]' ? ([] as Array<any>) : ({} as objectAny);
baseClone(source, __ob__)
return __ob__ as T
}
export function lockDetectWarn(
router:Router,
to:string|number|totalNextRoute|navRoute,
navType:NAVTYPE,
next:Function,
uniActualData:uniBackApiRule|uniBackRule|undefined = {},
passiveType?:'beforeHooks'| 'afterHooks'
):void{
if (passiveType === 'afterHooks') {
next();
} else {
const {detectBeforeLock} = router.options;
detectBeforeLock && detectBeforeLock(router, to, navType);
if (router.$lockStatus) {
(router.options.routerErrorEach as (error: navErrorRule, router:Router) => void)({
type: 2,
msg: '当前页面正在处于跳转状态,请稍后再进行跳转....',
NAVTYPE: navType,
uniActualData
}, router);
} else {
next();
}
}
}
export function assertParentChild(
parentPath:string,
vueVim:any,
):boolean {
while (vueVim.$parent != null) {
const mpPage = vueVim.$parent.$mp;
if (mpPage.page && mpPage.page.is === parentPath) {
return true;
}
vueVim = vueVim.$parent;
}
try {
if (vueVim.$mp.page.is === parentPath || vueVim.$mp.page.route === parentPath) {
return true
}
} catch (error) {
return false
}
return false
}
export function resolveAbsolutePath(
path:string,
router:Router
):string|never {
const reg = /^\/?([^\?\s]+)(\?.+)?$/;
const trimPath = path.trim();
if (!reg.test(trimPath)) {
throw new Error(`【${path}】 路径错误,请提供完整的路径(10001)。`);
}
const paramsArray = trimPath.match(reg);
if (paramsArray == null) {
throw new Error(`【${path}】 路径错误,请提供完整的路径(10002)。`);
}
const query:string = paramsArray[2] || '';
if (/^\.\/[^\.]+/.test(trimPath)) { // 当前路径下
const navPath:string = router.currentRoute.path + path;
return navPath.replace(/[^\/]+\.\//, '');
}
const relative = paramsArray[1].replace(/\//g, `\\/`).replace(/\.\./g, `[^\\/]+`).replace(/\./g, '\\.');
const relativeReg = new RegExp(`^\\/${relative}$`);
const route = router.options.routes.filter(it => relativeReg.test(it.path));
if (route.length !== 1) {
throw new Error(`【${path}】 路径错误,尝试转成绝对路径失败,请手动转成绝对路径(10003)。`);
}
return route[0].path + query;
}
export function deepDecodeQuery(
query:objectAny
):objectAny {
const formatQuery:objectAny = getDataType<objectAny>(query) === '[object Array]' ? [] : {};
const keys = Object.keys(query);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const it = query[key];
if (typeof it === 'string') {
try {
let json = JSON.parse(decodeURIComponent(it));
if (typeof json !== 'object') {
json = it;
}
formatQuery[key] = json;
} catch (error) {
try {
formatQuery[key] = decodeURIComponent(it)
} catch (error) {
formatQuery[key] = it
}
}
} else if (typeof it === 'object') {
const childQuery = deepDecodeQuery(it);
formatQuery[key] = childQuery
} else {
formatQuery[key] = it
}
}
return formatQuery
} | the_stack |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="pt_BR">
<context>
<name>MainUI</name>
<message>
<location filename="../mainUI.ui" line="14"/>
<location filename="../mainUI.cpp" line="286"/>
<source>Media Player</source>
<translation>Media Player</translation>
</message>
<message>
<location filename="../mainUI.ui" line="50"/>
<location filename="../mainUI.ui" line="261"/>
<location filename="../mainUI.cpp" line="632"/>
<source>Now Playing</source>
<translation>Tocando agora</translation>
</message>
<message>
<location filename="../mainUI.ui" line="74"/>
<source>(No Running Video)</source>
<translation>(Nenhum vídeo em execução)</translation>
</message>
<message>
<location filename="../mainUI.ui" line="105"/>
<source>Playlist</source>
<translation>Lista de reprodução</translation>
</message>
<message>
<location filename="../mainUI.ui" line="167"/>
<source>up</source>
<translation>Cima</translation>
</message>
<message>
<location filename="../mainUI.ui" line="183"/>
<source>down</source>
<translation>Baixo</translation>
</message>
<message>
<location filename="../mainUI.ui" line="267"/>
<source>Current Song</source>
<translation>Música atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="303"/>
<source>TITLE</source>
<translation>TÍTULO</translation>
</message>
<message>
<location filename="../mainUI.ui" line="327"/>
<source>ARTIST</source>
<translation>ARTISTA</translation>
</message>
<message>
<location filename="../mainUI.ui" line="337"/>
<source>ALBUM</source>
<translation>ÁLBUM</translation>
</message>
<message>
<location filename="../mainUI.ui" line="368"/>
<source>Love this song</source>
<translation>Marcar música como favorita</translation>
</message>
<message>
<location filename="../mainUI.ui" line="384"/>
<source>Tired of this song (will not play for a month)</source>
<translation>Enjoado dessa música (não vai tocar por um mês)</translation>
</message>
<message>
<location filename="../mainUI.ui" line="397"/>
<source>Ban this song (will never play again)</source>
<translation>Banir esta música (não será mais tocada)</translation>
</message>
<message>
<location filename="../mainUI.ui" line="417"/>
<source>View details about song (launches web browser)</source>
<translation>Ver detalhes da música (abre o navegador web)</translation>
</message>
<message>
<location filename="../mainUI.ui" line="448"/>
<source>Current Station</source>
<translation>Estação atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="479"/>
<source>Delete current station</source>
<translation>Remover estação atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="482"/>
<source>rm</source>
<translation>rm</translation>
</message>
<message>
<location filename="../mainUI.ui" line="492"/>
<source>Create new station</source>
<translation>Criar nova estação</translation>
</message>
<message>
<location filename="../mainUI.ui" line="495"/>
<source>add</source>
<translation>Add</translation>
</message>
<message>
<location filename="../mainUI.ui" line="512"/>
<source>Settings</source>
<translation>Configurações</translation>
</message>
<message>
<location filename="../mainUI.ui" line="521"/>
<source>Pandora Account Login</source>
<translation>Login na conta Pandora</translation>
</message>
<message>
<location filename="../mainUI.ui" line="527"/>
<source>Email</source>
<translation>E-mail</translation>
</message>
<message>
<location filename="../mainUI.ui" line="537"/>
<source>Password</source>
<translation>Senha</translation>
</message>
<message>
<location filename="../mainUI.ui" line="557"/>
<source><a href=https://www.pandora.com/account/register>Need an account?</a></source>
<translation><a href=https://www.pandora.com/account/register>Precisa de uma conta?</a></translation>
</message>
<message>
<location filename="../mainUI.ui" line="573"/>
<source>Audio Quality</source>
<translation>Qualidade do áudio</translation>
</message>
<message>
<location filename="../mainUI.ui" line="583"/>
<source>Proxy URL</source>
<translation>URL do proxy</translation>
</message>
<message>
<location filename="../mainUI.ui" line="593"/>
<source>Control Proxy URL</source>
<translation>URL do Proxy de Controle</translation>
</message>
<message>
<location filename="../mainUI.ui" line="618"/>
<source>Apply Settings</source>
<translation>Aplicar configurações</translation>
</message>
<message>
<location filename="../mainUI.ui" line="656"/>
<source>Audio Driver</source>
<translation>Driver de áudio</translation>
</message>
<message>
<location filename="../mainUI.ui" line="681"/>
<source>&File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.ui" line="688"/>
<source>&View</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.ui" line="723"/>
<source>Play</source>
<translation>Tocar</translation>
</message>
<message>
<location filename="../mainUI.ui" line="728"/>
<source>Pause</source>
<translation>Pausar</translation>
</message>
<message>
<location filename="../mainUI.ui" line="733"/>
<source>Stop</source>
<translation>Parar</translation>
</message>
<message>
<location filename="../mainUI.ui" line="738"/>
<source>Next</source>
<translation>Avançar</translation>
</message>
<message>
<location filename="../mainUI.ui" line="743"/>
<source>Back</source>
<translation>Voltar</translation>
</message>
<message>
<location filename="../mainUI.ui" line="748"/>
<source>VolUp</source>
<translation>VolUp</translation>
</message>
<message>
<location filename="../mainUI.ui" line="751"/>
<source>Raise audio volume</source>
<translation>Aumentar o volume do áudio</translation>
</message>
<message>
<location filename="../mainUI.ui" line="756"/>
<source>VolDown</source>
<translation>VolDown</translation>
</message>
<message>
<location filename="../mainUI.ui" line="759"/>
<source>Lower audio volume</source>
<translation>Diminuir o volume do áudio</translation>
</message>
<message>
<location filename="../mainUI.ui" line="764"/>
<source>Close Application</source>
<translation>Fechar aplicação</translation>
</message>
<message>
<location filename="../mainUI.ui" line="767"/>
<source>Ctrl+Q</source>
<translation>Ctrl+Q</translation>
</message>
<message>
<location filename="../mainUI.ui" line="781"/>
<source>Close to tray when active</source>
<translation>Fechar para a bandeja quando ativo</translation>
</message>
<message>
<location filename="../mainUI.ui" line="786"/>
<source>From current artist</source>
<translation>Do artista atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="789"/>
<source>Create station from current artist</source>
<translation>Criar estação do artista atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="794"/>
<source>From current song</source>
<translation>Da música atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="797"/>
<source>Create station from current song</source>
<translation>Criar uma estação da música atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="808"/>
<source>Show song notifications</source>
<translation>Mostrar notificações de músicas</translation>
</message>
<message>
<location filename="../mainUI.ui" line="813"/>
<source>Search...</source>
<translation>Procurar...</translation>
</message>
<message>
<location filename="../mainUI.ui" line="816"/>
<source>Search for a new station</source>
<translation>Procurar uma nova estação</translation>
</message>
<message>
<location filename="../mainUI.ui" line="828"/>
<location filename="../mainUI.cpp" line="277"/>
<source>Pandora Radio</source>
<translation>Pandora Radio</translation>
</message>
<message>
<location filename="../mainUI.ui" line="831"/>
<source>Stream from Pandora Radio</source>
<translation>Transmissão da Pandora Radio</translation>
</message>
<message>
<location filename="../mainUI.ui" line="839"/>
<source>Local Files</source>
<translation>Arquivos locais</translation>
</message>
<message>
<location filename="../mainUI.ui" line="842"/>
<source>Play Local Files</source>
<translation>Tocar arquivos locais</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="105"/>
<source>Please install the `pianobar` utility to enable this functionality</source>
<translation>Instale o utilitário `pianobar` para habilitar esta funcionalidade</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="109"/>
<source>Stream music from the Pandora online radio service</source>
<translation>Transmitir música do serviço de rádio on-line Pandora</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="122"/>
<source>Low</source>
<translation>Baixo</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="123"/>
<source>Medium</source>
<translation>Médio</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="124"/>
<source>High</source>
<translation>Alto</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="359"/>
<source>Open Multimedia Files</source>
<translation>Abrir arquivos multimídia</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="407"/>
<source>Now Playing:</source>
<translation>Tocando agora:</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="472"/>
<source>[PLAYBACK ERROR]
%1</source>
<translation>[PLAYBACK ERROR]
%1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="489"/>
<source>Media Loading...</source>
<translation>Carregando mídia...</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="491"/>
<source>Media Stalled...</source>
<translation>Mídia parada...</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="493"/>
<source>Media Buffering...</source>
<translation>Carregando mídia...</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="577"/>
<source>Pandora: Create Station</source>
<translation>Pandora: Criar estação</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="577"/>
<source>Search Term</source>
<translation>Procurar termo</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="655"/>
<source>Pandora Question</source>
<translation>Pergunta Pandora</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="660"/>
<source>Pandora Error</source>
<translation>Erro Pandora</translation>
</message>
</context>
<context>
<name>PianoBarProcess</name>
<message>
<location filename="../PianoBarProcess.cpp" line="360"/>
<source>Could not find any matches. Please try a different search term</source>
<translation>Não foi possível encontrar nenhum resultado. Experimente um termo de pesquisa diferente</translation>
</message>
</context>
<context>
<name>XDGDesktopList</name>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="618"/>
<source>Multimedia</source>
<translation>Multimídia</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="619"/>
<source>Development</source>
<translation>Desenvolvimento</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="620"/>
<source>Education</source>
<translation>Educação</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="621"/>
<source>Games</source>
<translation>Jogos</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="622"/>
<source>Graphics</source>
<translation>Gráficos</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="623"/>
<source>Network</source>
<translation>Rede</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="624"/>
<source>Office</source>
<translation>Escritório</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="625"/>
<source>Science</source>
<translation>Ciência</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="626"/>
<source>Settings</source>
<translation>Configurações</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="627"/>
<source>System</source>
<translation>Sistema</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="628"/>
<source>Utility</source>
<translation>Utilitários</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="629"/>
<source>Wine</source>
<translation>Wine</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="630"/>
<source>Unsorted</source>
<translation>Não classificado</translation>
</message>
</context>
</TS> | the_stack |
declare namespace GoogleAppsScript {
namespace Dfareporting {
namespace Collection {
namespace Reports {
interface CompatibleFieldsCollection {
// Returns the fields that are compatible to be selected in the respective sections of a report criteria, given the fields already selected in the input report and user permissions.
query(resource: Schema.Report, profileId: string): Dfareporting.Schema.CompatibleFields;
}
interface FilesCollection {
// Retrieves a report file. This method supports media download.
get(profileId: string, reportId: string, fileId: string): Dfareporting.Schema.File;
// Lists files for a report.
list(profileId: string, reportId: string): Dfareporting.Schema.FileList;
// Lists files for a report.
list(profileId: string, reportId: string, optionalArgs: object): Dfareporting.Schema.FileList;
}
}
interface AccountActiveAdSummariesCollection {
// Gets the account's active ad summary by account ID.
get(profileId: string, summaryAccountId: string): Dfareporting.Schema.AccountActiveAdSummary;
}
interface AccountPermissionGroupsCollection {
// Gets one account permission group by ID.
get(profileId: string, id: string): Dfareporting.Schema.AccountPermissionGroup;
// Retrieves the list of account permission groups.
list(profileId: string): Dfareporting.Schema.AccountPermissionGroupsListResponse;
}
interface AccountPermissionsCollection {
// Gets one account permission by ID.
get(profileId: string, id: string): Dfareporting.Schema.AccountPermission;
// Retrieves the list of account permissions.
list(profileId: string): Dfareporting.Schema.AccountPermissionsListResponse;
}
interface AccountUserProfilesCollection {
// Gets one account user profile by ID.
get(profileId: string, id: string): Dfareporting.Schema.AccountUserProfile;
// Inserts a new account user profile.
insert(resource: Schema.AccountUserProfile, profileId: string): Dfareporting.Schema.AccountUserProfile;
// Retrieves a list of account user profiles, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.AccountUserProfilesListResponse;
// Retrieves a list of account user profiles, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.AccountUserProfilesListResponse;
// Updates an existing account user profile. This method supports patch semantics.
patch(resource: Schema.AccountUserProfile, profileId: string, id: string): Dfareporting.Schema.AccountUserProfile;
// Updates an existing account user profile.
update(resource: Schema.AccountUserProfile, profileId: string): Dfareporting.Schema.AccountUserProfile;
}
interface AccountsCollection {
// Gets one account by ID.
get(profileId: string, id: string): Dfareporting.Schema.Account;
// Retrieves the list of accounts, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.AccountsListResponse;
// Retrieves the list of accounts, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.AccountsListResponse;
// Updates an existing account. This method supports patch semantics.
patch(resource: Schema.Account, profileId: string, id: string): Dfareporting.Schema.Account;
// Updates an existing account.
update(resource: Schema.Account, profileId: string): Dfareporting.Schema.Account;
}
interface AdsCollection {
// Gets one ad by ID.
get(profileId: string, id: string): Dfareporting.Schema.Ad;
// Inserts a new ad.
insert(resource: Schema.Ad, profileId: string): Dfareporting.Schema.Ad;
// Retrieves a list of ads, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.AdsListResponse;
// Retrieves a list of ads, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.AdsListResponse;
// Updates an existing ad. This method supports patch semantics.
patch(resource: Schema.Ad, profileId: string, id: string): Dfareporting.Schema.Ad;
// Updates an existing ad.
update(resource: Schema.Ad, profileId: string): Dfareporting.Schema.Ad;
}
interface AdvertiserGroupsCollection {
// Gets one advertiser group by ID.
get(profileId: string, id: string): Dfareporting.Schema.AdvertiserGroup;
// Inserts a new advertiser group.
insert(resource: Schema.AdvertiserGroup, profileId: string): Dfareporting.Schema.AdvertiserGroup;
// Retrieves a list of advertiser groups, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.AdvertiserGroupsListResponse;
// Retrieves a list of advertiser groups, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.AdvertiserGroupsListResponse;
// Updates an existing advertiser group. This method supports patch semantics.
patch(resource: Schema.AdvertiserGroup, profileId: string, id: string): Dfareporting.Schema.AdvertiserGroup;
// Deletes an existing advertiser group.
remove(profileId: string, id: string): void;
// Updates an existing advertiser group.
update(resource: Schema.AdvertiserGroup, profileId: string): Dfareporting.Schema.AdvertiserGroup;
}
interface AdvertiserLandingPagesCollection {
// Gets one landing page by ID.
get(profileId: string, id: string): Dfareporting.Schema.LandingPage;
// Inserts a new landing page.
insert(resource: Schema.LandingPage, profileId: string): Dfareporting.Schema.LandingPage;
// Retrieves a list of landing pages.
list(profileId: string): Dfareporting.Schema.AdvertiserLandingPagesListResponse;
// Retrieves a list of landing pages.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.AdvertiserLandingPagesListResponse;
// Updates an existing landing page. This method supports patch semantics.
patch(resource: Schema.LandingPage, profileId: string, id: string): Dfareporting.Schema.LandingPage;
// Updates an existing landing page.
update(resource: Schema.LandingPage, profileId: string): Dfareporting.Schema.LandingPage;
}
interface AdvertisersCollection {
// Gets one advertiser by ID.
get(profileId: string, id: string): Dfareporting.Schema.Advertiser;
// Inserts a new advertiser.
insert(resource: Schema.Advertiser, profileId: string): Dfareporting.Schema.Advertiser;
// Retrieves a list of advertisers, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.AdvertisersListResponse;
// Retrieves a list of advertisers, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.AdvertisersListResponse;
// Updates an existing advertiser. This method supports patch semantics.
patch(resource: Schema.Advertiser, profileId: string, id: string): Dfareporting.Schema.Advertiser;
// Updates an existing advertiser.
update(resource: Schema.Advertiser, profileId: string): Dfareporting.Schema.Advertiser;
}
interface BrowsersCollection {
// Retrieves a list of browsers.
list(profileId: string): Dfareporting.Schema.BrowsersListResponse;
}
interface CampaignCreativeAssociationsCollection {
// Associates a creative with the specified campaign. This method creates a default ad with dimensions matching the creative in the campaign if such a default ad does not exist already.
insert(resource: Schema.CampaignCreativeAssociation, profileId: string, campaignId: string): Dfareporting.Schema.CampaignCreativeAssociation;
// Retrieves the list of creative IDs associated with the specified campaign. This method supports paging.
list(profileId: string, campaignId: string): Dfareporting.Schema.CampaignCreativeAssociationsListResponse;
// Retrieves the list of creative IDs associated with the specified campaign. This method supports paging.
list(profileId: string, campaignId: string, optionalArgs: object): Dfareporting.Schema.CampaignCreativeAssociationsListResponse;
}
interface CampaignsCollection {
// Gets one campaign by ID.
get(profileId: string, id: string): Dfareporting.Schema.Campaign;
// Inserts a new campaign.
insert(resource: Schema.Campaign, profileId: string): Dfareporting.Schema.Campaign;
// Retrieves a list of campaigns, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.CampaignsListResponse;
// Retrieves a list of campaigns, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.CampaignsListResponse;
// Updates an existing campaign. This method supports patch semantics.
patch(resource: Schema.Campaign, profileId: string, id: string): Dfareporting.Schema.Campaign;
// Updates an existing campaign.
update(resource: Schema.Campaign, profileId: string): Dfareporting.Schema.Campaign;
}
interface ChangeLogsCollection {
// Gets one change log by ID.
get(profileId: string, id: string): Dfareporting.Schema.ChangeLog;
// Retrieves a list of change logs. This method supports paging.
list(profileId: string): Dfareporting.Schema.ChangeLogsListResponse;
// Retrieves a list of change logs. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.ChangeLogsListResponse;
}
interface CitiesCollection {
// Retrieves a list of cities, possibly filtered.
list(profileId: string): Dfareporting.Schema.CitiesListResponse;
// Retrieves a list of cities, possibly filtered.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.CitiesListResponse;
}
interface ConnectionTypesCollection {
// Gets one connection type by ID.
get(profileId: string, id: string): Dfareporting.Schema.ConnectionType;
// Retrieves a list of connection types.
list(profileId: string): Dfareporting.Schema.ConnectionTypesListResponse;
}
interface ContentCategoriesCollection {
// Gets one content category by ID.
get(profileId: string, id: string): Dfareporting.Schema.ContentCategory;
// Inserts a new content category.
insert(resource: Schema.ContentCategory, profileId: string): Dfareporting.Schema.ContentCategory;
// Retrieves a list of content categories, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.ContentCategoriesListResponse;
// Retrieves a list of content categories, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.ContentCategoriesListResponse;
// Updates an existing content category. This method supports patch semantics.
patch(resource: Schema.ContentCategory, profileId: string, id: string): Dfareporting.Schema.ContentCategory;
// Deletes an existing content category.
remove(profileId: string, id: string): void;
// Updates an existing content category.
update(resource: Schema.ContentCategory, profileId: string): Dfareporting.Schema.ContentCategory;
}
interface ConversionsCollection {
// Inserts conversions.
batchinsert(resource: Schema.ConversionsBatchInsertRequest, profileId: string): Dfareporting.Schema.ConversionsBatchInsertResponse;
// Updates existing conversions.
batchupdate(resource: Schema.ConversionsBatchUpdateRequest, profileId: string): Dfareporting.Schema.ConversionsBatchUpdateResponse;
}
interface CountriesCollection {
// Gets one country by ID.
get(profileId: string, dartId: string): Dfareporting.Schema.Country;
// Retrieves a list of countries.
list(profileId: string): Dfareporting.Schema.CountriesListResponse;
}
interface CreativeAssetsCollection {
// Inserts a new creative asset.
insert(resource: Schema.CreativeAssetMetadata, profileId: string, advertiserId: string): Dfareporting.Schema.CreativeAssetMetadata;
// Inserts a new creative asset.
insert(resource: Schema.CreativeAssetMetadata, profileId: string, advertiserId: string, mediaData: any): Dfareporting.Schema.CreativeAssetMetadata;
}
interface CreativeFieldValuesCollection {
// Gets one creative field value by ID.
get(profileId: string, creativeFieldId: string, id: string): Dfareporting.Schema.CreativeFieldValue;
// Inserts a new creative field value.
insert(resource: Schema.CreativeFieldValue, profileId: string, creativeFieldId: string): Dfareporting.Schema.CreativeFieldValue;
// Retrieves a list of creative field values, possibly filtered. This method supports paging.
list(profileId: string, creativeFieldId: string): Dfareporting.Schema.CreativeFieldValuesListResponse;
// Retrieves a list of creative field values, possibly filtered. This method supports paging.
list(profileId: string, creativeFieldId: string, optionalArgs: object): Dfareporting.Schema.CreativeFieldValuesListResponse;
// Updates an existing creative field value. This method supports patch semantics.
patch(resource: Schema.CreativeFieldValue, profileId: string, creativeFieldId: string, id: string): Dfareporting.Schema.CreativeFieldValue;
// Deletes an existing creative field value.
remove(profileId: string, creativeFieldId: string, id: string): void;
// Updates an existing creative field value.
update(resource: Schema.CreativeFieldValue, profileId: string, creativeFieldId: string): Dfareporting.Schema.CreativeFieldValue;
}
interface CreativeFieldsCollection {
// Gets one creative field by ID.
get(profileId: string, id: string): Dfareporting.Schema.CreativeField;
// Inserts a new creative field.
insert(resource: Schema.CreativeField, profileId: string): Dfareporting.Schema.CreativeField;
// Retrieves a list of creative fields, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.CreativeFieldsListResponse;
// Retrieves a list of creative fields, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.CreativeFieldsListResponse;
// Updates an existing creative field. This method supports patch semantics.
patch(resource: Schema.CreativeField, profileId: string, id: string): Dfareporting.Schema.CreativeField;
// Deletes an existing creative field.
remove(profileId: string, id: string): void;
// Updates an existing creative field.
update(resource: Schema.CreativeField, profileId: string): Dfareporting.Schema.CreativeField;
}
interface CreativeGroupsCollection {
// Gets one creative group by ID.
get(profileId: string, id: string): Dfareporting.Schema.CreativeGroup;
// Inserts a new creative group.
insert(resource: Schema.CreativeGroup, profileId: string): Dfareporting.Schema.CreativeGroup;
// Retrieves a list of creative groups, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.CreativeGroupsListResponse;
// Retrieves a list of creative groups, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.CreativeGroupsListResponse;
// Updates an existing creative group. This method supports patch semantics.
patch(resource: Schema.CreativeGroup, profileId: string, id: string): Dfareporting.Schema.CreativeGroup;
// Updates an existing creative group.
update(resource: Schema.CreativeGroup, profileId: string): Dfareporting.Schema.CreativeGroup;
}
interface CreativesCollection {
// Gets one creative by ID.
get(profileId: string, id: string): Dfareporting.Schema.Creative;
// Inserts a new creative.
insert(resource: Schema.Creative, profileId: string): Dfareporting.Schema.Creative;
// Retrieves a list of creatives, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.CreativesListResponse;
// Retrieves a list of creatives, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.CreativesListResponse;
// Updates an existing creative. This method supports patch semantics.
patch(resource: Schema.Creative, profileId: string, id: string): Dfareporting.Schema.Creative;
// Updates an existing creative.
update(resource: Schema.Creative, profileId: string): Dfareporting.Schema.Creative;
}
interface DimensionValuesCollection {
// Retrieves list of report dimension values for a list of filters.
query(resource: Schema.DimensionValueRequest, profileId: string): Dfareporting.Schema.DimensionValueList;
// Retrieves list of report dimension values for a list of filters.
query(resource: Schema.DimensionValueRequest, profileId: string, optionalArgs: object): Dfareporting.Schema.DimensionValueList;
}
interface DirectorySitesCollection {
// Gets one directory site by ID.
get(profileId: string, id: string): Dfareporting.Schema.DirectorySite;
// Inserts a new directory site.
insert(resource: Schema.DirectorySite, profileId: string): Dfareporting.Schema.DirectorySite;
// Retrieves a list of directory sites, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.DirectorySitesListResponse;
// Retrieves a list of directory sites, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.DirectorySitesListResponse;
}
interface DynamicTargetingKeysCollection {
// Inserts a new dynamic targeting key. Keys must be created at the advertiser level before being assigned to the advertiser's ads, creatives, or placements. There is a maximum of 1000 keys per advertiser, out of which a maximum of 20 keys can be assigned per ad, creative, or placement.
insert(resource: Schema.DynamicTargetingKey, profileId: string): Dfareporting.Schema.DynamicTargetingKey;
// Retrieves a list of dynamic targeting keys.
list(profileId: string): Dfareporting.Schema.DynamicTargetingKeysListResponse;
// Retrieves a list of dynamic targeting keys.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.DynamicTargetingKeysListResponse;
// Deletes an existing dynamic targeting key.
remove(profileId: string, objectId: string, name: string, objectType: string): void;
}
interface EventTagsCollection {
// Gets one event tag by ID.
get(profileId: string, id: string): Dfareporting.Schema.EventTag;
// Inserts a new event tag.
insert(resource: Schema.EventTag, profileId: string): Dfareporting.Schema.EventTag;
// Retrieves a list of event tags, possibly filtered.
list(profileId: string): Dfareporting.Schema.EventTagsListResponse;
// Retrieves a list of event tags, possibly filtered.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.EventTagsListResponse;
// Updates an existing event tag. This method supports patch semantics.
patch(resource: Schema.EventTag, profileId: string, id: string): Dfareporting.Schema.EventTag;
// Deletes an existing event tag.
remove(profileId: string, id: string): void;
// Updates an existing event tag.
update(resource: Schema.EventTag, profileId: string): Dfareporting.Schema.EventTag;
}
interface FilesCollection {
// Retrieves a report file by its report ID and file ID. This method supports media download.
get(reportId: string, fileId: string): Dfareporting.Schema.File;
// Lists files for a user profile.
list(profileId: string): Dfareporting.Schema.FileList;
// Lists files for a user profile.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.FileList;
}
interface FloodlightActivitiesCollection {
// Generates a tag for a floodlight activity.
generatetag(profileId: string): Dfareporting.Schema.FloodlightActivitiesGenerateTagResponse;
// Generates a tag for a floodlight activity.
generatetag(profileId: string, optionalArgs: object): Dfareporting.Schema.FloodlightActivitiesGenerateTagResponse;
// Gets one floodlight activity by ID.
get(profileId: string, id: string): Dfareporting.Schema.FloodlightActivity;
// Inserts a new floodlight activity.
insert(resource: Schema.FloodlightActivity, profileId: string): Dfareporting.Schema.FloodlightActivity;
// Retrieves a list of floodlight activities, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.FloodlightActivitiesListResponse;
// Retrieves a list of floodlight activities, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.FloodlightActivitiesListResponse;
// Updates an existing floodlight activity. This method supports patch semantics.
patch(resource: Schema.FloodlightActivity, profileId: string, id: string): Dfareporting.Schema.FloodlightActivity;
// Deletes an existing floodlight activity.
remove(profileId: string, id: string): void;
// Updates an existing floodlight activity.
update(resource: Schema.FloodlightActivity, profileId: string): Dfareporting.Schema.FloodlightActivity;
}
interface FloodlightActivityGroupsCollection {
// Gets one floodlight activity group by ID.
get(profileId: string, id: string): Dfareporting.Schema.FloodlightActivityGroup;
// Inserts a new floodlight activity group.
insert(resource: Schema.FloodlightActivityGroup, profileId: string): Dfareporting.Schema.FloodlightActivityGroup;
// Retrieves a list of floodlight activity groups, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.FloodlightActivityGroupsListResponse;
// Retrieves a list of floodlight activity groups, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.FloodlightActivityGroupsListResponse;
// Updates an existing floodlight activity group. This method supports patch semantics.
patch(resource: Schema.FloodlightActivityGroup, profileId: string, id: string): Dfareporting.Schema.FloodlightActivityGroup;
// Updates an existing floodlight activity group.
update(resource: Schema.FloodlightActivityGroup, profileId: string): Dfareporting.Schema.FloodlightActivityGroup;
}
interface FloodlightConfigurationsCollection {
// Gets one floodlight configuration by ID.
get(profileId: string, id: string): Dfareporting.Schema.FloodlightConfiguration;
// Retrieves a list of floodlight configurations, possibly filtered.
list(profileId: string): Dfareporting.Schema.FloodlightConfigurationsListResponse;
// Retrieves a list of floodlight configurations, possibly filtered.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.FloodlightConfigurationsListResponse;
// Updates an existing floodlight configuration. This method supports patch semantics.
patch(resource: Schema.FloodlightConfiguration, profileId: string, id: string): Dfareporting.Schema.FloodlightConfiguration;
// Updates an existing floodlight configuration.
update(resource: Schema.FloodlightConfiguration, profileId: string): Dfareporting.Schema.FloodlightConfiguration;
}
interface InventoryItemsCollection {
// Gets one inventory item by ID.
get(profileId: string, projectId: string, id: string): Dfareporting.Schema.InventoryItem;
// Retrieves a list of inventory items, possibly filtered. This method supports paging.
list(profileId: string, projectId: string): Dfareporting.Schema.InventoryItemsListResponse;
// Retrieves a list of inventory items, possibly filtered. This method supports paging.
list(profileId: string, projectId: string, optionalArgs: object): Dfareporting.Schema.InventoryItemsListResponse;
}
interface LanguagesCollection {
// Retrieves a list of languages.
list(profileId: string): Dfareporting.Schema.LanguagesListResponse;
}
interface MetrosCollection {
// Retrieves a list of metros.
list(profileId: string): Dfareporting.Schema.MetrosListResponse;
}
interface MobileAppsCollection {
// Gets one mobile app by ID.
get(profileId: string, id: string): Dfareporting.Schema.MobileApp;
// Retrieves list of available mobile apps.
list(profileId: string): Dfareporting.Schema.MobileAppsListResponse;
// Retrieves list of available mobile apps.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.MobileAppsListResponse;
}
interface MobileCarriersCollection {
// Gets one mobile carrier by ID.
get(profileId: string, id: string): Dfareporting.Schema.MobileCarrier;
// Retrieves a list of mobile carriers.
list(profileId: string): Dfareporting.Schema.MobileCarriersListResponse;
}
interface OperatingSystemVersionsCollection {
// Gets one operating system version by ID.
get(profileId: string, id: string): Dfareporting.Schema.OperatingSystemVersion;
// Retrieves a list of operating system versions.
list(profileId: string): Dfareporting.Schema.OperatingSystemVersionsListResponse;
}
interface OperatingSystemsCollection {
// Gets one operating system by DART ID.
get(profileId: string, dartId: string): Dfareporting.Schema.OperatingSystem;
// Retrieves a list of operating systems.
list(profileId: string): Dfareporting.Schema.OperatingSystemsListResponse;
}
interface OrderDocumentsCollection {
// Gets one order document by ID.
get(profileId: string, projectId: string, id: string): Dfareporting.Schema.OrderDocument;
// Retrieves a list of order documents, possibly filtered. This method supports paging.
list(profileId: string, projectId: string): Dfareporting.Schema.OrderDocumentsListResponse;
// Retrieves a list of order documents, possibly filtered. This method supports paging.
list(profileId: string, projectId: string, optionalArgs: object): Dfareporting.Schema.OrderDocumentsListResponse;
}
interface OrdersCollection {
// Gets one order by ID.
get(profileId: string, projectId: string, id: string): Dfareporting.Schema.Order;
// Retrieves a list of orders, possibly filtered. This method supports paging.
list(profileId: string, projectId: string): Dfareporting.Schema.OrdersListResponse;
// Retrieves a list of orders, possibly filtered. This method supports paging.
list(profileId: string, projectId: string, optionalArgs: object): Dfareporting.Schema.OrdersListResponse;
}
interface PlacementGroupsCollection {
// Gets one placement group by ID.
get(profileId: string, id: string): Dfareporting.Schema.PlacementGroup;
// Inserts a new placement group.
insert(resource: Schema.PlacementGroup, profileId: string): Dfareporting.Schema.PlacementGroup;
// Retrieves a list of placement groups, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.PlacementGroupsListResponse;
// Retrieves a list of placement groups, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.PlacementGroupsListResponse;
// Updates an existing placement group. This method supports patch semantics.
patch(resource: Schema.PlacementGroup, profileId: string, id: string): Dfareporting.Schema.PlacementGroup;
// Updates an existing placement group.
update(resource: Schema.PlacementGroup, profileId: string): Dfareporting.Schema.PlacementGroup;
}
interface PlacementStrategiesCollection {
// Gets one placement strategy by ID.
get(profileId: string, id: string): Dfareporting.Schema.PlacementStrategy;
// Inserts a new placement strategy.
insert(resource: Schema.PlacementStrategy, profileId: string): Dfareporting.Schema.PlacementStrategy;
// Retrieves a list of placement strategies, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.PlacementStrategiesListResponse;
// Retrieves a list of placement strategies, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.PlacementStrategiesListResponse;
// Updates an existing placement strategy. This method supports patch semantics.
patch(resource: Schema.PlacementStrategy, profileId: string, id: string): Dfareporting.Schema.PlacementStrategy;
// Deletes an existing placement strategy.
remove(profileId: string, id: string): void;
// Updates an existing placement strategy.
update(resource: Schema.PlacementStrategy, profileId: string): Dfareporting.Schema.PlacementStrategy;
}
interface PlacementsCollection {
// Generates tags for a placement.
generatetags(profileId: string): Dfareporting.Schema.PlacementsGenerateTagsResponse;
// Generates tags for a placement.
generatetags(profileId: string, optionalArgs: object): Dfareporting.Schema.PlacementsGenerateTagsResponse;
// Gets one placement by ID.
get(profileId: string, id: string): Dfareporting.Schema.Placement;
// Inserts a new placement.
insert(resource: Schema.Placement, profileId: string): Dfareporting.Schema.Placement;
// Retrieves a list of placements, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.PlacementsListResponse;
// Retrieves a list of placements, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.PlacementsListResponse;
// Updates an existing placement. This method supports patch semantics.
patch(resource: Schema.Placement, profileId: string, id: string): Dfareporting.Schema.Placement;
// Updates an existing placement.
update(resource: Schema.Placement, profileId: string): Dfareporting.Schema.Placement;
}
interface PlatformTypesCollection {
// Gets one platform type by ID.
get(profileId: string, id: string): Dfareporting.Schema.PlatformType;
// Retrieves a list of platform types.
list(profileId: string): Dfareporting.Schema.PlatformTypesListResponse;
}
interface PostalCodesCollection {
// Gets one postal code by ID.
get(profileId: string, code: string): Dfareporting.Schema.PostalCode;
// Retrieves a list of postal codes.
list(profileId: string): Dfareporting.Schema.PostalCodesListResponse;
}
interface ProjectsCollection {
// Gets one project by ID.
get(profileId: string, id: string): Dfareporting.Schema.Project;
// Retrieves a list of projects, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.ProjectsListResponse;
// Retrieves a list of projects, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.ProjectsListResponse;
}
interface RegionsCollection {
// Retrieves a list of regions.
list(profileId: string): Dfareporting.Schema.RegionsListResponse;
}
interface RemarketingListSharesCollection {
// Gets one remarketing list share by remarketing list ID.
get(profileId: string, remarketingListId: string): Dfareporting.Schema.RemarketingListShare;
// Updates an existing remarketing list share. This method supports patch semantics.
patch(resource: Schema.RemarketingListShare, profileId: string, remarketingListId: string): Dfareporting.Schema.RemarketingListShare;
// Updates an existing remarketing list share.
update(resource: Schema.RemarketingListShare, profileId: string): Dfareporting.Schema.RemarketingListShare;
}
interface RemarketingListsCollection {
// Gets one remarketing list by ID.
get(profileId: string, id: string): Dfareporting.Schema.RemarketingList;
// Inserts a new remarketing list.
insert(resource: Schema.RemarketingList, profileId: string): Dfareporting.Schema.RemarketingList;
// Retrieves a list of remarketing lists, possibly filtered. This method supports paging.
list(profileId: string, advertiserId: string): Dfareporting.Schema.RemarketingListsListResponse;
// Retrieves a list of remarketing lists, possibly filtered. This method supports paging.
list(profileId: string, advertiserId: string, optionalArgs: object): Dfareporting.Schema.RemarketingListsListResponse;
// Updates an existing remarketing list. This method supports patch semantics.
patch(resource: Schema.RemarketingList, profileId: string, id: string): Dfareporting.Schema.RemarketingList;
// Updates an existing remarketing list.
update(resource: Schema.RemarketingList, profileId: string): Dfareporting.Schema.RemarketingList;
}
interface ReportsCollection {
CompatibleFields?: Dfareporting.Collection.Reports.CompatibleFieldsCollection;
Files?: Dfareporting.Collection.Reports.FilesCollection;
// Retrieves a report by its ID.
get(profileId: string, reportId: string): Dfareporting.Schema.Report;
// Creates a report.
insert(resource: Schema.Report, profileId: string): Dfareporting.Schema.Report;
// Retrieves list of reports.
list(profileId: string): Dfareporting.Schema.ReportList;
// Retrieves list of reports.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.ReportList;
// Updates a report. This method supports patch semantics.
patch(resource: Schema.Report, profileId: string, reportId: string): Dfareporting.Schema.Report;
// Deletes a report by its ID.
remove(profileId: string, reportId: string): void;
// Runs a report.
run(profileId: string, reportId: string): Dfareporting.Schema.File;
// Runs a report.
run(profileId: string, reportId: string, optionalArgs: object): Dfareporting.Schema.File;
// Updates a report.
update(resource: Schema.Report, profileId: string, reportId: string): Dfareporting.Schema.Report;
}
interface SitesCollection {
// Gets one site by ID.
get(profileId: string, id: string): Dfareporting.Schema.Site;
// Inserts a new site.
insert(resource: Schema.Site, profileId: string): Dfareporting.Schema.Site;
// Retrieves a list of sites, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.SitesListResponse;
// Retrieves a list of sites, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.SitesListResponse;
// Updates an existing site. This method supports patch semantics.
patch(resource: Schema.Site, profileId: string, id: string): Dfareporting.Schema.Site;
// Updates an existing site.
update(resource: Schema.Site, profileId: string): Dfareporting.Schema.Site;
}
interface SizesCollection {
// Gets one size by ID.
get(profileId: string, id: string): Dfareporting.Schema.Size;
// Inserts a new size.
insert(resource: Schema.Size, profileId: string): Dfareporting.Schema.Size;
// Retrieves a list of sizes, possibly filtered. Retrieved sizes are globally unique and may include values not currently in use by your account. Due to this, the list of sizes returned by this method may differ from the list seen in the Trafficking UI.
list(profileId: string): Dfareporting.Schema.SizesListResponse;
// Retrieves a list of sizes, possibly filtered. Retrieved sizes are globally unique and may include values not currently in use by your account. Due to this, the list of sizes returned by this method may differ from the list seen in the Trafficking UI.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.SizesListResponse;
}
interface SubaccountsCollection {
// Gets one subaccount by ID.
get(profileId: string, id: string): Dfareporting.Schema.Subaccount;
// Inserts a new subaccount.
insert(resource: Schema.Subaccount, profileId: string): Dfareporting.Schema.Subaccount;
// Gets a list of subaccounts, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.SubaccountsListResponse;
// Gets a list of subaccounts, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.SubaccountsListResponse;
// Updates an existing subaccount. This method supports patch semantics.
patch(resource: Schema.Subaccount, profileId: string, id: string): Dfareporting.Schema.Subaccount;
// Updates an existing subaccount.
update(resource: Schema.Subaccount, profileId: string): Dfareporting.Schema.Subaccount;
}
interface TargetableRemarketingListsCollection {
// Gets one remarketing list by ID.
get(profileId: string, id: string): Dfareporting.Schema.TargetableRemarketingList;
// Retrieves a list of targetable remarketing lists, possibly filtered. This method supports paging.
list(profileId: string, advertiserId: string): Dfareporting.Schema.TargetableRemarketingListsListResponse;
// Retrieves a list of targetable remarketing lists, possibly filtered. This method supports paging.
list(profileId: string, advertiserId: string, optionalArgs: object): Dfareporting.Schema.TargetableRemarketingListsListResponse;
}
interface TargetingTemplatesCollection {
// Gets one targeting template by ID.
get(profileId: string, id: string): Dfareporting.Schema.TargetingTemplate;
// Inserts a new targeting template.
insert(resource: Schema.TargetingTemplate, profileId: string): Dfareporting.Schema.TargetingTemplate;
// Retrieves a list of targeting templates, optionally filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.TargetingTemplatesListResponse;
// Retrieves a list of targeting templates, optionally filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.TargetingTemplatesListResponse;
// Updates an existing targeting template. This method supports patch semantics.
patch(resource: Schema.TargetingTemplate, profileId: string, id: string): Dfareporting.Schema.TargetingTemplate;
// Updates an existing targeting template.
update(resource: Schema.TargetingTemplate, profileId: string): Dfareporting.Schema.TargetingTemplate;
}
interface UserProfilesCollection {
// Gets one user profile by ID.
get(profileId: string): Dfareporting.Schema.UserProfile;
// Retrieves list of user profiles for a user.
list(): Dfareporting.Schema.UserProfileList;
}
interface UserRolePermissionGroupsCollection {
// Gets one user role permission group by ID.
get(profileId: string, id: string): Dfareporting.Schema.UserRolePermissionGroup;
// Gets a list of all supported user role permission groups.
list(profileId: string): Dfareporting.Schema.UserRolePermissionGroupsListResponse;
}
interface UserRolePermissionsCollection {
// Gets one user role permission by ID.
get(profileId: string, id: string): Dfareporting.Schema.UserRolePermission;
// Gets a list of user role permissions, possibly filtered.
list(profileId: string): Dfareporting.Schema.UserRolePermissionsListResponse;
// Gets a list of user role permissions, possibly filtered.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.UserRolePermissionsListResponse;
}
interface UserRolesCollection {
// Gets one user role by ID.
get(profileId: string, id: string): Dfareporting.Schema.UserRole;
// Inserts a new user role.
insert(resource: Schema.UserRole, profileId: string): Dfareporting.Schema.UserRole;
// Retrieves a list of user roles, possibly filtered. This method supports paging.
list(profileId: string): Dfareporting.Schema.UserRolesListResponse;
// Retrieves a list of user roles, possibly filtered. This method supports paging.
list(profileId: string, optionalArgs: object): Dfareporting.Schema.UserRolesListResponse;
// Updates an existing user role. This method supports patch semantics.
patch(resource: Schema.UserRole, profileId: string, id: string): Dfareporting.Schema.UserRole;
// Deletes an existing user role.
remove(profileId: string, id: string): void;
// Updates an existing user role.
update(resource: Schema.UserRole, profileId: string): Dfareporting.Schema.UserRole;
}
interface VideoFormatsCollection {
// Gets one video format by ID.
get(profileId: string, id: number): Dfareporting.Schema.VideoFormat;
// Lists available video formats.
list(profileId: string): Dfareporting.Schema.VideoFormatsListResponse;
}
}
namespace Schema {
interface Account {
accountPermissionIds?: string[];
accountProfile?: string;
active?: boolean;
activeAdsLimitTier?: string;
activeViewOptOut?: boolean;
availablePermissionIds?: string[];
countryId?: string;
currencyId?: string;
defaultCreativeSizeId?: string;
description?: string;
id?: string;
kind?: string;
locale?: string;
maximumImageSize?: string;
name?: string;
nielsenOcrEnabled?: boolean;
reportsConfiguration?: Dfareporting.Schema.ReportsConfiguration;
shareReportsWithTwitter?: boolean;
teaserSizeLimit?: string;
}
interface AccountActiveAdSummary {
accountId?: string;
activeAds?: string;
activeAdsLimitTier?: string;
availableAds?: string;
kind?: string;
}
interface AccountPermission {
accountProfiles?: string[];
id?: string;
kind?: string;
level?: string;
name?: string;
permissionGroupId?: string;
}
interface AccountPermissionGroup {
id?: string;
kind?: string;
name?: string;
}
interface AccountPermissionGroupsListResponse {
accountPermissionGroups?: Dfareporting.Schema.AccountPermissionGroup[];
kind?: string;
}
interface AccountPermissionsListResponse {
accountPermissions?: Dfareporting.Schema.AccountPermission[];
kind?: string;
}
interface AccountUserProfile {
accountId?: string;
active?: boolean;
advertiserFilter?: Dfareporting.Schema.ObjectFilter;
campaignFilter?: Dfareporting.Schema.ObjectFilter;
comments?: string;
email?: string;
id?: string;
kind?: string;
locale?: string;
name?: string;
siteFilter?: Dfareporting.Schema.ObjectFilter;
subaccountId?: string;
traffickerType?: string;
userAccessType?: string;
userRoleFilter?: Dfareporting.Schema.ObjectFilter;
userRoleId?: string;
}
interface AccountUserProfilesListResponse {
accountUserProfiles?: Dfareporting.Schema.AccountUserProfile[];
kind?: string;
nextPageToken?: string;
}
interface AccountsListResponse {
accounts?: Dfareporting.Schema.Account[];
kind?: string;
nextPageToken?: string;
}
interface Activities {
filters?: Dfareporting.Schema.DimensionValue[];
kind?: string;
metricNames?: string[];
}
interface Ad {
accountId?: string;
active?: boolean;
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
archived?: boolean;
audienceSegmentId?: string;
campaignId?: string;
campaignIdDimensionValue?: Dfareporting.Schema.DimensionValue;
clickThroughUrl?: Dfareporting.Schema.ClickThroughUrl;
clickThroughUrlSuffixProperties?: Dfareporting.Schema.ClickThroughUrlSuffixProperties;
comments?: string;
compatibility?: string;
createInfo?: Dfareporting.Schema.LastModifiedInfo;
creativeGroupAssignments?: Dfareporting.Schema.CreativeGroupAssignment[];
creativeRotation?: Dfareporting.Schema.CreativeRotation;
dayPartTargeting?: Dfareporting.Schema.DayPartTargeting;
defaultClickThroughEventTagProperties?: Dfareporting.Schema.DefaultClickThroughEventTagProperties;
deliverySchedule?: Dfareporting.Schema.DeliverySchedule;
dynamicClickTracker?: boolean;
endTime?: string;
eventTagOverrides?: Dfareporting.Schema.EventTagOverride[];
geoTargeting?: Dfareporting.Schema.GeoTargeting;
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
keyValueTargetingExpression?: Dfareporting.Schema.KeyValueTargetingExpression;
kind?: string;
languageTargeting?: Dfareporting.Schema.LanguageTargeting;
lastModifiedInfo?: Dfareporting.Schema.LastModifiedInfo;
name?: string;
placementAssignments?: Dfareporting.Schema.PlacementAssignment[];
remarketingListExpression?: Dfareporting.Schema.ListTargetingExpression;
size?: Dfareporting.Schema.Size;
sslCompliant?: boolean;
sslRequired?: boolean;
startTime?: string;
subaccountId?: string;
targetingTemplateId?: string;
technologyTargeting?: Dfareporting.Schema.TechnologyTargeting;
type?: string;
}
interface AdBlockingConfiguration {
clickThroughUrl?: string;
creativeBundleId?: string;
enabled?: boolean;
overrideClickThroughUrl?: boolean;
}
interface AdSlot {
comment?: string;
compatibility?: string;
height?: string;
linkedPlacementId?: string;
name?: string;
paymentSourceType?: string;
primary?: boolean;
width?: string;
}
interface AdsListResponse {
ads?: Dfareporting.Schema.Ad[];
kind?: string;
nextPageToken?: string;
}
interface Advertiser {
accountId?: string;
advertiserGroupId?: string;
clickThroughUrlSuffix?: string;
defaultClickThroughEventTagId?: string;
defaultEmail?: string;
floodlightConfigurationId?: string;
floodlightConfigurationIdDimensionValue?: Dfareporting.Schema.DimensionValue;
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
kind?: string;
name?: string;
originalFloodlightConfigurationId?: string;
status?: string;
subaccountId?: string;
suspended?: boolean;
}
interface AdvertiserGroup {
accountId?: string;
id?: string;
kind?: string;
name?: string;
}
interface AdvertiserGroupsListResponse {
advertiserGroups?: Dfareporting.Schema.AdvertiserGroup[];
kind?: string;
nextPageToken?: string;
}
interface AdvertiserLandingPagesListResponse {
kind?: string;
landingPages?: Dfareporting.Schema.LandingPage[];
nextPageToken?: string;
}
interface AdvertisersListResponse {
advertisers?: Dfareporting.Schema.Advertiser[];
kind?: string;
nextPageToken?: string;
}
interface AudienceSegment {
allocation?: number;
id?: string;
name?: string;
}
interface AudienceSegmentGroup {
audienceSegments?: Dfareporting.Schema.AudienceSegment[];
id?: string;
name?: string;
}
interface Browser {
browserVersionId?: string;
dartId?: string;
kind?: string;
majorVersion?: string;
minorVersion?: string;
name?: string;
}
interface BrowsersListResponse {
browsers?: Dfareporting.Schema.Browser[];
kind?: string;
}
interface Campaign {
accountId?: string;
adBlockingConfiguration?: Dfareporting.Schema.AdBlockingConfiguration;
additionalCreativeOptimizationConfigurations?: Dfareporting.Schema.CreativeOptimizationConfiguration[];
advertiserGroupId?: string;
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
archived?: boolean;
audienceSegmentGroups?: Dfareporting.Schema.AudienceSegmentGroup[];
billingInvoiceCode?: string;
clickThroughUrlSuffixProperties?: Dfareporting.Schema.ClickThroughUrlSuffixProperties;
comment?: string;
createInfo?: Dfareporting.Schema.LastModifiedInfo;
creativeGroupIds?: string[];
creativeOptimizationConfiguration?: Dfareporting.Schema.CreativeOptimizationConfiguration;
defaultClickThroughEventTagProperties?: Dfareporting.Schema.DefaultClickThroughEventTagProperties;
defaultLandingPageId?: string;
endDate?: string;
eventTagOverrides?: Dfareporting.Schema.EventTagOverride[];
externalId?: string;
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
kind?: string;
lastModifiedInfo?: Dfareporting.Schema.LastModifiedInfo;
name?: string;
nielsenOcrEnabled?: boolean;
startDate?: string;
subaccountId?: string;
traffickerEmails?: string[];
}
interface CampaignCreativeAssociation {
creativeId?: string;
kind?: string;
}
interface CampaignCreativeAssociationsListResponse {
campaignCreativeAssociations?: Dfareporting.Schema.CampaignCreativeAssociation[];
kind?: string;
nextPageToken?: string;
}
interface CampaignsListResponse {
campaigns?: Dfareporting.Schema.Campaign[];
kind?: string;
nextPageToken?: string;
}
interface ChangeLog {
accountId?: string;
action?: string;
changeTime?: string;
fieldName?: string;
id?: string;
kind?: string;
newValue?: string;
objectId?: string;
objectType?: string;
oldValue?: string;
subaccountId?: string;
transactionId?: string;
userProfileId?: string;
userProfileName?: string;
}
interface ChangeLogsListResponse {
changeLogs?: Dfareporting.Schema.ChangeLog[];
kind?: string;
nextPageToken?: string;
}
interface CitiesListResponse {
cities?: Dfareporting.Schema.City[];
kind?: string;
}
interface City {
countryCode?: string;
countryDartId?: string;
dartId?: string;
kind?: string;
metroCode?: string;
metroDmaId?: string;
name?: string;
regionCode?: string;
regionDartId?: string;
}
interface ClickTag {
clickThroughUrl?: Dfareporting.Schema.CreativeClickThroughUrl;
eventName?: string;
name?: string;
}
interface ClickThroughUrl {
computedClickThroughUrl?: string;
customClickThroughUrl?: string;
defaultLandingPage?: boolean;
landingPageId?: string;
}
interface ClickThroughUrlSuffixProperties {
clickThroughUrlSuffix?: string;
overrideInheritedSuffix?: boolean;
}
interface CompanionClickThroughOverride {
clickThroughUrl?: Dfareporting.Schema.ClickThroughUrl;
creativeId?: string;
}
interface CompanionSetting {
companionsDisabled?: boolean;
enabledSizes?: Dfareporting.Schema.Size[];
imageOnly?: boolean;
kind?: string;
}
interface CompatibleFields {
crossDimensionReachReportCompatibleFields?: Dfareporting.Schema.CrossDimensionReachReportCompatibleFields;
floodlightReportCompatibleFields?: Dfareporting.Schema.FloodlightReportCompatibleFields;
kind?: string;
pathToConversionReportCompatibleFields?: Dfareporting.Schema.PathToConversionReportCompatibleFields;
reachReportCompatibleFields?: Dfareporting.Schema.ReachReportCompatibleFields;
reportCompatibleFields?: Dfareporting.Schema.ReportCompatibleFields;
}
interface ConnectionType {
id?: string;
kind?: string;
name?: string;
}
interface ConnectionTypesListResponse {
connectionTypes?: Dfareporting.Schema.ConnectionType[];
kind?: string;
}
interface ContentCategoriesListResponse {
contentCategories?: Dfareporting.Schema.ContentCategory[];
kind?: string;
nextPageToken?: string;
}
interface ContentCategory {
accountId?: string;
id?: string;
kind?: string;
name?: string;
}
interface Conversion {
childDirectedTreatment?: boolean;
customVariables?: Dfareporting.Schema.CustomFloodlightVariable[];
encryptedUserId?: string;
encryptedUserIdCandidates?: string[];
floodlightActivityId?: string;
floodlightConfigurationId?: string;
gclid?: string;
kind?: string;
limitAdTracking?: boolean;
mobileDeviceId?: string;
nonPersonalizedAd?: boolean;
ordinal?: string;
quantity?: string;
timestampMicros?: string;
treatmentForUnderage?: boolean;
value?: number;
}
interface ConversionError {
code?: string;
kind?: string;
message?: string;
}
interface ConversionStatus {
conversion?: Dfareporting.Schema.Conversion;
errors?: Dfareporting.Schema.ConversionError[];
kind?: string;
}
interface ConversionsBatchInsertRequest {
conversions?: Dfareporting.Schema.Conversion[];
encryptionInfo?: Dfareporting.Schema.EncryptionInfo;
kind?: string;
}
interface ConversionsBatchInsertResponse {
hasFailures?: boolean;
kind?: string;
status?: Dfareporting.Schema.ConversionStatus[];
}
interface ConversionsBatchUpdateRequest {
conversions?: Dfareporting.Schema.Conversion[];
encryptionInfo?: Dfareporting.Schema.EncryptionInfo;
kind?: string;
}
interface ConversionsBatchUpdateResponse {
hasFailures?: boolean;
kind?: string;
status?: Dfareporting.Schema.ConversionStatus[];
}
interface CountriesListResponse {
countries?: Dfareporting.Schema.Country[];
kind?: string;
}
interface Country {
countryCode?: string;
dartId?: string;
kind?: string;
name?: string;
sslEnabled?: boolean;
}
interface Creative {
accountId?: string;
active?: boolean;
adParameters?: string;
adTagKeys?: string[];
additionalSizes?: Dfareporting.Schema.Size[];
advertiserId?: string;
allowScriptAccess?: boolean;
archived?: boolean;
artworkType?: string;
authoringSource?: string;
authoringTool?: string;
autoAdvanceImages?: boolean;
backgroundColor?: string;
backupImageClickThroughUrl?: Dfareporting.Schema.CreativeClickThroughUrl;
backupImageFeatures?: string[];
backupImageReportingLabel?: string;
backupImageTargetWindow?: Dfareporting.Schema.TargetWindow;
clickTags?: Dfareporting.Schema.ClickTag[];
commercialId?: string;
companionCreatives?: string[];
compatibility?: string[];
convertFlashToHtml5?: boolean;
counterCustomEvents?: Dfareporting.Schema.CreativeCustomEvent[];
creativeAssetSelection?: Dfareporting.Schema.CreativeAssetSelection;
creativeAssets?: Dfareporting.Schema.CreativeAsset[];
creativeFieldAssignments?: Dfareporting.Schema.CreativeFieldAssignment[];
customKeyValues?: string[];
dynamicAssetSelection?: boolean;
exitCustomEvents?: Dfareporting.Schema.CreativeCustomEvent[];
fsCommand?: Dfareporting.Schema.FsCommand;
htmlCode?: string;
htmlCodeLocked?: boolean;
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
kind?: string;
lastModifiedInfo?: Dfareporting.Schema.LastModifiedInfo;
latestTraffickedCreativeId?: string;
mediaDescription?: string;
mediaDuration?: number;
name?: string;
overrideCss?: string;
progressOffset?: Dfareporting.Schema.VideoOffset;
redirectUrl?: string;
renderingId?: string;
renderingIdDimensionValue?: Dfareporting.Schema.DimensionValue;
requiredFlashPluginVersion?: string;
requiredFlashVersion?: number;
size?: Dfareporting.Schema.Size;
skipOffset?: Dfareporting.Schema.VideoOffset;
skippable?: boolean;
sslCompliant?: boolean;
sslOverride?: boolean;
studioAdvertiserId?: string;
studioCreativeId?: string;
studioTraffickedCreativeId?: string;
subaccountId?: string;
thirdPartyBackupImageImpressionsUrl?: string;
thirdPartyRichMediaImpressionsUrl?: string;
thirdPartyUrls?: Dfareporting.Schema.ThirdPartyTrackingUrl[];
timerCustomEvents?: Dfareporting.Schema.CreativeCustomEvent[];
totalFileSize?: string;
type?: string;
universalAdId?: Dfareporting.Schema.UniversalAdId;
version?: number;
}
interface CreativeAsset {
actionScript3?: boolean;
active?: boolean;
additionalSizes?: Dfareporting.Schema.Size[];
alignment?: string;
artworkType?: string;
assetIdentifier?: Dfareporting.Schema.CreativeAssetId;
audioBitRate?: number;
audioSampleRate?: number;
backupImageExit?: Dfareporting.Schema.CreativeCustomEvent;
bitRate?: number;
childAssetType?: string;
collapsedSize?: Dfareporting.Schema.Size;
companionCreativeIds?: string[];
customStartTimeValue?: number;
detectedFeatures?: string[];
displayType?: string;
duration?: number;
durationType?: string;
expandedDimension?: Dfareporting.Schema.Size;
fileSize?: string;
flashVersion?: number;
frameRate?: number;
hideFlashObjects?: boolean;
hideSelectionBoxes?: boolean;
horizontallyLocked?: boolean;
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
mediaDuration?: number;
mimeType?: string;
offset?: Dfareporting.Schema.OffsetPosition;
orientation?: string;
originalBackup?: boolean;
politeLoad?: boolean;
position?: Dfareporting.Schema.OffsetPosition;
positionLeftUnit?: string;
positionTopUnit?: string;
progressiveServingUrl?: string;
pushdown?: boolean;
pushdownDuration?: number;
role?: string;
size?: Dfareporting.Schema.Size;
sslCompliant?: boolean;
startTimeType?: string;
streamingServingUrl?: string;
transparency?: boolean;
verticallyLocked?: boolean;
windowMode?: string;
zIndex?: number;
zipFilename?: string;
zipFilesize?: string;
}
interface CreativeAssetId {
name?: string;
type?: string;
}
interface CreativeAssetMetadata {
assetIdentifier?: Dfareporting.Schema.CreativeAssetId;
clickTags?: Dfareporting.Schema.ClickTag[];
detectedFeatures?: string[];
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
kind?: string;
warnedValidationRules?: string[];
}
interface CreativeAssetSelection {
defaultAssetId?: string;
rules?: Dfareporting.Schema.Rule[];
}
interface CreativeAssignment {
active?: boolean;
applyEventTags?: boolean;
clickThroughUrl?: Dfareporting.Schema.ClickThroughUrl;
companionCreativeOverrides?: Dfareporting.Schema.CompanionClickThroughOverride[];
creativeGroupAssignments?: Dfareporting.Schema.CreativeGroupAssignment[];
creativeId?: string;
creativeIdDimensionValue?: Dfareporting.Schema.DimensionValue;
endTime?: string;
richMediaExitOverrides?: Dfareporting.Schema.RichMediaExitOverride[];
sequence?: number;
sslCompliant?: boolean;
startTime?: string;
weight?: number;
}
interface CreativeClickThroughUrl {
computedClickThroughUrl?: string;
customClickThroughUrl?: string;
landingPageId?: string;
}
interface CreativeCustomEvent {
advertiserCustomEventId?: string;
advertiserCustomEventName?: string;
advertiserCustomEventType?: string;
artworkLabel?: string;
artworkType?: string;
exitClickThroughUrl?: Dfareporting.Schema.CreativeClickThroughUrl;
id?: string;
popupWindowProperties?: Dfareporting.Schema.PopupWindowProperties;
targetType?: string;
videoReportingId?: string;
}
interface CreativeField {
accountId?: string;
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
id?: string;
kind?: string;
name?: string;
subaccountId?: string;
}
interface CreativeFieldAssignment {
creativeFieldId?: string;
creativeFieldValueId?: string;
}
interface CreativeFieldValue {
id?: string;
kind?: string;
value?: string;
}
interface CreativeFieldValuesListResponse {
creativeFieldValues?: Dfareporting.Schema.CreativeFieldValue[];
kind?: string;
nextPageToken?: string;
}
interface CreativeFieldsListResponse {
creativeFields?: Dfareporting.Schema.CreativeField[];
kind?: string;
nextPageToken?: string;
}
interface CreativeGroup {
accountId?: string;
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
groupNumber?: number;
id?: string;
kind?: string;
name?: string;
subaccountId?: string;
}
interface CreativeGroupAssignment {
creativeGroupId?: string;
creativeGroupNumber?: string;
}
interface CreativeGroupsListResponse {
creativeGroups?: Dfareporting.Schema.CreativeGroup[];
kind?: string;
nextPageToken?: string;
}
interface CreativeOptimizationConfiguration {
id?: string;
name?: string;
optimizationActivitys?: Dfareporting.Schema.OptimizationActivity[];
optimizationModel?: string;
}
interface CreativeRotation {
creativeAssignments?: Dfareporting.Schema.CreativeAssignment[];
creativeOptimizationConfigurationId?: string;
type?: string;
weightCalculationStrategy?: string;
}
interface CreativesListResponse {
creatives?: Dfareporting.Schema.Creative[];
kind?: string;
nextPageToken?: string;
}
interface CrossDimensionReachReportCompatibleFields {
breakdown?: Dfareporting.Schema.Dimension[];
dimensionFilters?: Dfareporting.Schema.Dimension[];
kind?: string;
metrics?: Dfareporting.Schema.Metric[];
overlapMetrics?: Dfareporting.Schema.Metric[];
}
interface CustomFloodlightVariable {
kind?: string;
type?: string;
value?: string;
}
interface CustomRichMediaEvents {
filteredEventIds?: Dfareporting.Schema.DimensionValue[];
kind?: string;
}
interface CustomViewabilityMetric {
configuration?: Dfareporting.Schema.CustomViewabilityMetricConfiguration;
id?: string;
name?: string;
}
interface CustomViewabilityMetricConfiguration {
audible?: boolean;
timeMillis?: number;
timePercent?: number;
viewabilityPercent?: number;
}
interface DateRange {
endDate?: string;
kind?: string;
relativeDateRange?: string;
startDate?: string;
}
interface DayPartTargeting {
daysOfWeek?: string[];
hoursOfDay?: number[];
userLocalTime?: boolean;
}
interface DeepLink {
appUrl?: string;
fallbackUrl?: string;
kind?: string;
mobileApp?: Dfareporting.Schema.MobileApp;
remarketingListIds?: string[];
}
interface DefaultClickThroughEventTagProperties {
defaultClickThroughEventTagId?: string;
overrideInheritedEventTag?: boolean;
}
interface DeliverySchedule {
frequencyCap?: Dfareporting.Schema.FrequencyCap;
hardCutoff?: boolean;
impressionRatio?: string;
priority?: string;
}
interface DfpSettings {
dfpNetworkCode?: string;
dfpNetworkName?: string;
programmaticPlacementAccepted?: boolean;
pubPaidPlacementAccepted?: boolean;
publisherPortalOnly?: boolean;
}
interface Dimension {
kind?: string;
name?: string;
}
interface DimensionFilter {
dimensionName?: string;
kind?: string;
value?: string;
}
interface DimensionValue {
dimensionName?: string;
etag?: string;
id?: string;
kind?: string;
matchType?: string;
value?: string;
}
interface DimensionValueList {
etag?: string;
items?: Dfareporting.Schema.DimensionValue[];
kind?: string;
nextPageToken?: string;
}
interface DimensionValueRequest {
dimensionName?: string;
endDate?: string;
filters?: Dfareporting.Schema.DimensionFilter[];
kind?: string;
startDate?: string;
}
interface DirectorySite {
active?: boolean;
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
inpageTagFormats?: string[];
interstitialTagFormats?: string[];
kind?: string;
name?: string;
settings?: Dfareporting.Schema.DirectorySiteSettings;
url?: string;
}
interface DirectorySiteSettings {
activeViewOptOut?: boolean;
dfpSettings?: Dfareporting.Schema.DfpSettings;
instreamVideoPlacementAccepted?: boolean;
interstitialPlacementAccepted?: boolean;
}
interface DirectorySitesListResponse {
directorySites?: Dfareporting.Schema.DirectorySite[];
kind?: string;
nextPageToken?: string;
}
interface DynamicTargetingKey {
kind?: string;
name?: string;
objectId?: string;
objectType?: string;
}
interface DynamicTargetingKeysListResponse {
dynamicTargetingKeys?: Dfareporting.Schema.DynamicTargetingKey[];
kind?: string;
}
interface EncryptionInfo {
encryptionEntityId?: string;
encryptionEntityType?: string;
encryptionSource?: string;
kind?: string;
}
interface EventTag {
accountId?: string;
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
campaignId?: string;
campaignIdDimensionValue?: Dfareporting.Schema.DimensionValue;
enabledByDefault?: boolean;
excludeFromAdxRequests?: boolean;
id?: string;
kind?: string;
name?: string;
siteFilterType?: string;
siteIds?: string[];
sslCompliant?: boolean;
status?: string;
subaccountId?: string;
type?: string;
url?: string;
urlEscapeLevels?: number;
}
interface EventTagOverride {
enabled?: boolean;
id?: string;
}
interface EventTagsListResponse {
eventTags?: Dfareporting.Schema.EventTag[];
kind?: string;
}
interface File {
dateRange?: Dfareporting.Schema.DateRange;
etag?: string;
fileName?: string;
format?: string;
id?: string;
kind?: string;
lastModifiedTime?: string;
reportId?: string;
status?: string;
urls?: Dfareporting.Schema.FileUrls;
}
interface FileList {
etag?: string;
items?: Dfareporting.Schema.File[];
kind?: string;
nextPageToken?: string;
}
interface FileUrls {
apiUrl?: string;
browserUrl?: string;
}
interface Flight {
endDate?: string;
rateOrCost?: string;
startDate?: string;
units?: string;
}
interface FloodlightActivitiesGenerateTagResponse {
floodlightActivityTag?: string;
globalSiteTagGlobalSnippet?: string;
kind?: string;
}
interface FloodlightActivitiesListResponse {
floodlightActivities?: Dfareporting.Schema.FloodlightActivity[];
kind?: string;
nextPageToken?: string;
}
interface FloodlightActivity {
accountId?: string;
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
cacheBustingType?: string;
countingMethod?: string;
defaultTags?: Dfareporting.Schema.FloodlightActivityDynamicTag[];
expectedUrl?: string;
floodlightActivityGroupId?: string;
floodlightActivityGroupName?: string;
floodlightActivityGroupTagString?: string;
floodlightActivityGroupType?: string;
floodlightConfigurationId?: string;
floodlightConfigurationIdDimensionValue?: Dfareporting.Schema.DimensionValue;
floodlightTagType?: string;
hidden?: boolean;
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
kind?: string;
name?: string;
notes?: string;
publisherTags?: Dfareporting.Schema.FloodlightActivityPublisherDynamicTag[];
secure?: boolean;
sslCompliant?: boolean;
sslRequired?: boolean;
subaccountId?: string;
tagFormat?: string;
tagString?: string;
userDefinedVariableTypes?: string[];
}
interface FloodlightActivityDynamicTag {
id?: string;
name?: string;
tag?: string;
}
interface FloodlightActivityGroup {
accountId?: string;
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
floodlightConfigurationId?: string;
floodlightConfigurationIdDimensionValue?: Dfareporting.Schema.DimensionValue;
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
kind?: string;
name?: string;
subaccountId?: string;
tagString?: string;
type?: string;
}
interface FloodlightActivityGroupsListResponse {
floodlightActivityGroups?: Dfareporting.Schema.FloodlightActivityGroup[];
kind?: string;
nextPageToken?: string;
}
interface FloodlightActivityPublisherDynamicTag {
clickThrough?: boolean;
directorySiteId?: string;
dynamicTag?: Dfareporting.Schema.FloodlightActivityDynamicTag;
siteId?: string;
siteIdDimensionValue?: Dfareporting.Schema.DimensionValue;
viewThrough?: boolean;
}
interface FloodlightConfiguration {
accountId?: string;
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
analyticsDataSharingEnabled?: boolean;
customViewabilityMetric?: Dfareporting.Schema.CustomViewabilityMetric;
exposureToConversionEnabled?: boolean;
firstDayOfWeek?: string;
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
inAppAttributionTrackingEnabled?: boolean;
kind?: string;
lookbackConfiguration?: Dfareporting.Schema.LookbackConfiguration;
naturalSearchConversionAttributionOption?: string;
omnitureSettings?: Dfareporting.Schema.OmnitureSettings;
subaccountId?: string;
tagSettings?: Dfareporting.Schema.TagSettings;
thirdPartyAuthenticationTokens?: Dfareporting.Schema.ThirdPartyAuthenticationToken[];
userDefinedVariableConfigurations?: Dfareporting.Schema.UserDefinedVariableConfiguration[];
}
interface FloodlightConfigurationsListResponse {
floodlightConfigurations?: Dfareporting.Schema.FloodlightConfiguration[];
kind?: string;
}
interface FloodlightReportCompatibleFields {
dimensionFilters?: Dfareporting.Schema.Dimension[];
dimensions?: Dfareporting.Schema.Dimension[];
kind?: string;
metrics?: Dfareporting.Schema.Metric[];
}
interface FrequencyCap {
duration?: string;
impressions?: string;
}
interface FsCommand {
left?: number;
positionOption?: string;
top?: number;
windowHeight?: number;
windowWidth?: number;
}
interface GeoTargeting {
cities?: Dfareporting.Schema.City[];
countries?: Dfareporting.Schema.Country[];
excludeCountries?: boolean;
metros?: Dfareporting.Schema.Metro[];
postalCodes?: Dfareporting.Schema.PostalCode[];
regions?: Dfareporting.Schema.Region[];
}
interface InventoryItem {
accountId?: string;
adSlots?: Dfareporting.Schema.AdSlot[];
advertiserId?: string;
contentCategoryId?: string;
estimatedClickThroughRate?: string;
estimatedConversionRate?: string;
id?: string;
inPlan?: boolean;
kind?: string;
lastModifiedInfo?: Dfareporting.Schema.LastModifiedInfo;
name?: string;
negotiationChannelId?: string;
orderId?: string;
placementStrategyId?: string;
pricing?: Dfareporting.Schema.Pricing;
projectId?: string;
rfpId?: string;
siteId?: string;
subaccountId?: string;
type?: string;
}
interface InventoryItemsListResponse {
inventoryItems?: Dfareporting.Schema.InventoryItem[];
kind?: string;
nextPageToken?: string;
}
interface KeyValueTargetingExpression {
expression?: string;
}
interface LandingPage {
advertiserId?: string;
archived?: boolean;
deepLinks?: Dfareporting.Schema.DeepLink[];
id?: string;
kind?: string;
name?: string;
url?: string;
}
interface Language {
id?: string;
kind?: string;
languageCode?: string;
name?: string;
}
interface LanguageTargeting {
languages?: Dfareporting.Schema.Language[];
}
interface LanguagesListResponse {
kind?: string;
languages?: Dfareporting.Schema.Language[];
}
interface LastModifiedInfo {
time?: string;
}
interface ListPopulationClause {
terms?: Dfareporting.Schema.ListPopulationTerm[];
}
interface ListPopulationRule {
floodlightActivityId?: string;
floodlightActivityName?: string;
listPopulationClauses?: Dfareporting.Schema.ListPopulationClause[];
}
interface ListPopulationTerm {
contains?: boolean;
negation?: boolean;
operator?: string;
remarketingListId?: string;
type?: string;
value?: string;
variableFriendlyName?: string;
variableName?: string;
}
interface ListTargetingExpression {
expression?: string;
}
interface LookbackConfiguration {
clickDuration?: number;
postImpressionActivitiesDuration?: number;
}
interface Metric {
kind?: string;
name?: string;
}
interface Metro {
countryCode?: string;
countryDartId?: string;
dartId?: string;
dmaId?: string;
kind?: string;
metroCode?: string;
name?: string;
}
interface MetrosListResponse {
kind?: string;
metros?: Dfareporting.Schema.Metro[];
}
interface MobileApp {
directory?: string;
id?: string;
kind?: string;
publisherName?: string;
title?: string;
}
interface MobileAppsListResponse {
kind?: string;
mobileApps?: Dfareporting.Schema.MobileApp[];
nextPageToken?: string;
}
interface MobileCarrier {
countryCode?: string;
countryDartId?: string;
id?: string;
kind?: string;
name?: string;
}
interface MobileCarriersListResponse {
kind?: string;
mobileCarriers?: Dfareporting.Schema.MobileCarrier[];
}
interface ObjectFilter {
kind?: string;
objectIds?: string[];
status?: string;
}
interface OffsetPosition {
left?: number;
top?: number;
}
interface OmnitureSettings {
omnitureCostDataEnabled?: boolean;
omnitureIntegrationEnabled?: boolean;
}
interface OperatingSystem {
dartId?: string;
desktop?: boolean;
kind?: string;
mobile?: boolean;
name?: string;
}
interface OperatingSystemVersion {
id?: string;
kind?: string;
majorVersion?: string;
minorVersion?: string;
name?: string;
operatingSystem?: Dfareporting.Schema.OperatingSystem;
}
interface OperatingSystemVersionsListResponse {
kind?: string;
operatingSystemVersions?: Dfareporting.Schema.OperatingSystemVersion[];
}
interface OperatingSystemsListResponse {
kind?: string;
operatingSystems?: Dfareporting.Schema.OperatingSystem[];
}
interface OptimizationActivity {
floodlightActivityId?: string;
floodlightActivityIdDimensionValue?: Dfareporting.Schema.DimensionValue;
weight?: number;
}
interface Order {
accountId?: string;
advertiserId?: string;
approverUserProfileIds?: string[];
buyerInvoiceId?: string;
buyerOrganizationName?: string;
comments?: string;
contacts?: Dfareporting.Schema.OrderContact[];
id?: string;
kind?: string;
lastModifiedInfo?: Dfareporting.Schema.LastModifiedInfo;
name?: string;
notes?: string;
planningTermId?: string;
projectId?: string;
sellerOrderId?: string;
sellerOrganizationName?: string;
siteId?: string[];
siteNames?: string[];
subaccountId?: string;
termsAndConditions?: string;
}
interface OrderContact {
contactInfo?: string;
contactName?: string;
contactTitle?: string;
contactType?: string;
signatureUserProfileId?: string;
}
interface OrderDocument {
accountId?: string;
advertiserId?: string;
amendedOrderDocumentId?: string;
approvedByUserProfileIds?: string[];
cancelled?: boolean;
createdInfo?: Dfareporting.Schema.LastModifiedInfo;
effectiveDate?: string;
id?: string;
kind?: string;
lastSentRecipients?: string[];
lastSentTime?: string;
orderId?: string;
projectId?: string;
signed?: boolean;
subaccountId?: string;
title?: string;
type?: string;
}
interface OrderDocumentsListResponse {
kind?: string;
nextPageToken?: string;
orderDocuments?: Dfareporting.Schema.OrderDocument[];
}
interface OrdersListResponse {
kind?: string;
nextPageToken?: string;
orders?: Dfareporting.Schema.Order[];
}
interface PathToConversionReportCompatibleFields {
conversionDimensions?: Dfareporting.Schema.Dimension[];
customFloodlightVariables?: Dfareporting.Schema.Dimension[];
kind?: string;
metrics?: Dfareporting.Schema.Metric[];
perInteractionDimensions?: Dfareporting.Schema.Dimension[];
}
interface Placement {
accountId?: string;
adBlockingOptOut?: boolean;
additionalSizes?: Dfareporting.Schema.Size[];
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
archived?: boolean;
campaignId?: string;
campaignIdDimensionValue?: Dfareporting.Schema.DimensionValue;
comment?: string;
compatibility?: string;
contentCategoryId?: string;
createInfo?: Dfareporting.Schema.LastModifiedInfo;
directorySiteId?: string;
directorySiteIdDimensionValue?: Dfareporting.Schema.DimensionValue;
externalId?: string;
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
keyName?: string;
kind?: string;
lastModifiedInfo?: Dfareporting.Schema.LastModifiedInfo;
lookbackConfiguration?: Dfareporting.Schema.LookbackConfiguration;
name?: string;
paymentApproved?: boolean;
paymentSource?: string;
placementGroupId?: string;
placementGroupIdDimensionValue?: Dfareporting.Schema.DimensionValue;
placementStrategyId?: string;
pricingSchedule?: Dfareporting.Schema.PricingSchedule;
primary?: boolean;
publisherUpdateInfo?: Dfareporting.Schema.LastModifiedInfo;
siteId?: string;
siteIdDimensionValue?: Dfareporting.Schema.DimensionValue;
size?: Dfareporting.Schema.Size;
sslRequired?: boolean;
status?: string;
subaccountId?: string;
tagFormats?: string[];
tagSetting?: Dfareporting.Schema.TagSetting;
videoActiveViewOptOut?: boolean;
videoSettings?: Dfareporting.Schema.VideoSettings;
vpaidAdapterChoice?: string;
}
interface PlacementAssignment {
active?: boolean;
placementId?: string;
placementIdDimensionValue?: Dfareporting.Schema.DimensionValue;
sslRequired?: boolean;
}
interface PlacementGroup {
accountId?: string;
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
archived?: boolean;
campaignId?: string;
campaignIdDimensionValue?: Dfareporting.Schema.DimensionValue;
childPlacementIds?: string[];
comment?: string;
contentCategoryId?: string;
createInfo?: Dfareporting.Schema.LastModifiedInfo;
directorySiteId?: string;
directorySiteIdDimensionValue?: Dfareporting.Schema.DimensionValue;
externalId?: string;
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
kind?: string;
lastModifiedInfo?: Dfareporting.Schema.LastModifiedInfo;
name?: string;
placementGroupType?: string;
placementStrategyId?: string;
pricingSchedule?: Dfareporting.Schema.PricingSchedule;
primaryPlacementId?: string;
primaryPlacementIdDimensionValue?: Dfareporting.Schema.DimensionValue;
siteId?: string;
siteIdDimensionValue?: Dfareporting.Schema.DimensionValue;
subaccountId?: string;
}
interface PlacementGroupsListResponse {
kind?: string;
nextPageToken?: string;
placementGroups?: Dfareporting.Schema.PlacementGroup[];
}
interface PlacementStrategiesListResponse {
kind?: string;
nextPageToken?: string;
placementStrategies?: Dfareporting.Schema.PlacementStrategy[];
}
interface PlacementStrategy {
accountId?: string;
id?: string;
kind?: string;
name?: string;
}
interface PlacementTag {
placementId?: string;
tagDatas?: Dfareporting.Schema.TagData[];
}
interface PlacementsGenerateTagsResponse {
kind?: string;
placementTags?: Dfareporting.Schema.PlacementTag[];
}
interface PlacementsListResponse {
kind?: string;
nextPageToken?: string;
placements?: Dfareporting.Schema.Placement[];
}
interface PlatformType {
id?: string;
kind?: string;
name?: string;
}
interface PlatformTypesListResponse {
kind?: string;
platformTypes?: Dfareporting.Schema.PlatformType[];
}
interface PopupWindowProperties {
dimension?: Dfareporting.Schema.Size;
offset?: Dfareporting.Schema.OffsetPosition;
positionType?: string;
showAddressBar?: boolean;
showMenuBar?: boolean;
showScrollBar?: boolean;
showStatusBar?: boolean;
showToolBar?: boolean;
title?: string;
}
interface PostalCode {
code?: string;
countryCode?: string;
countryDartId?: string;
id?: string;
kind?: string;
}
interface PostalCodesListResponse {
kind?: string;
postalCodes?: Dfareporting.Schema.PostalCode[];
}
interface Pricing {
capCostType?: string;
endDate?: string;
flights?: Dfareporting.Schema.Flight[];
groupType?: string;
pricingType?: string;
startDate?: string;
}
interface PricingSchedule {
capCostOption?: string;
disregardOverdelivery?: boolean;
endDate?: string;
flighted?: boolean;
floodlightActivityId?: string;
pricingPeriods?: Dfareporting.Schema.PricingSchedulePricingPeriod[];
pricingType?: string;
startDate?: string;
testingStartDate?: string;
}
interface PricingSchedulePricingPeriod {
endDate?: string;
pricingComment?: string;
rateOrCostNanos?: string;
startDate?: string;
units?: string;
}
interface Project {
accountId?: string;
advertiserId?: string;
audienceAgeGroup?: string;
audienceGender?: string;
budget?: string;
clientBillingCode?: string;
clientName?: string;
endDate?: string;
id?: string;
kind?: string;
lastModifiedInfo?: Dfareporting.Schema.LastModifiedInfo;
name?: string;
overview?: string;
startDate?: string;
subaccountId?: string;
targetClicks?: string;
targetConversions?: string;
targetCpaNanos?: string;
targetCpcNanos?: string;
targetCpmActiveViewNanos?: string;
targetCpmNanos?: string;
targetImpressions?: string;
}
interface ProjectsListResponse {
kind?: string;
nextPageToken?: string;
projects?: Dfareporting.Schema.Project[];
}
interface ReachReportCompatibleFields {
dimensionFilters?: Dfareporting.Schema.Dimension[];
dimensions?: Dfareporting.Schema.Dimension[];
kind?: string;
metrics?: Dfareporting.Schema.Metric[];
pivotedActivityMetrics?: Dfareporting.Schema.Metric[];
reachByFrequencyMetrics?: Dfareporting.Schema.Metric[];
}
interface Recipient {
deliveryType?: string;
email?: string;
kind?: string;
}
interface Region {
countryCode?: string;
countryDartId?: string;
dartId?: string;
kind?: string;
name?: string;
regionCode?: string;
}
interface RegionsListResponse {
kind?: string;
regions?: Dfareporting.Schema.Region[];
}
interface RemarketingList {
accountId?: string;
active?: boolean;
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
description?: string;
id?: string;
kind?: string;
lifeSpan?: string;
listPopulationRule?: Dfareporting.Schema.ListPopulationRule;
listSize?: string;
listSource?: string;
name?: string;
subaccountId?: string;
}
interface RemarketingListShare {
kind?: string;
remarketingListId?: string;
sharedAccountIds?: string[];
sharedAdvertiserIds?: string[];
}
interface RemarketingListsListResponse {
kind?: string;
nextPageToken?: string;
remarketingLists?: Dfareporting.Schema.RemarketingList[];
}
interface Report {
accountId?: string;
criteria?: Dfareporting.Schema.ReportCriteria;
crossDimensionReachCriteria?: Dfareporting.Schema.ReportCrossDimensionReachCriteria;
delivery?: Dfareporting.Schema.ReportDelivery;
etag?: string;
fileName?: string;
floodlightCriteria?: Dfareporting.Schema.ReportFloodlightCriteria;
format?: string;
id?: string;
kind?: string;
lastModifiedTime?: string;
name?: string;
ownerProfileId?: string;
pathToConversionCriteria?: Dfareporting.Schema.ReportPathToConversionCriteria;
reachCriteria?: Dfareporting.Schema.ReportReachCriteria;
schedule?: Dfareporting.Schema.ReportSchedule;
subAccountId?: string;
type?: string;
}
interface ReportCompatibleFields {
dimensionFilters?: Dfareporting.Schema.Dimension[];
dimensions?: Dfareporting.Schema.Dimension[];
kind?: string;
metrics?: Dfareporting.Schema.Metric[];
pivotedActivityMetrics?: Dfareporting.Schema.Metric[];
}
interface ReportCriteria {
activities?: Dfareporting.Schema.Activities;
customRichMediaEvents?: Dfareporting.Schema.CustomRichMediaEvents;
dateRange?: Dfareporting.Schema.DateRange;
dimensionFilters?: Dfareporting.Schema.DimensionValue[];
dimensions?: Dfareporting.Schema.SortedDimension[];
metricNames?: string[];
}
interface ReportCrossDimensionReachCriteria {
breakdown?: Dfareporting.Schema.SortedDimension[];
dateRange?: Dfareporting.Schema.DateRange;
dimension?: string;
dimensionFilters?: Dfareporting.Schema.DimensionValue[];
metricNames?: string[];
overlapMetricNames?: string[];
pivoted?: boolean;
}
interface ReportDelivery {
emailOwner?: boolean;
emailOwnerDeliveryType?: string;
message?: string;
recipients?: Dfareporting.Schema.Recipient[];
}
interface ReportFloodlightCriteria {
customRichMediaEvents?: Dfareporting.Schema.DimensionValue[];
dateRange?: Dfareporting.Schema.DateRange;
dimensionFilters?: Dfareporting.Schema.DimensionValue[];
dimensions?: Dfareporting.Schema.SortedDimension[];
floodlightConfigId?: Dfareporting.Schema.DimensionValue;
metricNames?: string[];
reportProperties?: Dfareporting.Schema.ReportFloodlightCriteriaReportProperties;
}
interface ReportFloodlightCriteriaReportProperties {
includeAttributedIPConversions?: boolean;
includeUnattributedCookieConversions?: boolean;
includeUnattributedIPConversions?: boolean;
}
interface ReportList {
etag?: string;
items?: Dfareporting.Schema.Report[];
kind?: string;
nextPageToken?: string;
}
interface ReportPathToConversionCriteria {
activityFilters?: Dfareporting.Schema.DimensionValue[];
conversionDimensions?: Dfareporting.Schema.SortedDimension[];
customFloodlightVariables?: Dfareporting.Schema.SortedDimension[];
customRichMediaEvents?: Dfareporting.Schema.DimensionValue[];
dateRange?: Dfareporting.Schema.DateRange;
floodlightConfigId?: Dfareporting.Schema.DimensionValue;
metricNames?: string[];
perInteractionDimensions?: Dfareporting.Schema.SortedDimension[];
reportProperties?: Dfareporting.Schema.ReportPathToConversionCriteriaReportProperties;
}
interface ReportPathToConversionCriteriaReportProperties {
clicksLookbackWindow?: number;
impressionsLookbackWindow?: number;
includeAttributedIPConversions?: boolean;
includeUnattributedCookieConversions?: boolean;
includeUnattributedIPConversions?: boolean;
maximumClickInteractions?: number;
maximumImpressionInteractions?: number;
maximumInteractionGap?: number;
pivotOnInteractionPath?: boolean;
}
interface ReportReachCriteria {
activities?: Dfareporting.Schema.Activities;
customRichMediaEvents?: Dfareporting.Schema.CustomRichMediaEvents;
dateRange?: Dfareporting.Schema.DateRange;
dimensionFilters?: Dfareporting.Schema.DimensionValue[];
dimensions?: Dfareporting.Schema.SortedDimension[];
enableAllDimensionCombinations?: boolean;
metricNames?: string[];
reachByFrequencyMetricNames?: string[];
}
interface ReportSchedule {
active?: boolean;
every?: number;
expirationDate?: string;
repeats?: string;
repeatsOnWeekDays?: string[];
runsOnDayOfMonth?: string;
startDate?: string;
}
interface ReportsConfiguration {
exposureToConversionEnabled?: boolean;
lookbackConfiguration?: Dfareporting.Schema.LookbackConfiguration;
reportGenerationTimeZoneId?: string;
}
interface RichMediaExitOverride {
clickThroughUrl?: Dfareporting.Schema.ClickThroughUrl;
enabled?: boolean;
exitId?: string;
}
interface Rule {
assetId?: string;
name?: string;
targetingTemplateId?: string;
}
interface Site {
accountId?: string;
approved?: boolean;
directorySiteId?: string;
directorySiteIdDimensionValue?: Dfareporting.Schema.DimensionValue;
id?: string;
idDimensionValue?: Dfareporting.Schema.DimensionValue;
keyName?: string;
kind?: string;
name?: string;
siteContacts?: Dfareporting.Schema.SiteContact[];
siteSettings?: Dfareporting.Schema.SiteSettings;
subaccountId?: string;
videoSettings?: Dfareporting.Schema.SiteVideoSettings;
}
interface SiteCompanionSetting {
companionsDisabled?: boolean;
enabledSizes?: Dfareporting.Schema.Size[];
imageOnly?: boolean;
kind?: string;
}
interface SiteContact {
address?: string;
contactType?: string;
email?: string;
firstName?: string;
id?: string;
lastName?: string;
phone?: string;
title?: string;
}
interface SiteSettings {
activeViewOptOut?: boolean;
adBlockingOptOut?: boolean;
disableNewCookie?: boolean;
tagSetting?: Dfareporting.Schema.TagSetting;
videoActiveViewOptOutTemplate?: boolean;
vpaidAdapterChoiceTemplate?: string;
}
interface SiteSkippableSetting {
kind?: string;
progressOffset?: Dfareporting.Schema.VideoOffset;
skipOffset?: Dfareporting.Schema.VideoOffset;
skippable?: boolean;
}
interface SiteTranscodeSetting {
enabledVideoFormats?: number[];
kind?: string;
}
interface SiteVideoSettings {
companionSettings?: Dfareporting.Schema.SiteCompanionSetting;
kind?: string;
orientation?: string;
skippableSettings?: Dfareporting.Schema.SiteSkippableSetting;
transcodeSettings?: Dfareporting.Schema.SiteTranscodeSetting;
}
interface SitesListResponse {
kind?: string;
nextPageToken?: string;
sites?: Dfareporting.Schema.Site[];
}
interface Size {
height?: number;
iab?: boolean;
id?: string;
kind?: string;
width?: number;
}
interface SizesListResponse {
kind?: string;
sizes?: Dfareporting.Schema.Size[];
}
interface SkippableSetting {
kind?: string;
progressOffset?: Dfareporting.Schema.VideoOffset;
skipOffset?: Dfareporting.Schema.VideoOffset;
skippable?: boolean;
}
interface SortedDimension {
kind?: string;
name?: string;
sortOrder?: string;
}
interface Subaccount {
accountId?: string;
availablePermissionIds?: string[];
id?: string;
kind?: string;
name?: string;
}
interface SubaccountsListResponse {
kind?: string;
nextPageToken?: string;
subaccounts?: Dfareporting.Schema.Subaccount[];
}
interface TagData {
adId?: string;
clickTag?: string;
creativeId?: string;
format?: string;
impressionTag?: string;
}
interface TagSetting {
additionalKeyValues?: string;
includeClickThroughUrls?: boolean;
includeClickTracking?: boolean;
keywordOption?: string;
}
interface TagSettings {
dynamicTagEnabled?: boolean;
imageTagEnabled?: boolean;
}
interface TargetWindow {
customHtml?: string;
targetWindowOption?: string;
}
interface TargetableRemarketingList {
accountId?: string;
active?: boolean;
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
description?: string;
id?: string;
kind?: string;
lifeSpan?: string;
listSize?: string;
listSource?: string;
name?: string;
subaccountId?: string;
}
interface TargetableRemarketingListsListResponse {
kind?: string;
nextPageToken?: string;
targetableRemarketingLists?: Dfareporting.Schema.TargetableRemarketingList[];
}
interface TargetingTemplate {
accountId?: string;
advertiserId?: string;
advertiserIdDimensionValue?: Dfareporting.Schema.DimensionValue;
dayPartTargeting?: Dfareporting.Schema.DayPartTargeting;
geoTargeting?: Dfareporting.Schema.GeoTargeting;
id?: string;
keyValueTargetingExpression?: Dfareporting.Schema.KeyValueTargetingExpression;
kind?: string;
languageTargeting?: Dfareporting.Schema.LanguageTargeting;
listTargetingExpression?: Dfareporting.Schema.ListTargetingExpression;
name?: string;
subaccountId?: string;
technologyTargeting?: Dfareporting.Schema.TechnologyTargeting;
}
interface TargetingTemplatesListResponse {
kind?: string;
nextPageToken?: string;
targetingTemplates?: Dfareporting.Schema.TargetingTemplate[];
}
interface TechnologyTargeting {
browsers?: Dfareporting.Schema.Browser[];
connectionTypes?: Dfareporting.Schema.ConnectionType[];
mobileCarriers?: Dfareporting.Schema.MobileCarrier[];
operatingSystemVersions?: Dfareporting.Schema.OperatingSystemVersion[];
operatingSystems?: Dfareporting.Schema.OperatingSystem[];
platformTypes?: Dfareporting.Schema.PlatformType[];
}
interface ThirdPartyAuthenticationToken {
name?: string;
value?: string;
}
interface ThirdPartyTrackingUrl {
thirdPartyUrlType?: string;
url?: string;
}
interface TranscodeSetting {
enabledVideoFormats?: number[];
kind?: string;
}
interface UniversalAdId {
registry?: string;
value?: string;
}
interface UserDefinedVariableConfiguration {
dataType?: string;
reportName?: string;
variableType?: string;
}
interface UserProfile {
accountId?: string;
accountName?: string;
etag?: string;
kind?: string;
profileId?: string;
subAccountId?: string;
subAccountName?: string;
userName?: string;
}
interface UserProfileList {
etag?: string;
items?: Dfareporting.Schema.UserProfile[];
kind?: string;
}
interface UserRole {
accountId?: string;
defaultUserRole?: boolean;
id?: string;
kind?: string;
name?: string;
parentUserRoleId?: string;
permissions?: Dfareporting.Schema.UserRolePermission[];
subaccountId?: string;
}
interface UserRolePermission {
availability?: string;
id?: string;
kind?: string;
name?: string;
permissionGroupId?: string;
}
interface UserRolePermissionGroup {
id?: string;
kind?: string;
name?: string;
}
interface UserRolePermissionGroupsListResponse {
kind?: string;
userRolePermissionGroups?: Dfareporting.Schema.UserRolePermissionGroup[];
}
interface UserRolePermissionsListResponse {
kind?: string;
userRolePermissions?: Dfareporting.Schema.UserRolePermission[];
}
interface UserRolesListResponse {
kind?: string;
nextPageToken?: string;
userRoles?: Dfareporting.Schema.UserRole[];
}
interface VideoFormat {
fileType?: string;
id?: number;
kind?: string;
resolution?: Dfareporting.Schema.Size;
targetBitRate?: number;
}
interface VideoFormatsListResponse {
kind?: string;
videoFormats?: Dfareporting.Schema.VideoFormat[];
}
interface VideoOffset {
offsetPercentage?: number;
offsetSeconds?: number;
}
interface VideoSettings {
companionSettings?: Dfareporting.Schema.CompanionSetting;
kind?: string;
orientation?: string;
skippableSettings?: Dfareporting.Schema.SkippableSetting;
transcodeSettings?: Dfareporting.Schema.TranscodeSetting;
}
}
}
interface Dfareporting {
AccountActiveAdSummaries?: Dfareporting.Collection.AccountActiveAdSummariesCollection;
AccountPermissionGroups?: Dfareporting.Collection.AccountPermissionGroupsCollection;
AccountPermissions?: Dfareporting.Collection.AccountPermissionsCollection;
AccountUserProfiles?: Dfareporting.Collection.AccountUserProfilesCollection;
Accounts?: Dfareporting.Collection.AccountsCollection;
Ads?: Dfareporting.Collection.AdsCollection;
AdvertiserGroups?: Dfareporting.Collection.AdvertiserGroupsCollection;
AdvertiserLandingPages?: Dfareporting.Collection.AdvertiserLandingPagesCollection;
Advertisers?: Dfareporting.Collection.AdvertisersCollection;
Browsers?: Dfareporting.Collection.BrowsersCollection;
CampaignCreativeAssociations?: Dfareporting.Collection.CampaignCreativeAssociationsCollection;
Campaigns?: Dfareporting.Collection.CampaignsCollection;
ChangeLogs?: Dfareporting.Collection.ChangeLogsCollection;
Cities?: Dfareporting.Collection.CitiesCollection;
ConnectionTypes?: Dfareporting.Collection.ConnectionTypesCollection;
ContentCategories?: Dfareporting.Collection.ContentCategoriesCollection;
Conversions?: Dfareporting.Collection.ConversionsCollection;
Countries?: Dfareporting.Collection.CountriesCollection;
CreativeAssets?: Dfareporting.Collection.CreativeAssetsCollection;
CreativeFieldValues?: Dfareporting.Collection.CreativeFieldValuesCollection;
CreativeFields?: Dfareporting.Collection.CreativeFieldsCollection;
CreativeGroups?: Dfareporting.Collection.CreativeGroupsCollection;
Creatives?: Dfareporting.Collection.CreativesCollection;
DimensionValues?: Dfareporting.Collection.DimensionValuesCollection;
DirectorySites?: Dfareporting.Collection.DirectorySitesCollection;
DynamicTargetingKeys?: Dfareporting.Collection.DynamicTargetingKeysCollection;
EventTags?: Dfareporting.Collection.EventTagsCollection;
Files?: Dfareporting.Collection.FilesCollection;
FloodlightActivities?: Dfareporting.Collection.FloodlightActivitiesCollection;
FloodlightActivityGroups?: Dfareporting.Collection.FloodlightActivityGroupsCollection;
FloodlightConfigurations?: Dfareporting.Collection.FloodlightConfigurationsCollection;
InventoryItems?: Dfareporting.Collection.InventoryItemsCollection;
Languages?: Dfareporting.Collection.LanguagesCollection;
Metros?: Dfareporting.Collection.MetrosCollection;
MobileApps?: Dfareporting.Collection.MobileAppsCollection;
MobileCarriers?: Dfareporting.Collection.MobileCarriersCollection;
OperatingSystemVersions?: Dfareporting.Collection.OperatingSystemVersionsCollection;
OperatingSystems?: Dfareporting.Collection.OperatingSystemsCollection;
OrderDocuments?: Dfareporting.Collection.OrderDocumentsCollection;
Orders?: Dfareporting.Collection.OrdersCollection;
PlacementGroups?: Dfareporting.Collection.PlacementGroupsCollection;
PlacementStrategies?: Dfareporting.Collection.PlacementStrategiesCollection;
Placements?: Dfareporting.Collection.PlacementsCollection;
PlatformTypes?: Dfareporting.Collection.PlatformTypesCollection;
PostalCodes?: Dfareporting.Collection.PostalCodesCollection;
Projects?: Dfareporting.Collection.ProjectsCollection;
Regions?: Dfareporting.Collection.RegionsCollection;
RemarketingListShares?: Dfareporting.Collection.RemarketingListSharesCollection;
RemarketingLists?: Dfareporting.Collection.RemarketingListsCollection;
Reports?: Dfareporting.Collection.ReportsCollection;
Sites?: Dfareporting.Collection.SitesCollection;
Sizes?: Dfareporting.Collection.SizesCollection;
Subaccounts?: Dfareporting.Collection.SubaccountsCollection;
TargetableRemarketingLists?: Dfareporting.Collection.TargetableRemarketingListsCollection;
TargetingTemplates?: Dfareporting.Collection.TargetingTemplatesCollection;
UserProfiles?: Dfareporting.Collection.UserProfilesCollection;
UserRolePermissionGroups?: Dfareporting.Collection.UserRolePermissionGroupsCollection;
UserRolePermissions?: Dfareporting.Collection.UserRolePermissionsCollection;
UserRoles?: Dfareporting.Collection.UserRolesCollection;
VideoFormats?: Dfareporting.Collection.VideoFormatsCollection;
// Create a new instance of Account
newAccount(): Dfareporting.Schema.Account;
// Create a new instance of AccountUserProfile
newAccountUserProfile(): Dfareporting.Schema.AccountUserProfile;
// Create a new instance of Activities
newActivities(): Dfareporting.Schema.Activities;
// Create a new instance of Ad
newAd(): Dfareporting.Schema.Ad;
// Create a new instance of AdBlockingConfiguration
newAdBlockingConfiguration(): Dfareporting.Schema.AdBlockingConfiguration;
// Create a new instance of Advertiser
newAdvertiser(): Dfareporting.Schema.Advertiser;
// Create a new instance of AdvertiserGroup
newAdvertiserGroup(): Dfareporting.Schema.AdvertiserGroup;
// Create a new instance of AudienceSegment
newAudienceSegment(): Dfareporting.Schema.AudienceSegment;
// Create a new instance of AudienceSegmentGroup
newAudienceSegmentGroup(): Dfareporting.Schema.AudienceSegmentGroup;
// Create a new instance of Browser
newBrowser(): Dfareporting.Schema.Browser;
// Create a new instance of Campaign
newCampaign(): Dfareporting.Schema.Campaign;
// Create a new instance of CampaignCreativeAssociation
newCampaignCreativeAssociation(): Dfareporting.Schema.CampaignCreativeAssociation;
// Create a new instance of City
newCity(): Dfareporting.Schema.City;
// Create a new instance of ClickTag
newClickTag(): Dfareporting.Schema.ClickTag;
// Create a new instance of ClickThroughUrl
newClickThroughUrl(): Dfareporting.Schema.ClickThroughUrl;
// Create a new instance of ClickThroughUrlSuffixProperties
newClickThroughUrlSuffixProperties(): Dfareporting.Schema.ClickThroughUrlSuffixProperties;
// Create a new instance of CompanionClickThroughOverride
newCompanionClickThroughOverride(): Dfareporting.Schema.CompanionClickThroughOverride;
// Create a new instance of CompanionSetting
newCompanionSetting(): Dfareporting.Schema.CompanionSetting;
// Create a new instance of ConnectionType
newConnectionType(): Dfareporting.Schema.ConnectionType;
// Create a new instance of ContentCategory
newContentCategory(): Dfareporting.Schema.ContentCategory;
// Create a new instance of Conversion
newConversion(): Dfareporting.Schema.Conversion;
// Create a new instance of ConversionsBatchInsertRequest
newConversionsBatchInsertRequest(): Dfareporting.Schema.ConversionsBatchInsertRequest;
// Create a new instance of ConversionsBatchUpdateRequest
newConversionsBatchUpdateRequest(): Dfareporting.Schema.ConversionsBatchUpdateRequest;
// Create a new instance of Country
newCountry(): Dfareporting.Schema.Country;
// Create a new instance of Creative
newCreative(): Dfareporting.Schema.Creative;
// Create a new instance of CreativeAsset
newCreativeAsset(): Dfareporting.Schema.CreativeAsset;
// Create a new instance of CreativeAssetId
newCreativeAssetId(): Dfareporting.Schema.CreativeAssetId;
// Create a new instance of CreativeAssetMetadata
newCreativeAssetMetadata(): Dfareporting.Schema.CreativeAssetMetadata;
// Create a new instance of CreativeAssetSelection
newCreativeAssetSelection(): Dfareporting.Schema.CreativeAssetSelection;
// Create a new instance of CreativeAssignment
newCreativeAssignment(): Dfareporting.Schema.CreativeAssignment;
// Create a new instance of CreativeClickThroughUrl
newCreativeClickThroughUrl(): Dfareporting.Schema.CreativeClickThroughUrl;
// Create a new instance of CreativeCustomEvent
newCreativeCustomEvent(): Dfareporting.Schema.CreativeCustomEvent;
// Create a new instance of CreativeField
newCreativeField(): Dfareporting.Schema.CreativeField;
// Create a new instance of CreativeFieldAssignment
newCreativeFieldAssignment(): Dfareporting.Schema.CreativeFieldAssignment;
// Create a new instance of CreativeFieldValue
newCreativeFieldValue(): Dfareporting.Schema.CreativeFieldValue;
// Create a new instance of CreativeGroup
newCreativeGroup(): Dfareporting.Schema.CreativeGroup;
// Create a new instance of CreativeGroupAssignment
newCreativeGroupAssignment(): Dfareporting.Schema.CreativeGroupAssignment;
// Create a new instance of CreativeOptimizationConfiguration
newCreativeOptimizationConfiguration(): Dfareporting.Schema.CreativeOptimizationConfiguration;
// Create a new instance of CreativeRotation
newCreativeRotation(): Dfareporting.Schema.CreativeRotation;
// Create a new instance of CustomFloodlightVariable
newCustomFloodlightVariable(): Dfareporting.Schema.CustomFloodlightVariable;
// Create a new instance of CustomRichMediaEvents
newCustomRichMediaEvents(): Dfareporting.Schema.CustomRichMediaEvents;
// Create a new instance of CustomViewabilityMetric
newCustomViewabilityMetric(): Dfareporting.Schema.CustomViewabilityMetric;
// Create a new instance of CustomViewabilityMetricConfiguration
newCustomViewabilityMetricConfiguration(): Dfareporting.Schema.CustomViewabilityMetricConfiguration;
// Create a new instance of DateRange
newDateRange(): Dfareporting.Schema.DateRange;
// Create a new instance of DayPartTargeting
newDayPartTargeting(): Dfareporting.Schema.DayPartTargeting;
// Create a new instance of DeepLink
newDeepLink(): Dfareporting.Schema.DeepLink;
// Create a new instance of DefaultClickThroughEventTagProperties
newDefaultClickThroughEventTagProperties(): Dfareporting.Schema.DefaultClickThroughEventTagProperties;
// Create a new instance of DeliverySchedule
newDeliverySchedule(): Dfareporting.Schema.DeliverySchedule;
// Create a new instance of DfpSettings
newDfpSettings(): Dfareporting.Schema.DfpSettings;
// Create a new instance of DimensionFilter
newDimensionFilter(): Dfareporting.Schema.DimensionFilter;
// Create a new instance of DimensionValue
newDimensionValue(): Dfareporting.Schema.DimensionValue;
// Create a new instance of DimensionValueRequest
newDimensionValueRequest(): Dfareporting.Schema.DimensionValueRequest;
// Create a new instance of DirectorySite
newDirectorySite(): Dfareporting.Schema.DirectorySite;
// Create a new instance of DirectorySiteSettings
newDirectorySiteSettings(): Dfareporting.Schema.DirectorySiteSettings;
// Create a new instance of DynamicTargetingKey
newDynamicTargetingKey(): Dfareporting.Schema.DynamicTargetingKey;
// Create a new instance of EncryptionInfo
newEncryptionInfo(): Dfareporting.Schema.EncryptionInfo;
// Create a new instance of EventTag
newEventTag(): Dfareporting.Schema.EventTag;
// Create a new instance of EventTagOverride
newEventTagOverride(): Dfareporting.Schema.EventTagOverride;
// Create a new instance of FloodlightActivity
newFloodlightActivity(): Dfareporting.Schema.FloodlightActivity;
// Create a new instance of FloodlightActivityDynamicTag
newFloodlightActivityDynamicTag(): Dfareporting.Schema.FloodlightActivityDynamicTag;
// Create a new instance of FloodlightActivityGroup
newFloodlightActivityGroup(): Dfareporting.Schema.FloodlightActivityGroup;
// Create a new instance of FloodlightActivityPublisherDynamicTag
newFloodlightActivityPublisherDynamicTag(): Dfareporting.Schema.FloodlightActivityPublisherDynamicTag;
// Create a new instance of FloodlightConfiguration
newFloodlightConfiguration(): Dfareporting.Schema.FloodlightConfiguration;
// Create a new instance of FrequencyCap
newFrequencyCap(): Dfareporting.Schema.FrequencyCap;
// Create a new instance of FsCommand
newFsCommand(): Dfareporting.Schema.FsCommand;
// Create a new instance of GeoTargeting
newGeoTargeting(): Dfareporting.Schema.GeoTargeting;
// Create a new instance of KeyValueTargetingExpression
newKeyValueTargetingExpression(): Dfareporting.Schema.KeyValueTargetingExpression;
// Create a new instance of LandingPage
newLandingPage(): Dfareporting.Schema.LandingPage;
// Create a new instance of Language
newLanguage(): Dfareporting.Schema.Language;
// Create a new instance of LanguageTargeting
newLanguageTargeting(): Dfareporting.Schema.LanguageTargeting;
// Create a new instance of LastModifiedInfo
newLastModifiedInfo(): Dfareporting.Schema.LastModifiedInfo;
// Create a new instance of ListPopulationClause
newListPopulationClause(): Dfareporting.Schema.ListPopulationClause;
// Create a new instance of ListPopulationRule
newListPopulationRule(): Dfareporting.Schema.ListPopulationRule;
// Create a new instance of ListPopulationTerm
newListPopulationTerm(): Dfareporting.Schema.ListPopulationTerm;
// Create a new instance of ListTargetingExpression
newListTargetingExpression(): Dfareporting.Schema.ListTargetingExpression;
// Create a new instance of LookbackConfiguration
newLookbackConfiguration(): Dfareporting.Schema.LookbackConfiguration;
// Create a new instance of Metro
newMetro(): Dfareporting.Schema.Metro;
// Create a new instance of MobileApp
newMobileApp(): Dfareporting.Schema.MobileApp;
// Create a new instance of MobileCarrier
newMobileCarrier(): Dfareporting.Schema.MobileCarrier;
// Create a new instance of ObjectFilter
newObjectFilter(): Dfareporting.Schema.ObjectFilter;
// Create a new instance of OffsetPosition
newOffsetPosition(): Dfareporting.Schema.OffsetPosition;
// Create a new instance of OmnitureSettings
newOmnitureSettings(): Dfareporting.Schema.OmnitureSettings;
// Create a new instance of OperatingSystem
newOperatingSystem(): Dfareporting.Schema.OperatingSystem;
// Create a new instance of OperatingSystemVersion
newOperatingSystemVersion(): Dfareporting.Schema.OperatingSystemVersion;
// Create a new instance of OptimizationActivity
newOptimizationActivity(): Dfareporting.Schema.OptimizationActivity;
// Create a new instance of Placement
newPlacement(): Dfareporting.Schema.Placement;
// Create a new instance of PlacementAssignment
newPlacementAssignment(): Dfareporting.Schema.PlacementAssignment;
// Create a new instance of PlacementGroup
newPlacementGroup(): Dfareporting.Schema.PlacementGroup;
// Create a new instance of PlacementStrategy
newPlacementStrategy(): Dfareporting.Schema.PlacementStrategy;
// Create a new instance of PlatformType
newPlatformType(): Dfareporting.Schema.PlatformType;
// Create a new instance of PopupWindowProperties
newPopupWindowProperties(): Dfareporting.Schema.PopupWindowProperties;
// Create a new instance of PostalCode
newPostalCode(): Dfareporting.Schema.PostalCode;
// Create a new instance of PricingSchedule
newPricingSchedule(): Dfareporting.Schema.PricingSchedule;
// Create a new instance of PricingSchedulePricingPeriod
newPricingSchedulePricingPeriod(): Dfareporting.Schema.PricingSchedulePricingPeriod;
// Create a new instance of Recipient
newRecipient(): Dfareporting.Schema.Recipient;
// Create a new instance of Region
newRegion(): Dfareporting.Schema.Region;
// Create a new instance of RemarketingList
newRemarketingList(): Dfareporting.Schema.RemarketingList;
// Create a new instance of RemarketingListShare
newRemarketingListShare(): Dfareporting.Schema.RemarketingListShare;
// Create a new instance of Report
newReport(): Dfareporting.Schema.Report;
// Create a new instance of ReportCriteria
newReportCriteria(): Dfareporting.Schema.ReportCriteria;
// Create a new instance of ReportCrossDimensionReachCriteria
newReportCrossDimensionReachCriteria(): Dfareporting.Schema.ReportCrossDimensionReachCriteria;
// Create a new instance of ReportDelivery
newReportDelivery(): Dfareporting.Schema.ReportDelivery;
// Create a new instance of ReportFloodlightCriteria
newReportFloodlightCriteria(): Dfareporting.Schema.ReportFloodlightCriteria;
// Create a new instance of ReportFloodlightCriteriaReportProperties
newReportFloodlightCriteriaReportProperties(): Dfareporting.Schema.ReportFloodlightCriteriaReportProperties;
// Create a new instance of ReportPathToConversionCriteria
newReportPathToConversionCriteria(): Dfareporting.Schema.ReportPathToConversionCriteria;
// Create a new instance of ReportPathToConversionCriteriaReportProperties
newReportPathToConversionCriteriaReportProperties(): Dfareporting.Schema.ReportPathToConversionCriteriaReportProperties;
// Create a new instance of ReportReachCriteria
newReportReachCriteria(): Dfareporting.Schema.ReportReachCriteria;
// Create a new instance of ReportSchedule
newReportSchedule(): Dfareporting.Schema.ReportSchedule;
// Create a new instance of ReportsConfiguration
newReportsConfiguration(): Dfareporting.Schema.ReportsConfiguration;
// Create a new instance of RichMediaExitOverride
newRichMediaExitOverride(): Dfareporting.Schema.RichMediaExitOverride;
// Create a new instance of Rule
newRule(): Dfareporting.Schema.Rule;
// Create a new instance of Site
newSite(): Dfareporting.Schema.Site;
// Create a new instance of SiteCompanionSetting
newSiteCompanionSetting(): Dfareporting.Schema.SiteCompanionSetting;
// Create a new instance of SiteContact
newSiteContact(): Dfareporting.Schema.SiteContact;
// Create a new instance of SiteSettings
newSiteSettings(): Dfareporting.Schema.SiteSettings;
// Create a new instance of SiteSkippableSetting
newSiteSkippableSetting(): Dfareporting.Schema.SiteSkippableSetting;
// Create a new instance of SiteTranscodeSetting
newSiteTranscodeSetting(): Dfareporting.Schema.SiteTranscodeSetting;
// Create a new instance of SiteVideoSettings
newSiteVideoSettings(): Dfareporting.Schema.SiteVideoSettings;
// Create a new instance of Size
newSize(): Dfareporting.Schema.Size;
// Create a new instance of SkippableSetting
newSkippableSetting(): Dfareporting.Schema.SkippableSetting;
// Create a new instance of SortedDimension
newSortedDimension(): Dfareporting.Schema.SortedDimension;
// Create a new instance of Subaccount
newSubaccount(): Dfareporting.Schema.Subaccount;
// Create a new instance of TagSetting
newTagSetting(): Dfareporting.Schema.TagSetting;
// Create a new instance of TagSettings
newTagSettings(): Dfareporting.Schema.TagSettings;
// Create a new instance of TargetWindow
newTargetWindow(): Dfareporting.Schema.TargetWindow;
// Create a new instance of TargetingTemplate
newTargetingTemplate(): Dfareporting.Schema.TargetingTemplate;
// Create a new instance of TechnologyTargeting
newTechnologyTargeting(): Dfareporting.Schema.TechnologyTargeting;
// Create a new instance of ThirdPartyAuthenticationToken
newThirdPartyAuthenticationToken(): Dfareporting.Schema.ThirdPartyAuthenticationToken;
// Create a new instance of ThirdPartyTrackingUrl
newThirdPartyTrackingUrl(): Dfareporting.Schema.ThirdPartyTrackingUrl;
// Create a new instance of TranscodeSetting
newTranscodeSetting(): Dfareporting.Schema.TranscodeSetting;
// Create a new instance of UniversalAdId
newUniversalAdId(): Dfareporting.Schema.UniversalAdId;
// Create a new instance of UserDefinedVariableConfiguration
newUserDefinedVariableConfiguration(): Dfareporting.Schema.UserDefinedVariableConfiguration;
// Create a new instance of UserRole
newUserRole(): Dfareporting.Schema.UserRole;
// Create a new instance of UserRolePermission
newUserRolePermission(): Dfareporting.Schema.UserRolePermission;
// Create a new instance of VideoOffset
newVideoOffset(): Dfareporting.Schema.VideoOffset;
// Create a new instance of VideoSettings
newVideoSettings(): Dfareporting.Schema.VideoSettings;
}
}
declare var Dfareporting: GoogleAppsScript.Dfareporting; | the_stack |
import { ServerRuntime, SnowpackDevServer, startServer } from "snowpack";
import arg from "arg";
import { join, resolve, extname } from "path";
import type { IncomingMessage, ServerResponse } from "http";
import { green, dim } from "kleur/colors";
import polka from "polka";
import { openInBrowser } from "../utils/open.js";
import { readDir } from "../utils/fs.js";
import { promises as fsp } from "fs";
import { ErrorProps } from "error.js";
import { loadConfiguration } from "../utils/command.js";
import { h, FunctionalComponent } from "preact";
import {
generateStaticPropsContext,
normalizePathName,
} from "../utils/router.js";
const noop = () => Promise.resolve();
let devServer: SnowpackDevServer;
let runtime: ServerRuntime;
let renderToString: any;
let csrSrc: string;
let Document: any;
let __HeadContext: any;
let __InternalDocContext: any;
let ErrorPage: any;
let errorSrc: string;
const loadErrorPage = async () => {
if (!ErrorPage) {
try {
const {
exports: { default: UserErrorPage },
} = await runtime.importModule("/src/pages/_error.js");
ErrorPage = UserErrorPage;
errorSrc = "/src/pages/_error.js";
} catch (e) {
errorSrc = await devServer.getUrlForPackage("microsite/error");
const {
exports: { default: InternalErrorPage },
} = await runtime.importModule(errorSrc);
ErrorPage = InternalErrorPage;
}
}
return [ErrorPage, errorSrc];
};
const renderPage = async (
componentPath: string,
absoluteUrl: string,
initialProps?: any
) => {
if (!renderToString) {
const preactRenderToStringSrc = await devServer.getUrlForPackage(
"preact-render-to-string"
);
renderToString = await runtime
.importModule(preactRenderToStringSrc)
.then(({ exports: { default: mod } }) => mod);
}
if (!Document) {
const [documentSrc, csrUrl] = await Promise.all([
devServer.getUrlForPackage("microsite/document"),
devServer.getUrlForPackage("microsite/client/csr"),
]);
csrSrc = csrUrl;
const {
exports: {
Document: InternalDocument,
__HeadContext: __Head,
__InternalDocContext: __Doc,
},
} = await runtime.importModule(documentSrc);
__HeadContext = __Head;
__InternalDocContext = __Doc;
try {
const {
exports: { default: UserDocument },
} = await runtime.importModule("/src/pages/_document.js");
Document = UserDocument;
} catch (e) {
Document = InternalDocument;
}
}
try {
let pathname = componentPath.replace("/src/pages/", "");
let Component = null;
let getStaticProps: any = noop;
let getStaticPaths: any = noop;
let pageProps = initialProps ?? {};
let paths = [];
try {
let {
exports: { default: Page },
} = await runtime.importModule(componentPath);
if (typeof Page === "function") Component = Page;
if (Page.Component) {
Component = Page.Component;
getStaticProps = Page.getStaticProps ?? noop;
getStaticPaths = Page.getStaticPaths ?? noop;
}
} catch (e) {
const [Page, errorSrc] = await loadErrorPage();
Component = ErrorPage;
pageProps = initialProps?.statusCode ? initialProps : { statusCode: 404 };
componentPath = errorSrc;
pathname = "/_error";
if (typeof Page === "function") Component = Page;
if (Page.Component) {
Component = Page.Component;
getStaticProps = Page.getStaticProps ?? noop;
getStaticPaths = Page.getStaticPaths ?? noop;
}
}
paths = await getStaticPaths({}).then((res) => res && res.paths);
paths =
paths &&
paths.map((pathOrParams) =>
generateStaticPropsContext(pathname, pathOrParams)
);
const match =
paths &&
paths.find(
(ctx) =>
ctx.path === pathname ||
ctx.path === `${pathname}/index` ||
ctx.path === normalizePathName(absoluteUrl)
);
if (paths && !match) {
const [ErrorPage, errorSrc] = await loadErrorPage();
Component = ErrorPage;
pageProps = { statusCode: 404 };
componentPath = errorSrc;
} else {
let ctx = paths ? match : generateStaticPropsContext(pathname, pathname);
pageProps = await getStaticProps(ctx).then((res) => res && res.props);
if (!pageProps) pageProps = initialProps;
}
const headContext = {
head: {
current: [],
},
};
const HeadProvider: FunctionalComponent = ({ children }) => {
return <__HeadContext.Provider value={headContext} {...{ children }} />;
};
const { __renderPageResult, ...docProps } = await Document.prepare({
renderPage: async () => ({
__renderPageResult: renderToString(
<HeadProvider>
<Component {...pageProps} />
</HeadProvider>
),
}),
});
const docContext = {
dev: componentPath,
devProps: pageProps ?? {},
__csrUrl: csrSrc,
__renderPageHead: headContext.head.current,
__renderPageResult,
};
let contents = renderToString(
<__InternalDocContext.Provider
value={docContext}
children={<Document {...(docProps as any)} />}
/>
);
return `<!DOCTYPE html>\n<!-- Generated by microsite -->\n${contents}`;
} catch (e) {
console.error(e);
return;
}
};
const EXTS = [".js", ".jsx", ".ts", ".tsx", ".mjs"];
function parseArgs(argv: string[]) {
return arg(
{
"--port": Number,
"--no-open": Boolean,
// Aliases
"-p": "--port",
},
{ permissive: true, argv }
);
}
export default async function dev(
argvOrParsedArgs: string[] | ReturnType<typeof parseArgs>
) {
const cwd = process.cwd();
const args = Array.isArray(argvOrParsedArgs)
? parseArgs(argvOrParsedArgs)
: argvOrParsedArgs;
let PORT = args["--port"] ?? 8888;
const config = await loadConfiguration("dev");
const snowpack = await startServer({
config,
lockfile: null,
});
devServer = snowpack;
runtime = snowpack.getServerRuntime();
snowpack.onFileChange(({ filePath }) => {
const url = snowpack.getUrlForFile(filePath);
if (url === "/src/pages/_document.js") {
Document = null;
}
if (url === "/src/pages/_error.js") {
ErrorPage = null;
}
});
const sendErr = async (res: ServerResponse, props?: ErrorProps) => {
// Calling `renderPage` with a component and path that do not exist
// triggers rendering of an error page.
const contents = await renderPage(`/_error`, `/_error`, props);
res.writeHead(props?.statusCode ?? 500, {
"Content-Type": "text/html",
});
res.end(contents);
};
const server = polka()
.use(async (req: IncomingMessage, res: ServerResponse, next: any) => {
if (req.url?.endsWith(".js")) {
res.setHeader("Content-Type", "application/javascript");
}
next();
})
.use(async (req: IncomingMessage, res: ServerResponse, next: any) => {
if (req.url === "/") return next();
const clean = /(\.html|index\.html|index|\/)$/;
if (clean.test(req.url ?? "")) {
res.writeHead(302, {
Location: req.url?.replace(clean, ""),
});
res.end();
}
next();
})
.use(async (req: IncomingMessage, res: ServerResponse, next: any) => {
if (
req.url !== "/" &&
!(req.url.endsWith(".html") || req.url.indexOf(".") === -1)
)
return next();
let base = req.url.slice(1);
if (base.endsWith(".html")) base = base.slice(0, ".html".length * -1);
if (base === "") base = "index";
const findPageComponentPathForBaseUrl = async (
base: string
): Promise<string | null> => {
const possiblePagePaths = [base, `${base}/index`].map(
buildPageComponentPathForBaseUrl
);
for (const pagePath of possiblePagePaths) {
if (await isPageComponentPresent(pagePath)) {
return pagePath;
}
}
const dynamicBaseUrl = await findPotentialMatch(base);
if (!dynamicBaseUrl) {
return null;
}
return buildPageComponentPathForBaseUrl(dynamicBaseUrl);
};
const buildPageComponentPathForBaseUrl = (base: string): string =>
`/src/pages/${base}.js`;
const isPageComponentPresent = async (path: string): Promise<boolean> => {
try {
await snowpack.loadUrl(path, { isSSR: true });
return true;
} catch {
return false;
}
};
const findPotentialMatch = async (base: string) => {
const baseParts = [...base.split("/"), "index"];
const pages = join(cwd, "src", "pages");
let files = await readDir(pages);
files = files
.filter((file: string) => EXTS.includes(extname(file)))
.map((file: string) =>
file.slice(pages.length, extname(file).length * -1)
)
.filter((file: string) => {
if (file.indexOf("[") === -1) return false;
const parts = file.slice(1).split("/");
if (parts.length === baseParts.length - 1)
return parts.every((part, i) =>
part.indexOf("[") > -1 ? true : part === baseParts[i]
);
if (parts.length === baseParts.length)
return parts.every((part, i) =>
part.indexOf("[") > -1 ? true : part === baseParts[i]
);
if (file.indexOf("[[") > -1)
return parts.every((part, i) => {
if (part.indexOf("[[")) return i === parts.length - 1;
if (part.indexOf("[")) return true;
return part === baseParts[i];
});
});
if (files.length === 0) return null;
if (files.length === 1) return files[0].slice(1);
if (files.length > 1) {
// TODO: rank direct matches above catch-all routes
// console.log(files);
return files[0];
}
};
const pagePath = await findPageComponentPathForBaseUrl(base);
if (!pagePath) {
return next();
}
const absoluteUrl = `/${base}`;
res.setHeader("Content-Type", "text/html");
res.end(await renderPage(pagePath, absoluteUrl));
})
.use(async (req: IncomingMessage, res: ServerResponse, next: any) => {
try {
// Respond directly if asset is found
const result = await snowpack.loadUrl(req.url);
if (result.contentType)
res.setHeader("Content-Type", result.contentType);
const MIME_EXCLUDE = ["image", "font"];
if (
req.url.indexOf("/_snowpack/pkg/microsite") === -1 &&
result.contentType &&
!MIME_EXCLUDE.includes(result.contentType.split("/")[0])
) {
result.contents = result.contents
.toString()
.replace(/preact\/hooks/, "microsite/client/hooks");
}
return res.end(result.contents);
} catch (err) {}
next();
})
.use(async (req: IncomingMessage, res: ServerResponse, next: any) => {
try {
let localPath = resolve(cwd, `.${req.url}`);
const stats = await fsp.stat(localPath);
if (stats.isDirectory()) {
let contents = await readDir(localPath);
contents = contents.map((path) => path.slice(localPath.length));
res.setHeader("Content-Type", "application/json");
return res.end(JSON.stringify(contents));
}
} catch (err) {}
next();
})
.get("*", (_req: IncomingMessage, res: ServerResponse) =>
sendErr(res, { statusCode: 404 })
);
await new Promise<void>((resolve) =>
server.listen(PORT, (err) => {
if (err) throw err;
resolve();
})
);
let protocol = "http:";
let hostname = "localhost";
if (!args["--no-open"]) {
await openInBrowser(protocol, hostname, PORT, "/", "chrome");
}
console.log(
`${dim("[microsite]")} ${green("✔")} Microsite started on ${green(
`${protocol}//${hostname}:${PORT}`
)}\n`
);
} | the_stack |
import { ConseilQuery, ConseilOperator, ConseilServerInfo, ConseilSortDirection, ConseilFunction } from "../../types/conseil/QueryTypes"
import { OperationKindType } from "../../types/tezos/TezosChainTypes";
import { ContractMapDetails, ContractMapDetailsItem } from '../../types/conseil/ConseilTezosTypes';
import LogSelector from '../../utils/LoggerSelector';
import { TezosConstants } from "../../types/tezos/TezosConstants";
import { ConseilDataClient } from "../ConseilDataClient";
import { ConseilQueryBuilder } from "../ConseilQueryBuilder";
const log = LogSelector.log;
/**
* Functions for querying the Conseil backend REST API v2 for Tezos chain data.
*/
export namespace TezosConseilClient {
const BLOCKS = 'blocks';
const ACCOUNTS = 'accounts';
const OPERATION_GROUPS = 'operation_groups';
const OPERATIONS = 'operations';
const FEES = 'fees';
const PROPOSALS = 'proposals';
const BAKERS = 'bakers';
const BALLOTS = 'ballots';
/**
* Returns a record set for a specific entity of the Tezos platform. Entity list and metadata can be retrieved using ConseilMetadataClient.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param entity Entity to retrieve.
* @param query Query to submit.
*/
export async function getTezosEntityData(serverInfo: ConseilServerInfo, network: string, entity: string, query: ConseilQuery): Promise<any[]> {
return ConseilDataClient.executeEntityQuery(serverInfo, 'tezos', network, entity, query);
}
/**
* Get the head block from the Tezos platform given a network.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
*/
export async function getBlockHead(serverInfo: ConseilServerInfo, network: string): Promise<any> {
const query = ConseilQueryBuilder.setLimit(ConseilQueryBuilder.addOrdering(ConseilQueryBuilder.blankQuery(), 'level', ConseilSortDirection.DESC), 1);
const r = await getTezosEntityData(serverInfo, network, BLOCKS, query);
return r[0];
}
/**
* Get a block by hash from the Tezos platform given a network.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param hash Block hash to query for.
*/
export async function getBlock(serverInfo: ConseilServerInfo, network: string, hash: string): Promise<any> {
if (hash === 'head') { return getBlockHead(serverInfo, network); }
const query = ConseilQueryBuilder.setLimit(ConseilQueryBuilder.addPredicate(ConseilQueryBuilder.blankQuery(), 'hash', ConseilOperator.EQ, [hash], false), 1);
const r = await getTezosEntityData(serverInfo, network, BLOCKS, query);
return r[0];
}
/**
* Get a block by hash from the Tezos platform given a network.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param {number} level Block level to query for.
*/
export async function getBlockByLevel(serverInfo: ConseilServerInfo, network: string, level: number): Promise<any> {
const query = ConseilQueryBuilder.setLimit(ConseilQueryBuilder.addPredicate(ConseilQueryBuilder.blankQuery(), 'level', ConseilOperator.EQ, [level], false), 1);
const r = await getTezosEntityData(serverInfo, network, BLOCKS, query);
return r[0];
}
/**
* Get an account from the Tezos platform given a network by account id.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param accountID Account hash to query for.
*/
export async function getAccount(serverInfo: ConseilServerInfo, network: string, accountID: string): Promise<any> {
const query = ConseilQueryBuilder.setLimit(ConseilQueryBuilder.addPredicate(ConseilQueryBuilder.blankQuery(), 'account_id', ConseilOperator.EQ, [accountID], false), 1);
const r = await getTezosEntityData(serverInfo, network, ACCOUNTS, query);
return r[0];
}
/**
* Get an operation group from the Tezos platform given a network, by id.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param operationGroupID Operation group hash to query for.
*/
export async function getOperationGroup(serverInfo: ConseilServerInfo, network: string, operationGroupID: string): Promise<any> {
const query = ConseilQueryBuilder.setLimit(ConseilQueryBuilder.addPredicate(ConseilQueryBuilder.blankQuery(), 'hash', ConseilOperator.EQ, [operationGroupID], false), 1);
const r = await getTezosEntityData(serverInfo, network, OPERATION_GROUPS, query);
return r[0];
}
/**
* Get an operation from the Tezos platform given a network, by id.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param operationGroupID Operation group hash to query for.
*/
export async function getOperation(serverInfo: ConseilServerInfo, network: string, operationGroupID: string): Promise<any> {
const query = ConseilQueryBuilder.setLimit(ConseilQueryBuilder.addPredicate(ConseilQueryBuilder.blankQuery(), 'operation_group_hash', ConseilOperator.EQ, [operationGroupID], false), 1);
const r = await getTezosEntityData(serverInfo, network, OPERATIONS, query);
return r[0];
}
/**
* Request block-entity data for a given network. Rather than simply requesting a block by hash, this function allows modification of the response to contain a subset of block attributes subject to a filter on some of them.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param query Conseil JSON query. See reference.
*
* @see [Conseil Query Format Spec]{@link https://github.com/Cryptonomic/Conseil/blob/master/docs/README.md#tezos-chain-data-query}
*/
export async function getBlocks(serverInfo: ConseilServerInfo, network: string, query: ConseilQuery): Promise<any[]> {
return getTezosEntityData(serverInfo, network, BLOCKS, query);
}
/**
* Request account-entity data for a given network. Rather than simply requesting an account by hash, this function allows modification of the response to contain a subset of account attributes subject to a filter on some of them.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param query Conseil JSON query. See reference.
*
* @see [Conseil Query Format Spec]{@link https://github.com/Cryptonomic/Conseil/blob/master/docs/README.md#tezos-chain-data-query}
*/
export async function getAccounts(serverInfo: ConseilServerInfo, network: string, query: ConseilQuery): Promise<any[]> {
return getTezosEntityData(serverInfo, network, ACCOUNTS, query)
}
/**
* Request operation group-entity data for a given network. Rather than simply requesting an operation group by hash, this function allows modification of the response to contain a subset of operation group attributes subject to a filter on some of them.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param query Conseil JSON query. See reference.
*
* @see [Conseil Query Format Spec]{@link https://github.com/Cryptonomic/Conseil/blob/master/docs/README.md#tezos-chain-data-query}
*/
export async function getOperationGroups(serverInfo: ConseilServerInfo, network: string, query: ConseilQuery): Promise<any[]> {
return getTezosEntityData(serverInfo, network, OPERATION_GROUPS, query)
}
/**
* Request operation-entity data for a given network. This function allows modification of the response to contain a subset of operation attributes subject to a filter on some of them.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param query Conseil JSON query. See reference.
*
* @see [Conseil Query Format Spec]{@link https://github.com/Cryptonomic/Conseil/blob/master/docs/README.md#tezos-chain-data-query}
*/
export async function getOperations(serverInfo: ConseilServerInfo, network: string, query: ConseilQuery): Promise<any[]> {
return getTezosEntityData(serverInfo, network, OPERATIONS, query);
}
/**
* Request pre-computed fee statistics for operation fees by operation kind. The query returns the latest record.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param operationType Tezos operation kind
*/
export async function getFeeStatistics(serverInfo: ConseilServerInfo, network: string, operationType: OperationKindType) {
let query = ConseilQueryBuilder.blankQuery();
query = ConseilQueryBuilder.addPredicate(query, 'kind', ConseilOperator.EQ, [operationType]);
query = ConseilQueryBuilder.addOrdering(query, 'timestamp', ConseilSortDirection.DESC);
query = ConseilQueryBuilder.setLimit(query, 1);
return getTezosEntityData(serverInfo, network, FEES, query);
}
export async function getProposals(serverInfo: ConseilServerInfo, network: string, query: ConseilQuery): Promise<any[]> {
return getTezosEntityData(serverInfo, network, PROPOSALS, query);
}
export async function getBakers(serverInfo: ConseilServerInfo, network: string, query: ConseilQuery): Promise<any[]> {
return getTezosEntityData(serverInfo, network, BAKERS, query);
}
export async function getBallots(serverInfo: ConseilServerInfo, network: string, query: ConseilQuery): Promise<any[]> {
return getTezosEntityData(serverInfo, network, BALLOTS, query);
}
/**
* Wait for the operation with the provided `hash` to appear on the chain for up to `duration` blocks.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param {string} hash Operation group hash of interest.
* @param {number} duration Number of blocks to wait.
* @param {number} blocktime Expected number of seconds between blocks.
*
* @returns Operation record
*/
export async function awaitOperationConfirmation(serverInfo: ConseilServerInfo, network: string, hash: string, duration: number = 10, blocktime: number = TezosConstants.DefaultBlockTime): Promise<any> {
if (duration <= 0) { throw new Error('Invalid duration'); }
const initialLevel = (await getBlockHead(serverInfo, network))['level'];
const timeOffset = 180000;
const startTime = (new Date).getTime() - timeOffset;
const estimatedEndTime = startTime + timeOffset + duration * blocktime * 1000;
log.debug(`TezosConseilClient.awaitOperationConfirmation looking for ${hash} since ${initialLevel} at ${(new Date(startTime).toUTCString())}, +${duration}`);
let currentLevel = initialLevel;
let operationQuery = ConseilQueryBuilder.blankQuery();
operationQuery = ConseilQueryBuilder.addPredicate(operationQuery , 'operation_group_hash', ConseilOperator.EQ, [hash], false);
operationQuery = ConseilQueryBuilder.addPredicate(operationQuery , 'timestamp', ConseilOperator.AFTER, [startTime], false);
operationQuery = ConseilQueryBuilder.setLimit(operationQuery, 1);
while (initialLevel + duration > currentLevel) {
const group = await getOperations(serverInfo, network, operationQuery);
if (group.length > 0) { return group[0]; }
currentLevel = (await getBlockHead(serverInfo, network))['level'];
if (initialLevel + duration < currentLevel) { break; }
if ((new Date).getTime() > estimatedEndTime) { break; }
await new Promise(resolve => setTimeout(resolve, blocktime * 1000));
}
throw new Error(`Did not observe ${hash} on ${network} in ${duration} block${duration > 1 ? 's' : ''} since ${initialLevel}`);
}
/**
* Wait for the operation with the provided `hash` to appear on the chain for up to `duration` blocks. Then wait for an additional `depth` blocks to ensure that a fork has not occurred.
*
* @param serverInfo Conseil server connection definition.
* @param network Tezos network to query, mainnet, alphanet, etc.
* @param {string} hash Operation group hash of interest.
* @param {number} duration Number of blocks to wait.
* @param {number} depth Number of blocks to skip for fork validation.
*
* @returns `true` if the chain ids match between the original operation block and the current head, false otherwise.
*/
export async function awaitOperationForkConfirmation(serverInfo: ConseilServerInfo, network: string, hash: string, duration: number, depth: number): Promise<boolean> {
const op = await awaitOperationConfirmation(serverInfo, network, hash, duration);
const initialLevel: number = op['block_level'];
const initialHash: string = op['block_hash'];
let currentLevel = initialLevel;
await new Promise(resolve => setTimeout(resolve, depth * 50 * 1000));
while (currentLevel < initialLevel + depth) {
const currentBlock = await getBlockHead(serverInfo, network);
currentLevel = currentBlock['level'];
if (currentLevel >= initialLevel + depth) { break; }
await new Promise(resolve => setTimeout(resolve, 60 * 1000));
}
let blockSequenceQuery = ConseilQueryBuilder.blankQuery();
blockSequenceQuery = ConseilQueryBuilder.addFields(blockSequenceQuery, 'level', 'hash', 'predecessor');
blockSequenceQuery = ConseilQueryBuilder.addPredicate(blockSequenceQuery, 'level', ConseilOperator.BETWEEN, [initialLevel - 1, initialLevel + depth]);
blockSequenceQuery = ConseilQueryBuilder.setLimit(blockSequenceQuery, depth * 2);
const blockSequenceResult = await getBlocks(serverInfo, network, blockSequenceQuery);
if (blockSequenceResult.length === depth + 2) {
return fastBlockContinuity(blockSequenceResult, initialLevel, initialHash);
} else {
return slowBlockContinuity(blockSequenceResult, initialLevel, initialHash, depth);
}
}
/**
* Returns big_map data for a given contract if any is available.
*
* @param serverInfo Conseil server connection definition.
* @param contract Contract address to query for.
*/
export async function getBigMapData(serverInfo: ConseilServerInfo, contract: string): Promise<ContractMapDetails | undefined> {
if (!contract.startsWith('KT1')) { throw new Error('Invalid address'); }
const ownerQuery = ConseilQueryBuilder.setLimit(ConseilQueryBuilder.addFields(ConseilQueryBuilder.addPredicate(ConseilQueryBuilder.blankQuery(), 'account_id', ConseilOperator.EQ, [contract], false), 'big_map_id'), 100);
const ownerResult = await getTezosEntityData(serverInfo, serverInfo.network, 'originated_account_maps', ownerQuery);
if (ownerResult.length < 1) { return undefined; }
const definitionQuery = ConseilQueryBuilder.setLimit(ConseilQueryBuilder.addPredicate(ConseilQueryBuilder.blankQuery(), 'big_map_id', (ownerResult.length > 1 ? ConseilOperator.IN : ConseilOperator.EQ), ownerResult.map(r => r.big_map_id), false), 100);
const definitionResult = await getTezosEntityData(serverInfo, serverInfo.network, 'big_maps', definitionQuery);
const contentQuery = ConseilQueryBuilder.setLimit(ConseilQueryBuilder.addFields(ConseilQueryBuilder.addPredicate(ConseilQueryBuilder.blankQuery(), 'big_map_id', (ownerResult.length > 1 ? ConseilOperator.IN : ConseilOperator.EQ), ownerResult.map(r => r.big_map_id), false), 'big_map_id', 'key', 'value'), 1000);
const contentResult = await getTezosEntityData(serverInfo, serverInfo.network, 'big_map_contents', contentQuery);
let maps: ContractMapDetailsItem[] = [];
for (const d of definitionResult) {
const definition = { index: Number(d['big_map_id']), key: d['key_type'], value: d['value_type'] };
let content: { key: string, value: string }[] = [];
for(const c of contentResult.filter(r => r['big_map_id'] === definition.index)) {
content.push({ key: JSON.stringify(c['key']), value: JSON.stringify(c['value'])});
}
maps.push({definition, content});
}
return { contract, maps };
}
/**
* Returns a value for a given plain-text key. The big map id is either provided as a paramter or the smallest of the possibly multiple big maps associated with the given contract address is used. Note that sometimes key values must be wrapped in quotes for key types that are non-numeric and not byte type.
*
* Under normal circumstances these keys are hashed and TezosNodeReader.getValueForBigMapKey() expects such an encoded key. However, with the Conseil indexer it's possible to query for plain-text keys.
*
* @param serverInfo Conseil server connection definition.
* @param key Key to query for.
* @param contract Optional contract address to be used to identify an associated big map.
* @param mapIndex Optional big map index to query, but one of contract or mapIndex must be provided.
*/
export async function getBigMapValueForKey(serverInfo: ConseilServerInfo, key: string, contract: string = '', mapIndex: number = -1): Promise<string> {
if (!contract.startsWith('KT1')) { throw new Error('Invalid address'); }
if (key.length < 1) { throw new Error('Invalid key'); }
if (mapIndex < 0 && contract.length === 0) { throw new Error('One of contract or mapIndex must be specified'); }
if (mapIndex < 0 && contract.length > 0) {
let ownerQuery = ConseilQueryBuilder.setLimit(ConseilQueryBuilder.blankQuery(), 1);
ownerQuery = ConseilQueryBuilder.addFields(ownerQuery, 'big_map_id');
ownerQuery = ConseilQueryBuilder.addPredicate(ownerQuery, 'account_id', ConseilOperator.EQ, [contract], false);
ownerQuery = ConseilQueryBuilder.addOrdering(ownerQuery, 'big_map_id', ConseilSortDirection.DESC);
const ownerResult = await getTezosEntityData(serverInfo, serverInfo.network, 'originated_account_maps', ownerQuery);
if (ownerResult.length < 1) { throw new Error(`Could not find any maps for ${contract}`); }
mapIndex = ownerResult[0];
}
let contentQuery = ConseilQueryBuilder.setLimit(ConseilQueryBuilder.blankQuery(), 1);
contentQuery = ConseilQueryBuilder.addFields(contentQuery, 'value');
contentQuery = ConseilQueryBuilder.addPredicate(contentQuery, 'key', ConseilOperator.EQ, [key], false);
contentQuery = ConseilQueryBuilder.addPredicate(contentQuery, 'big_map_id', ConseilOperator.EQ, [mapIndex], false);
const contentResult = await getTezosEntityData(serverInfo, serverInfo.network, 'big_map_contents', contentQuery);
if (contentResult.length < 1) { throw new Error(`Could not a value for key ${key} in map ${mapIndex}`); }
return contentResult[0];
}
/**
* Confirms that the specified operation was recorded on a continuous block sequence starting with the level below the block where
* it appeared through the end of the sequence from `awaitOperationForkConfirmation()` with the depth that was called with. This method is
* useful when the sequence of blocks retrieved by `awaitOperationForkConfirmation()` is the expected length, meaning `depth + 2`.
*
* Note, this is not an absolute guarantee that this operation is not part of a longer fork; just that the predecessor of each block
* at position `n` matches the hash of the block preceding it.
*/
function fastBlockContinuity(blocks, initialLevel: number, initialHash: string): boolean {
try {
return blocks.sort((a, b) => parseInt(a['level']) - parseInt(b['level'])).reduce((a, c, i) => {
if (!a) { throw new Error('Block sequence mismatch'); }
if (i > 1) {
return c['predecessor'] === blocks[i - 1]['hash'];
}
if (i === 1) {
return a && c['level'] === initialLevel
&& c['hash'] === initialHash
&& c['predecessor'] === blocks[i - 1]['hash'];
}
if (i === 0) {
return true;
}
}, true);
} catch {
return false;
}
}
/**
* Compared to `fastBlockContinuity()`, this method performs more sophisticated validation on the block sequence. This function is
* useful where `awaitOperationForkConfirmation()` receives a longer sequence of blocks than expected, more than `depth + 2`. In this
* case it's necessary to reconstruct a sequence from the provided blocks where of each block at position `n` matches the hash of
* the block preceding it with the expectation that there will be at least one instance of a duplicate level.
*/
function slowBlockContinuity(blocks, initialLevel: number, initialHash: string, depth: number): boolean {
throw new Error('Not implemented'); // TODO
}
/**
* Returns an entity query for the given ID. Positive numbers are interpreted as block level, strings starting with B as block hashes, strings starting with 'o' as operation group hashes, strings starting with 'tz1', 'tz2', 'tz3' or 'KT1' as account hashes.
*
* @param id
* @returns {{entity: string, query: ConseilQuery}} entity, query pair
*/
export function getEntityQueryForId(id: string | number): { entity: string, query: ConseilQuery } {
let q = ConseilQueryBuilder.setLimit(ConseilQueryBuilder.blankQuery(), 1);
if (typeof id === 'number') {
const n = Number(id);
if (n < 0) { throw new Error('Invalid numeric id parameter'); }
return { entity: BLOCKS, query: ConseilQueryBuilder.addPredicate(q, 'level', ConseilOperator.EQ, [id], false) };
} else if (typeof id === 'string') {
const s = String(id);
if (s.startsWith('tz1') || s.startsWith('tz2') || s.startsWith('tz3') || s.startsWith('KT1')) {
return { entity: ACCOUNTS, query: ConseilQueryBuilder.addPredicate(q, 'account_id', ConseilOperator.EQ, [id], false) };
} else if (s.startsWith('B')) {
return { entity: BLOCKS, query: ConseilQueryBuilder.addPredicate(q, 'hash', ConseilOperator.EQ, [id], false) };
} else if (s.startsWith('o')) {
q = ConseilQueryBuilder.setLimit(q, 1000);
q = ConseilQueryBuilder.addPredicate(q, 'operation_group_hash', ConseilOperator.EQ, [id], false);
q = ConseilQueryBuilder.addOrdering(q, 'nonce', ConseilSortDirection.DESC);
return { entity: OPERATIONS, query: q};
}
}
throw new Error('Invalid id parameter');
}
export async function countKeysInMap(serverInfo: ConseilServerInfo, mapIndex: number): Promise<number> {
let countQuery = ConseilQueryBuilder.blankQuery();
countQuery = ConseilQueryBuilder.addFields(countQuery, 'key');
countQuery = ConseilQueryBuilder.addPredicate(countQuery, 'big_map_id', ConseilOperator.EQ, [mapIndex]);
countQuery = ConseilQueryBuilder.addAggregationFunction(countQuery, 'key', ConseilFunction.count);
countQuery = ConseilQueryBuilder.setLimit(countQuery, 1);
const result = await ConseilDataClient.executeEntityQuery(serverInfo, 'tezos', serverInfo.network, 'big_map_contents', countQuery);
try {
return result[0]['count_key'];
} catch {
return -1;
}
}
} | the_stack |
import '@polymer/iron-autogrow-textarea/iron-autogrow-textarea';
import '../../../styles/shared-styles';
import '../../plugins/gr-endpoint-decorator/gr-endpoint-decorator';
import '../../plugins/gr-endpoint-param/gr-endpoint-param';
import '../gr-button/gr-button';
import '../gr-dialog/gr-dialog';
import '../gr-formatted-text/gr-formatted-text';
import '../gr-icons/gr-icons';
import '../gr-overlay/gr-overlay';
import '../gr-textarea/gr-textarea';
import '../gr-tooltip-content/gr-tooltip-content';
import '../gr-confirm-delete-comment-dialog/gr-confirm-delete-comment-dialog';
import '../gr-account-label/gr-account-label';
import {getAppContext} from '../../../services/app-context';
import {css, html, LitElement, PropertyValues} from 'lit';
import {customElement, property, query, state} from 'lit/decorators';
import {resolve} from '../../../models/dependency';
import {GerritNav} from '../../core/gr-navigation/gr-navigation';
import {GrTextarea} from '../gr-textarea/gr-textarea';
import {GrOverlay} from '../gr-overlay/gr-overlay';
import {
AccountDetailInfo,
CommentLinks,
NumericChangeId,
RepoName,
RobotCommentInfo,
} from '../../../types/common';
import {GrConfirmDeleteCommentDialog} from '../gr-confirm-delete-comment-dialog/gr-confirm-delete-comment-dialog';
import {
Comment,
DraftInfo,
isDraftOrUnsaved,
isRobot,
isUnsaved,
} from '../../../utils/comment-util';
import {
OpenFixPreviewEventDetail,
ValueChangedEvent,
} from '../../../types/events';
import {fire, fireEvent} from '../../../utils/event-util';
import {assertIsDefined} from '../../../utils/common-util';
import {Key, Modifier} from '../../../utils/dom-util';
import {commentsModelToken} from '../../../models/comments/comments-model';
import {sharedStyles} from '../../../styles/shared-styles';
import {subscribe} from '../../lit/subscription-controller';
import {ShortcutController} from '../../lit/shortcut-controller';
import {classMap} from 'lit/directives/class-map';
import {LineNumber} from '../../../api/diff';
import {CommentSide} from '../../../constants/constants';
import {getRandomInt} from '../../../utils/math-util';
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
import {configModelToken} from '../../../models/config/config-model';
const UNSAVED_MESSAGE = 'Unable to save draft';
const FILE = 'FILE';
// visible for testing
export const AUTO_SAVE_DEBOUNCE_DELAY_MS = 2000;
export const __testOnly_UNSAVED_MESSAGE = UNSAVED_MESSAGE;
/**
* All candidates tips to show, will pick randomly.
*/
const RESPECTFUL_REVIEW_TIPS = [
'Assume competence.',
'Provide rationale or context.',
'Consider how comments may be interpreted.',
'Avoid harsh language.',
'Make your comments specific and actionable.',
'When disagreeing, explain the advantage of your approach.',
];
declare global {
interface HTMLElementEventMap {
'comment-editing-changed': CustomEvent<boolean>;
'comment-unresolved-changed': CustomEvent<boolean>;
'comment-anchor-tap': CustomEvent<CommentAnchorTapEventDetail>;
}
}
export interface CommentAnchorTapEventDetail {
number: LineNumber;
side?: CommentSide;
}
@customElement('gr-comment')
export class GrComment extends LitElement {
/**
* Fired when the create fix comment action is triggered.
*
* @event create-fix-comment
*/
/**
* Fired when the show fix preview action is triggered.
*
* @event open-fix-preview
*/
/**
* Fired when editing status changed.
*
* @event comment-editing-changed
*/
/**
* Fired when the comment's timestamp is tapped.
*
* @event comment-anchor-tap
*/
@query('#editTextarea')
textarea?: GrTextarea;
@query('#container')
container?: HTMLElement;
@query('#resolvedCheckbox')
resolvedCheckbox?: HTMLInputElement;
@query('#confirmDeleteOverlay')
confirmDeleteOverlay?: GrOverlay;
@property({type: Object})
comment?: Comment;
// TODO: Move this out of gr-comment. gr-comment should not have a comments
// property. This is only used for hasHumanReply at the moment.
@property({type: Array})
comments?: Comment[];
/**
* Initial collapsed state of the comment.
*/
@property({type: Boolean, attribute: 'initially-collapsed'})
initiallyCollapsed?: boolean;
/**
* This is the *current* (internal) collapsed state of the comment. Do not set
* from the outside. Use `initiallyCollapsed` instead. This is just a
* reflected property such that css rules can be based on it.
*/
@property({type: Boolean, reflect: true})
collapsed?: boolean;
@property({type: Boolean, attribute: 'robot-button-disabled'})
robotButtonDisabled = false;
/* internal only, but used in css rules */
@property({type: Boolean, reflect: true})
saving = false;
/**
* `saving` and `autoSaving` are separate and cannot be set at the same time.
* `saving` affects the UI state (disabled buttons, etc.) and eventually
* leaves editing mode, but `autoSaving` just happens in the background
* without the user noticing.
*/
@state()
autoSaving?: Promise<DraftInfo>;
@state()
changeNum?: NumericChangeId;
@state()
editing = false;
@state()
commentLinks: CommentLinks = {};
@state()
repoName?: RepoName;
/* The 'dirty' state of the comment.message, which will be saved on demand. */
@state()
messageText = '';
/* The 'dirty' state of !comment.unresolved, which will be saved on demand. */
@state()
unresolved = true;
@property({type: Boolean})
showConfirmDeleteOverlay = false;
@property({type: Boolean})
showRespectfulTip = false;
@property({type: String})
respectfulReviewTip?: string;
@property({type: Boolean})
respectfulTipDismissed = false;
@property({type: Boolean})
unableToSave = false;
@property({type: Boolean, attribute: 'show-patchset'})
showPatchset = false;
@property({type: Boolean, attribute: 'show-ported-comment'})
showPortedComment = false;
@state()
account?: AccountDetailInfo;
@state()
isAdmin = false;
private readonly restApiService = getAppContext().restApiService;
private readonly storage = getAppContext().storageService;
private readonly reporting = getAppContext().reportingService;
private readonly changeModel = getAppContext().changeModel;
// Private but used in tests.
readonly getCommentsModel = resolve(this, commentsModelToken);
private readonly userModel = getAppContext().userModel;
private readonly configModel = resolve(this, configModelToken);
private readonly shortcuts = new ShortcutController(this);
/**
* This is triggered when the user types into the editing textarea. We then
* debounce it and call autoSave().
*/
private autoSaveTrigger$ = new Subject();
/**
* Set to the content of DraftInfo when entering editing mode.
* Only used for "Cancel".
*/
private originalMessage = '';
/**
* Set to the content of DraftInfo when entering editing mode.
* Only used for "Cancel".
*/
private originalUnresolved = false;
constructor() {
super();
subscribe(this, this.userModel.account$, x => (this.account = x));
subscribe(this, this.userModel.isAdmin$, x => (this.isAdmin = x));
subscribe(this, this.changeModel.repo$, x => (this.repoName = x));
subscribe(this, this.changeModel.changeNum$, x => (this.changeNum = x));
subscribe(
this,
this.autoSaveTrigger$.pipe(debounceTime(AUTO_SAVE_DEBOUNCE_DELAY_MS)),
() => {
this.autoSave();
}
);
this.shortcuts.addLocal({key: Key.ESC}, () => this.handleEsc());
for (const key of ['s', Key.ENTER]) {
for (const modifier of [Modifier.CTRL_KEY, Modifier.META_KEY]) {
this.shortcuts.addLocal({key, modifiers: [modifier]}, () => {
this.save();
});
}
}
}
override connectedCallback() {
super.connectedCallback();
subscribe(
this,
this.configModel().repoCommentLinks$,
x => (this.commentLinks = x)
);
}
override disconnectedCallback() {
// Clean up emoji dropdown.
if (this.textarea) this.textarea.closeDropdown();
super.disconnectedCallback();
}
static override get styles() {
return [
sharedStyles,
css`
:host {
display: block;
font-family: var(--font-family);
padding: var(--spacing-m);
}
:host([collapsed]) {
padding: var(--spacing-s) var(--spacing-m);
}
:host([saving]) {
pointer-events: none;
}
:host([saving]) .actions,
:host([saving]) .robotActions,
:host([saving]) .date {
opacity: 0.5;
}
.body {
padding-top: var(--spacing-m);
}
.header {
align-items: center;
cursor: pointer;
display: flex;
}
.headerLeft > span {
font-weight: var(--font-weight-bold);
}
.headerMiddle {
color: var(--deemphasized-text-color);
flex: 1;
overflow: hidden;
}
.draftLabel,
.draftTooltip {
color: var(--deemphasized-text-color);
display: inline;
}
.date {
justify-content: flex-end;
text-align: right;
white-space: nowrap;
}
span.date {
color: var(--deemphasized-text-color);
}
span.date:hover {
text-decoration: underline;
}
.actions,
.robotActions {
display: flex;
justify-content: flex-end;
padding-top: 0;
}
.robotActions {
/* Better than the negative margin would be to remove the gr-button
* padding, but then we would also need to fix the buttons that are
* inserted by plugins. :-/ */
margin: 4px 0 -4px;
}
.action {
margin-left: var(--spacing-l);
}
.rightActions {
display: flex;
justify-content: flex-end;
}
.rightActions gr-button {
--gr-button-padding: 0 var(--spacing-s);
}
.editMessage {
display: block;
margin: var(--spacing-m) 0;
width: 100%;
}
.show-hide {
margin-left: var(--spacing-s);
}
.robotId {
color: var(--deemphasized-text-color);
margin-bottom: var(--spacing-m);
}
.robotRun {
margin-left: var(--spacing-m);
}
.robotRunLink {
margin-left: var(--spacing-m);
}
/* just for a11y */
input.show-hide {
display: none;
}
label.show-hide {
cursor: pointer;
display: block;
}
label.show-hide iron-icon {
vertical-align: top;
}
:host([collapsed]) #container .body {
padding-top: 0;
}
#container .collapsedContent {
display: block;
overflow: hidden;
padding-left: var(--spacing-m);
text-overflow: ellipsis;
white-space: nowrap;
}
.resolve,
.unresolved {
align-items: center;
display: flex;
flex: 1;
margin: 0;
}
.resolve label {
color: var(--comment-text-color);
}
gr-dialog .main {
display: flex;
flex-direction: column;
width: 100%;
}
#deleteBtn {
--gr-button-text-color: var(--deemphasized-text-color);
--gr-button-padding: 0;
}
/** Disable select for the caret and actions */
.actions,
.show-hide {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.respectfulReviewTip {
justify-content: space-between;
display: flex;
padding: var(--spacing-m);
border: 1px solid var(--border-color);
border-radius: var(--border-radius);
margin-bottom: var(--spacing-m);
}
.respectfulReviewTip div {
display: flex;
}
.respectfulReviewTip div iron-icon {
margin-right: var(--spacing-s);
}
.respectfulReviewTip a {
white-space: nowrap;
margin-right: var(--spacing-s);
padding-left: var(--spacing-m);
text-decoration: none;
}
.pointer {
cursor: pointer;
}
.patchset-text {
color: var(--deemphasized-text-color);
margin-left: var(--spacing-s);
}
.headerLeft gr-account-label {
--account-max-length: 130px;
width: 150px;
}
.headerLeft gr-account-label::part(gr-account-label-text) {
font-weight: var(--font-weight-bold);
}
.draft gr-account-label {
width: unset;
}
.portedMessage {
margin: 0 var(--spacing-m);
}
.link-icon {
cursor: pointer;
}
`,
];
}
override render() {
if (isUnsaved(this.comment) && !this.editing) return;
const classes = {container: true, draft: isDraftOrUnsaved(this.comment)};
return html`
<div id="container" class="${classMap(classes)}">
<div
class="header"
id="header"
@click="${() => (this.collapsed = !this.collapsed)}"
>
<div class="headerLeft">
${this.renderAuthor()} ${this.renderPortedCommentMessage()}
${this.renderDraftLabel()}
</div>
<div class="headerMiddle">${this.renderCollapsedContent()}</div>
${this.renderRunDetails()} ${this.renderDeleteButton()}
${this.renderPatchset()} ${this.renderDate()} ${this.renderToggle()}
</div>
<div class="body">
${this.renderRobotAuthor()} ${this.renderEditingTextarea()}
${this.renderRespectfulTip()} ${this.renderCommentMessage()}
${this.renderHumanActions()} ${this.renderRobotActions()}
</div>
</div>
${this.renderConfirmDialog()}
`;
}
private renderAuthor() {
if (isRobot(this.comment)) {
const id = this.comment.robot_id;
return html`<span class="robotName">${id}</span>`;
}
const classes = {draft: isDraftOrUnsaved(this.comment)};
return html`
<gr-account-label
.account="${this.comment?.author ?? this.account}"
class="${classMap(classes)}"
hideStatus
>
</gr-account-label>
`;
}
private renderPortedCommentMessage() {
if (!this.showPortedComment) return;
if (!this.comment?.patch_set) return;
return html`
<a href="${this.getUrlForComment()}">
<span class="portedMessage" @click="${this.handlePortedMessageClick}">
From patchset ${this.comment?.patch_set}
</span>
</a>
`;
}
private renderDraftLabel() {
if (!isDraftOrUnsaved(this.comment)) return;
let label = 'DRAFT';
let tooltip =
'This draft is only visible to you. ' +
"To publish drafts, click the 'Reply' or 'Start review' button " +
"at the top of the change or press the 'a' key.";
if (this.unableToSave) {
label += ' (Failed to save)';
tooltip = 'Unable to save draft. Please try to save again.';
}
return html`
<gr-tooltip-content
class="draftTooltip"
has-tooltip
title="${tooltip}"
max-width="20em"
show-icon
>
<span class="draftLabel">${label}</span>
</gr-tooltip-content>
`;
}
private renderCollapsedContent() {
if (!this.collapsed) return;
return html`
<span class="collapsedContent">${this.comment?.message}</span>
`;
}
private renderRunDetails() {
if (!isRobot(this.comment)) return;
if (!this.comment?.url || this.collapsed) return;
return html`
<div class="runIdMessage message">
<div class="runIdInformation">
<a class="robotRunLink" href="${this.comment.url}">
<span class="robotRun link">Run Details</span>
</a>
</div>
</div>
`;
}
/**
* Deleting a comment is an admin feature. It means more than just discarding
* a draft. It is an action applied to published comments.
*/
private renderDeleteButton() {
if (
!this.isAdmin ||
isDraftOrUnsaved(this.comment) ||
isRobot(this.comment)
)
return;
if (this.collapsed) return;
return html`
<gr-button
id="deleteBtn"
title="Delete Comment"
link
class="action delete"
@click="${this.openDeleteCommentOverlay}"
>
<iron-icon id="icon" icon="gr-icons:delete"></iron-icon>
</gr-button>
`;
}
private renderPatchset() {
if (!this.showPatchset) return;
assertIsDefined(this.comment?.patch_set, 'comment.patch_set');
return html`
<span class="patchset-text"> Patchset ${this.comment.patch_set}</span>
`;
}
private renderDate() {
if (!this.comment?.updated || this.collapsed) return;
return html`
<span class="separator"></span>
<span class="date" tabindex="0" @click="${this.handleAnchorClick}">
<gr-date-formatter
withTooltip
.dateStr="${this.comment.updated}"
></gr-date-formatter>
</span>
`;
}
private renderToggle() {
const icon = this.collapsed
? 'gr-icons:expand-more'
: 'gr-icons:expand-less';
const ariaLabel = this.collapsed ? 'Expand' : 'Collapse';
return html`
<div class="show-hide" tabindex="0">
<label class="show-hide" aria-label="${ariaLabel}">
<input
type="checkbox"
class="show-hide"
?checked="${this.collapsed}"
@change="${() => (this.collapsed = !this.collapsed)}"
/>
<iron-icon id="icon" icon="${icon}"></iron-icon>
</label>
</div>
`;
}
private renderRobotAuthor() {
if (!isRobot(this.comment) || this.collapsed) return;
return html`<div class="robotId">${this.comment.author?.name}</div>`;
}
private renderEditingTextarea() {
if (!this.editing || this.collapsed) return;
return html`
<gr-textarea
id="editTextarea"
class="editMessage"
autocomplete="on"
code=""
?disabled="${this.saving}"
rows="4"
text="${this.messageText}"
@text-changed="${(e: ValueChangedEvent) => {
// TODO: This is causing a re-render of <gr-comment> on every key
// press. Try to avoid always setting `this.messageText` or at least
// debounce it. Most of the code can just inspect the current value
// of the textare instead of needing a dedicated property.
this.messageText = e.detail.value;
this.autoSaveTrigger$.next();
}}"
></gr-textarea>
`;
}
private renderRespectfulTip() {
if (!this.showRespectfulTip || this.respectfulTipDismissed) return;
if (!this.editing || this.collapsed) return;
return html`
<div class="respectfulReviewTip">
<div>
<gr-tooltip-content
has-tooltip
title="Tips for respectful code reviews."
>
<iron-icon
class="pointer"
icon="gr-icons:lightbulb-outline"
></iron-icon>
</gr-tooltip-content>
${this.respectfulReviewTip}
</div>
<div>
<a
tabindex="-1"
@click="${this.onRespectfulReadMoreClick}"
href="https://testing.googleblog.com/2019/11/code-health-respectful-reviews-useful.html"
target="_blank"
>
Read more
</a>
<a
tabindex="-1"
class="close pointer"
@click="${this.dismissRespectfulTip}"
>
Not helpful
</a>
</div>
</div>
`;
}
private renderCommentMessage() {
if (this.collapsed || this.editing) return;
return html`
<!--The "message" class is needed to ensure selectability from
gr-diff-selection.-->
<gr-formatted-text
class="message"
.content="${this.comment?.message}"
.config="${this.commentLinks}"
?noTrailingMargin="${!isDraftOrUnsaved(this.comment)}"
></gr-formatted-text>
`;
}
private renderCopyLinkIcon() {
// Only show the icon when the thread contains a published comment.
if (!this.comment?.in_reply_to && isDraftOrUnsaved(this.comment)) return;
return html`
<iron-icon
class="copy link-icon"
@click="${this.handleCopyLink}"
title="Copy link to this comment"
icon="gr-icons:link"
role="button"
tabindex="0"
>
</iron-icon>
`;
}
private renderHumanActions() {
if (!this.account || isRobot(this.comment)) return;
if (this.collapsed || !isDraftOrUnsaved(this.comment)) return;
return html`
<div class="actions">
<div class="action resolve">
<label>
<input
type="checkbox"
id="resolvedCheckbox"
?checked="${!this.unresolved}"
@change="${this.handleToggleResolved}"
/>
Resolved
</label>
</div>
${this.renderDraftActions()}
</div>
`;
}
private renderDraftActions() {
if (!isDraftOrUnsaved(this.comment)) return;
return html`
<div class="rightActions">
${this.autoSaving ? html`. ` : ''}
${this.renderCopyLinkIcon()} ${this.renderDiscardButton()}
${this.renderEditButton()} ${this.renderCancelButton()}
${this.renderSaveButton()}
</div>
`;
}
private renderDiscardButton() {
if (this.editing) return;
return html`<gr-button
link
?disabled="${this.saving}"
class="action discard"
@click="${this.discard}"
>Discard</gr-button
>`;
}
private renderEditButton() {
if (this.editing) return;
return html`<gr-button
link
?disabled="${this.saving}"
class="action edit"
@click="${this.edit}"
>Edit</gr-button
>`;
}
private renderCancelButton() {
if (!this.editing) return;
return html`
<gr-button
link
?disabled="${this.saving}"
class="action cancel"
@click="${this.cancel}"
>Cancel</gr-button
>
`;
}
private renderSaveButton() {
if (!this.editing && !this.unableToSave) return;
return html`
<gr-button
link
?disabled="${this.isSaveDisabled()}"
class="action save"
@click="${this.save}"
>Save</gr-button
>
`;
}
private renderRobotActions() {
if (!this.account || !isRobot(this.comment)) return;
const endpoint = html`
<gr-endpoint-decorator name="robot-comment-controls">
<gr-endpoint-param name="comment" .value="${this.comment}">
</gr-endpoint-param>
</gr-endpoint-decorator>
`;
return html`
<div class="robotActions">
${this.renderCopyLinkIcon()} ${endpoint} ${this.renderShowFixButton()}
${this.renderPleaseFixButton()}
</div>
`;
}
private renderShowFixButton() {
if (!(this.comment as RobotCommentInfo)?.fix_suggestions) return;
return html`
<gr-button
link
secondary
class="action show-fix"
?disabled="${this.saving}"
@click="${this.handleShowFix}"
>
Show Fix
</gr-button>
`;
}
private renderPleaseFixButton() {
if (this.hasHumanReply()) return;
return html`
<gr-button
link
?disabled="${this.robotButtonDisabled}"
class="action fix"
@click="${this.handleFix}"
>
Please Fix
</gr-button>
`;
}
private renderConfirmDialog() {
if (!this.showConfirmDeleteOverlay) return;
return html`
<gr-overlay id="confirmDeleteOverlay" with-backdrop>
<gr-confirm-delete-comment-dialog
id="confirmDeleteComment"
@confirm="${this.handleConfirmDeleteComment}"
@cancel="${this.closeDeleteCommentOverlay}"
>
</gr-confirm-delete-comment-dialog>
</gr-overlay>
`;
}
private getUrlForComment() {
const comment = this.comment;
if (!comment || !this.changeNum || !this.repoName) return '';
if (!comment.id) throw new Error('comment must have an id');
return GerritNav.getUrlForComment(
this.changeNum as NumericChangeId,
this.repoName,
comment.id
);
}
private firstWillUpdateDone = false;
firstWillUpdate() {
if (this.firstWillUpdateDone) return;
this.firstWillUpdateDone = true;
assertIsDefined(this.comment, 'comment');
this.unresolved = this.comment.unresolved ?? true;
if (isUnsaved(this.comment)) this.editing = true;
if (isDraftOrUnsaved(this.comment)) {
this.collapsed = false;
} else {
this.collapsed = !!this.initiallyCollapsed;
}
}
override willUpdate(changed: PropertyValues) {
this.firstWillUpdate();
if (changed.has('editing')) {
this.onEditingChanged();
}
if (changed.has('unresolved')) {
// The <gr-comment-thread> component wants to change its color based on
// the (dirty) unresolved state, so let's notify it about changes.
fire(this, 'comment-unresolved-changed', this.unresolved);
}
}
private handlePortedMessageClick() {
assertIsDefined(this.comment, 'comment');
this.reporting.reportInteraction('navigate-to-original-comment', {
line: this.comment.line,
range: this.comment.range,
});
}
// private, but visible for testing
getRandomInt(from: number, to: number) {
return getRandomInt(from, to);
}
private dismissRespectfulTip() {
this.respectfulTipDismissed = true;
this.reporting.reportInteraction('respectful-tip-dismissed', {
tip: this.respectfulReviewTip,
});
// add a 14-day delay to the tip cache
this.storage.setRespectfulTipVisibility(/* delayDays= */ 14);
}
private onRespectfulReadMoreClick() {
this.reporting.reportInteraction('respectful-read-more-clicked');
}
private handleCopyLink() {
fireEvent(this, 'copy-comment-link');
}
/** Enter editing mode. */
private edit() {
if (!isDraftOrUnsaved(this.comment)) {
throw new Error('Cannot edit published comment.');
}
if (this.editing) return;
this.editing = true;
}
// TODO: Move this out of gr-comment. gr-comment should not have a comments
// property.
private hasHumanReply() {
if (!this.comment || !this.comments) return false;
return this.comments.some(
c => c.in_reply_to && c.in_reply_to === this.comment?.id && !isRobot(c)
);
}
// private, but visible for testing
getEventPayload(): OpenFixPreviewEventDetail {
assertIsDefined(this.comment?.patch_set, 'comment.patch_set');
return {comment: this.comment, patchNum: this.comment.patch_set};
}
private onEditingChanged() {
if (this.editing) {
this.collapsed = false;
this.messageText = this.comment?.message ?? '';
this.unresolved = this.comment?.unresolved ?? true;
this.originalMessage = this.messageText;
this.originalUnresolved = this.unresolved;
setTimeout(() => this.textarea?.putCursorAtEnd(), 1);
}
this.setRespectfulTip();
// Parent components such as the reply dialog might be interested in whether
// come of their child components are in editing mode.
fire(this, 'comment-editing-changed', this.editing);
}
private setRespectfulTip() {
// visibility based on cache this will make sure we only and always show
// a tip once every Math.max(a day, period between creating comments)
const cachedVisibilityOfRespectfulTip =
this.storage.getRespectfulTipVisibility();
if (this.editing && !cachedVisibilityOfRespectfulTip) {
// we still want to show the tip with a probability of 33%
if (this.getRandomInt(0, 2) >= 1) return;
this.showRespectfulTip = true;
const randomIdx = this.getRandomInt(0, RESPECTFUL_REVIEW_TIPS.length);
this.respectfulReviewTip = RESPECTFUL_REVIEW_TIPS[randomIdx];
this.reporting.reportInteraction('respectful-tip-appeared', {
tip: this.respectfulReviewTip,
});
// update cache
this.storage.setRespectfulTipVisibility();
} else {
this.showRespectfulTip = false;
this.respectfulReviewTip = undefined;
}
}
// private, but visible for testing
isSaveDisabled() {
assertIsDefined(this.comment, 'comment');
if (this.saving) return true;
if (this.comment.unresolved !== this.unresolved) return false;
return !this.messageText?.trimEnd();
}
private handleEsc() {
// vim users don't like ESC to cancel/discard, so only do this when the
// comment text is empty.
if (!this.messageText?.trimEnd()) this.cancel();
}
private handleAnchorClick() {
assertIsDefined(this.comment, 'comment');
fire(this, 'comment-anchor-tap', {
number: this.comment.line || FILE,
side: this.comment?.side,
});
}
private handleFix() {
// Handled by <gr-comment-thread>.
fire(this, 'create-fix-comment', this.getEventPayload());
}
private handleShowFix() {
// Handled top-level in the diff and change view components.
fire(this, 'open-fix-preview', this.getEventPayload());
}
// private, but visible for testing
cancel() {
assertIsDefined(this.comment, 'comment');
if (!isDraftOrUnsaved(this.comment)) {
throw new Error('only unsaved and draft comments are editable');
}
this.messageText = this.originalMessage;
this.unresolved = this.originalUnresolved;
this.save();
}
async autoSave() {
if (this.saving || this.autoSaving) return;
if (!this.editing || !this.comment) return;
if (!isDraftOrUnsaved(this.comment)) return;
const messageToSave = this.messageText.trimEnd();
if (messageToSave === '') return;
if (messageToSave === this.comment.message) return;
try {
this.autoSaving = this.rawSave(messageToSave, {showToast: false});
await this.autoSaving;
} finally {
this.autoSaving = undefined;
}
}
async discard() {
this.messageText = '';
await this.save();
}
async save() {
if (!isDraftOrUnsaved(this.comment)) throw new Error('not a draft');
try {
this.saving = true;
this.unableToSave = false;
if (this.autoSaving) {
this.comment = await this.autoSaving;
}
// Depending on whether `messageToSave` is empty we treat this either as
// a discard or a save action.
const messageToSave = this.messageText.trimEnd();
if (messageToSave === '') {
// Don't try to discard UnsavedInfo. Nothing to do then.
if (this.comment.id) {
await this.getCommentsModel().discardDraft(this.comment.id);
}
} else {
// No need to make a backend call when nothing has changed.
if (
messageToSave !== this.comment?.message ||
this.unresolved !== this.comment.unresolved
) {
await this.rawSave(messageToSave, {showToast: true});
}
}
this.editing = false;
} catch (e) {
this.unableToSave = true;
throw e;
} finally {
this.saving = false;
}
}
/** For sharing between save() and autoSave(). */
private rawSave(message: string, options: {showToast: boolean}) {
if (!isDraftOrUnsaved(this.comment)) throw new Error('not a draft');
return this.getCommentsModel().saveDraft(
{
...this.comment,
message,
unresolved: this.unresolved,
},
options.showToast
);
}
private handleToggleResolved() {
this.unresolved = !this.unresolved;
if (!this.editing) {
// messageText is only assigned a value if the comment reaches editing
// state, however it is possible that the user toggles the resolved state
// without editing the comment in which case we assign the correct value
// to messageText here
this.messageText = this.comment?.message ?? '';
this.save();
}
}
private async openDeleteCommentOverlay() {
this.showConfirmDeleteOverlay = true;
await this.updateComplete;
await this.confirmDeleteOverlay?.open();
}
private closeDeleteCommentOverlay() {
this.showConfirmDeleteOverlay = false;
this.confirmDeleteOverlay?.remove();
this.confirmDeleteOverlay?.close();
}
/**
* Deleting a *published* comment is an admin feature. It means more than just
* discarding a draft.
*
* TODO: Also move this into the comments-service.
* TODO: Figure out a good reloading strategy when deleting was successful.
* `this.comment = newComment` does not seem sufficient.
*/
// private, but visible for testing
handleConfirmDeleteComment() {
const dialog = this.confirmDeleteOverlay?.querySelector(
'#confirmDeleteComment'
) as GrConfirmDeleteCommentDialog | null;
if (!dialog || !dialog.message) {
throw new Error('missing confirm delete dialog');
}
assertIsDefined(this.changeNum, 'changeNum');
assertIsDefined(this.comment, 'comment');
assertIsDefined(this.comment.patch_set, 'comment.patch_set');
if (isDraftOrUnsaved(this.comment)) {
throw new Error('Admin deletion is only for published comments.');
}
this.restApiService
.deleteComment(
this.changeNum,
this.comment.patch_set,
this.comment.id,
dialog.message
)
.then(newComment => {
this.closeDeleteCommentOverlay();
this.comment = newComment;
});
}
}
declare global {
interface HTMLElementTagNameMap {
'gr-comment': GrComment;
}
} | the_stack |
import { Graph } from '../../../src';
import '../../../src/behavior';
import { GraphData, Item } from '@antv/g6-core';
import Core from '@antv/g6-core';
const { scale, translate } = Core.Util;
const div = document.createElement('div');
div.id = 'global-spec';
document.body.appendChild(div);
describe('graph', () => {
const globalGraph = new Graph({
container: div,
width: 500,
height: 500,
modes: {
default: ['drag-node'],
},
});
const data = {
nodes: [
{
id: 'node1',
x: 150,
y: 50,
label: 'node1',
},
{
id: 'node2',
x: 200,
y: 150,
label: 'node2',
},
{
id: 'node3',
x: 100,
y: 150,
label: 'node3',
},
],
edges: [
{
source: 'node1',
target: 'node2',
},
{
source: 'node2',
target: 'node3',
},
{
source: 'node3',
target: 'node1',
},
],
};
globalGraph.data(data);
globalGraph.render();
it('invalid container', () => {
expect(() => {
// eslint-disable-next-line no-new
new Graph({} as any);
}).toThrowError('invalid container');
});
it('new & destroy graph', () => {
const inst = new Graph({
container: div,
width: 500,
height: 500,
modes: {
default: ['drag-node', 'drag-canvas', 'zoom-canvas'],
},
});
const length = div.childNodes.length;
expect(inst).not.toBe(undefined);
expect(inst instanceof Graph).toBe(true);
expect(length > 1).toBe(true);
expect(inst.get('canvas')).not.toBe(undefined);
expect(inst.get('group')).not.toBe(undefined);
expect(inst.get('group').get('className')).toEqual('root-container');
expect(
inst
.get('group')
.get('id')
.endsWith('-root'),
).toBe(true);
const children = inst.get('group').get('children');
expect(children.length).toBe(4);
expect(children[1].get('className')).toEqual('edge-container');
const nodes = inst.getNodes();
expect(nodes).not.toBe(undefined);
expect(nodes.length).toBe(0);
const edges = inst.getEdges();
expect(edges).not.toBe(undefined);
expect(edges.length).toBe(0);
const canvas = inst.get('canvas');
inst.destroy();
expect(inst.destroyed).toBe(true);
expect(canvas.destroyed).toBe(true);
expect(length - div.childNodes.length).toBe(1);
});
it('render without data', () => {
const inst = new Graph({
container: div,
width: 500,
height: 500,
});
inst.data(null);
expect(() => {
inst.render();
}).toThrowError('data must be defined first');
});
it('groupByTypes is false & toDataURL', () => {
const inst = new Graph({
container: div,
width: 500,
height: 500,
groupByTypes: false,
});
const data = {
nodes: [
{
id: 'node1',
label: 'node1',
},
{
id: 'node2',
},
],
edges: [
{
id: 'edge1',
source: 'node1',
target: 'node2',
},
{
id: 'edge2',
source: 'node1',
target: 'node1',
},
{
id: 'edge3',
source: 'node2',
target: 'node2',
},
],
};
inst.data(data);
inst.render();
const nodeGroup = inst.get('nodeGroup');
const edgeGroup = inst.get('edgeGroup');
expect(nodeGroup).toBe(undefined);
expect(edgeGroup).toBe(undefined);
const node = inst.findById('node1');
const edge = inst.findById('edge1');
const group1 = node.get('group').getParent();
const group2 = edge.get('group').getParent();
expect(group1).toEqual(group2);
const url = inst.toDataURL();
expect(url).not.toBe(null);
inst.destroy();
});
it('translate', () => {
const canvasMatrix = globalGraph.get('canvas').getMatrix();
globalGraph.translate(100, 100);
const matrix = globalGraph.get('group').getMatrix();
expect(canvasMatrix).toBe(null);
expect(matrix[6]).toBe(100);
expect(matrix[7]).toBe(100);
globalGraph.get('group').resetMatrix();
});
it('moveTo', () => {
let group = globalGraph.get('group');
let bbox = group.getCanvasBBox();
globalGraph.moveTo(100, 100);
group = globalGraph.get('group');
bbox = group.getCanvasBBox();
expect(bbox.x).toBe(100);
expect(bbox.y).toBe(100);
globalGraph.get('group').resetMatrix();
});
it('zoom', () => {
globalGraph.zoom(3, { x: 100, y: 100 });
const matrix = globalGraph.get('group').getMatrix();
expect(matrix[0]).toBe(3);
expect(matrix[4]).toBe(3);
expect(matrix[6]).toBe(-200);
expect(matrix[7]).toBe(-200);
expect(globalGraph.getZoom()).toBe(3);
globalGraph.get('group').resetMatrix();
});
it('minZoom & maxZoom', () => {
const graph = new Graph({
container: div,
minZoom: 2,
maxZoom: 5,
width: 500,
height: 500,
});
const data = {
nodes: [
{
id: 'node',
},
],
};
graph.data(data);
graph.render();
let matrix = graph.get('group').getMatrix();
expect(matrix).toBe(null);
graph.zoom(0.5, { x: 100, y: 100 });
matrix = graph.get('group').getMatrix();
expect(matrix).toBe(null);
graph.zoom(5.5);
matrix = graph.get('group').getMatrix();
expect(matrix).toBe(null);
});
it('zoomTo', () => {
let matrix = globalGraph.get('group').getMatrix();
expect(matrix).toBe(null);
globalGraph.zoomTo(2);
matrix = globalGraph.get('group').getMatrix();
expect(matrix[0]).toBe(2);
expect(matrix[4]).toBe(2);
expect(matrix[6]).toBe(0);
expect(matrix[7]).toBe(0);
globalGraph.zoomTo(1.5, { x: 250, y: 250 });
matrix = globalGraph.get('group').getMatrix();
expect(matrix[0]).toBe(1.5);
expect(matrix[4]).toBe(1.5);
expect(matrix[6]).toBe(62.5);
expect(matrix[7]).toBe(62.5);
});
it('change size', () => {
const graph = new Graph({
container: div,
width: 500,
height: 500,
});
expect(graph.get('width')).toBe(500);
expect(graph.get('height')).toBe(500);
expect(typeof graph.changeSize).toEqual('function');
graph.changeSize(300, 300);
expect(graph.get('width')).toBe(300);
expect(graph.get('height')).toBe(300);
// 专门用于测试使用非 number 类型 会报错的情况 // TODO 可以移走这个测试, TS 本身就限制了类型参数
// expect(() => {
// graph.changeSize('x', 10);
// }).toThrowError(
// 'invalid canvas width & height, please make sure width & height type is number',
// );
graph.destroy();
});
it('getCurrentMode', () => {
const mode = globalGraph.getCurrentMode();
expect(mode).toBe('default');
});
it('data & changeData & save', () => {
const data = {
nodes: [
{
id: 'a',
type: 'circle',
color: '#333',
x: 30,
y: 30,
size: 20,
label: 'a',
},
{
id: 'b',
type: 'ellipse',
color: '#666',
x: 50,
y: 60,
size: [30, 40],
label: 'b',
},
{
id: 'c',
type: 'rect',
color: '#999',
x: 100,
y: 70,
size: 20,
label: 'c',
},
],
edges: [
{
source: 'a',
target: 'b',
id: 'd',
},
{
source: 'a',
target: 'c',
id: 'e',
},
],
};
globalGraph.data(data);
globalGraph.render();
expect(globalGraph.get('nodes').length).toBe(3);
expect(globalGraph.get('edges').length).toBe(2);
let map = globalGraph.get('itemMap');
expect(map.a).not.toBe(undefined);
expect(map.b).not.toBe(undefined);
expect(map.c).not.toBe(undefined);
expect(map.d).not.toBe(undefined);
const edges = globalGraph.getEdges();
expect(edges.length).toBe(2);
const nodes = globalGraph.getNodes();
expect(nodes.length).toBe(3);
expect(map.e).not.toBe(undefined);
data.nodes.splice(0, 1);
data.edges.splice(0, 1);
data.edges[0].source = 'b';
data.nodes.push({
id: 'f',
type: 'circle',
color: '#333',
x: 100,
y: 80,
size: 30,
label: 'f',
});
globalGraph.changeData(data);
map = globalGraph.get('itemMap');
expect(globalGraph.get('nodes').length).toBe(3);
expect(globalGraph.get('edges').length).toBe(1);
expect(map.a).toBe(undefined);
expect(map.b).not.toBe(undefined);
expect(map.c).not.toBe(undefined);
expect(map.d).toBe(undefined);
expect(map.e).not.toBe(undefined);
expect(map.f).not.toBe(undefined);
const exported: GraphData = globalGraph.save() as GraphData;
// expect(JSON.stringify(exported)).not.to.throw;
expect(exported.nodes.length).toBe(3);
expect(exported.edges.length).toBe(1);
const edge = exported.edges[0];
expect(edge.id).toBe('e');
expect(edge.source).toBe('b');
expect(edge.target).toBe('c');
});
it('change data with null', () => {
const data = {
nodes: [
{
id: 'a',
type: 'circle',
color: '#333',
x: 30,
y: 30,
size: 20,
label: 'a',
},
{
id: 'b',
type: 'ellipse',
color: '#666',
x: 50,
y: 60,
size: [30, 40],
label: 'b',
},
{
id: 'c',
type: 'rect',
color: '#999',
x: 100,
y: 70,
size: 20,
label: 'c',
},
],
edges: [
{
source: 'a',
target: 'b',
id: 'd',
},
{
source: 'a',
target: 'c',
id: 'e',
},
],
};
globalGraph.data(data);
globalGraph.render();
const newData = null;
const nodeNumBeforeChange = globalGraph.getNodes().length;
globalGraph.changeData(newData);
const nodeNumAfterChange = globalGraph.getNodes().length;
expect(nodeNumBeforeChange).toBe(nodeNumAfterChange);
});
it('change data with animate', () => {
const data = {
nodes: [
{
id: 'a',
type: 'circle',
color: '#333',
x: 30,
y: 30,
size: 20,
label: 'a',
},
{
id: 'b',
type: 'ellipse',
color: '#666',
x: 50,
y: 60,
size: [30, 40],
label: 'b',
},
{
id: 'c',
type: 'rect',
color: '#999',
x: 100,
y: 70,
size: 20,
label: 'c',
},
],
edges: [
{
source: 'a',
target: 'b',
id: 'd',
},
{
source: 'a',
target: 'c',
id: 'e',
},
],
};
globalGraph.data(data);
globalGraph.render();
globalGraph.set('animate', true);
data.nodes[0].x = 100;
data.nodes[0].y = 100;
globalGraph.changeData(data);
const nodeModel = globalGraph.getNodes()[0].getModel();
expect(nodeModel.x).toBe(100);
expect(nodeModel.y).toBe(100);
});
it('find', () => {
globalGraph.clear();
globalGraph.addItem('node', { id: 'node', x: 50, y: 100, size: 50, className: 'test test2' });
const item = globalGraph.addItem('node', {
id: 'node2',
x: 100,
y: 100,
size: 50,
className: 'test',
});
const findNode = globalGraph.find('node', (node: any) => node.get('model').x === 100);
expect(findNode).not.toBe(undefined);
expect(findNode).toEqual(item);
});
it('findAll', () => {
globalGraph.clear();
const node1 = globalGraph.addItem('node', {
id: 'node',
x: 100,
y: 100,
size: 50,
className: 'test test2',
});
const node2 = globalGraph.addItem('node', {
id: 'node2',
x: 100,
y: 100,
size: 50,
className: 'test',
});
const node3 = globalGraph.addItem('node', { id: 'node3', x: 100, y: 100, size: 50 });
node1.setState('active', true);
node2.setState('selected', true);
node3.setState('active', true);
let nodes = globalGraph.findAllByState('node', 'active');
expect(nodes.length).toEqual(2);
expect(nodes[0]).toEqual(node1);
expect(nodes[1]).toEqual(node3);
nodes = globalGraph.findAllByState('node', 'selected');
expect(nodes.length).toEqual(1);
expect(nodes[0]).toEqual(node2);
});
it('refresh positions', () => {
const data = { id: 'node4', x: 100, y: 50, size: 50, className: 'test test2' };
const node = globalGraph.addItem('node', data);
const group = node.get('group');
expect(group.getMatrix()[6]).toBe(100);
expect(group.getMatrix()[7]).toBe(50);
data.x = 50;
data.y = 100;
globalGraph.refreshPositions();
expect(group.getMatrix()[6]).toBe(50);
expect(group.getMatrix()[7]).toBe(100);
});
it('removeItem', () => {
let removeNode = globalGraph.findById('remove-item');
expect(removeNode).toBe(undefined);
const data = { id: 'remove-item', x: 10, y: 50, size: 50, className: 'test test2' };
const node = globalGraph.addItem('node', data);
expect(node).not.toBe(undefined);
globalGraph.removeItem('remove-item');
removeNode = globalGraph.findById('remove-item');
expect(removeNode).toBe(undefined);
});
it('canvas point & model point convert', () => {
const group = globalGraph.get('group');
let point = globalGraph.getPointByCanvas(100, 100);
expect(point.x).toBe(100);
expect(point.y).toBe(100);
translate(group, {
x: 100,
y: 100,
});
point = globalGraph.getPointByCanvas(100, 100);
expect(point.x).toBe(0);
expect(point.y).toBe(0);
scale(group, [1.5, 1.5]);
point = globalGraph.getPointByCanvas(100, 100);
expect(point.x).toBe(-33.33333333333334);
expect(point.y).toBe(-33.33333333333334);
group.resetMatrix();
point = globalGraph.getCanvasByPoint(100, 100);
expect(point.x).toBe(100);
expect(point.y).toBe(100);
translate(group, {
x: 100,
y: 100,
});
point = globalGraph.getCanvasByPoint(0, 0);
expect(point.x).toBe(100);
expect(point.y).toBe(100);
group.resetMatrix();
});
it('client point & model point convert', () => {
const group = globalGraph.get('group');
const bbox = globalGraph
.get('canvas')
.get('el')
.getBoundingClientRect();
let point = globalGraph.getPointByClient(bbox.left + 100, bbox.top + 100);
expect(point.x).toBe(100);
expect(point.y).toBe(100);
translate(group, {
x: 100,
y: 100,
});
point = globalGraph.getPointByClient(bbox.left + 100, bbox.top + 100);
expect(point.x).toBe(0);
expect(point.y).toBe(0);
scale(group, [1.5, 1.5]);
point = globalGraph.getPointByClient(bbox.left + 100, bbox.top + 100);
expect(point.x).toBe(-33.33333333333334);
expect(point.y).toBe(-33.33333333333334);
group.resetMatrix();
point = globalGraph.getClientByPoint(100, 100);
expect(point.x).toBe(bbox.left + 100);
expect(point.y).toBe(bbox.top + 100);
translate(group, {
x: 100,
y: 100,
});
point = globalGraph.getClientByPoint(100, 100);
expect(point.x).toBe(bbox.left + 200);
expect(point.y).toBe(bbox.top + 200);
});
it('clear', () => {
globalGraph.destroy();
expect(globalGraph.destroyed).toBe(true);
});
});
describe('all node link center', () => {
const graph = new Graph({
container: div,
width: 500,
height: 500,
linkCenter: true,
nodeStateStyles: {
a: {
fill: 'red',
},
b: {
stroke: 'red',
},
},
});
it('init', () => {
expect(graph.get('linkCenter')).toBe(true);
graph.data({
nodes: [
{
id: '1',
x: 10,
y: 10,
},
{
id: '2',
x: 100,
y: 100,
},
],
edges: [{ id: 'e1', source: '1', target: '2' }],
});
graph.render();
const edge = graph.findById('e1');
expect(edge.get('keyShape').attr('path')).toEqual([['M', 10, 10], ['L', 100, 100]]);
});
it('loop', () => {
graph.set('linkCenter', false);
const node = graph.addItem('node', {
id: 'circleNode',
x: 150,
y: 150,
style: { fill: 'yellow' },
anchorPoints: [[0, 0], [0, 1]],
});
const edge1 = graph.addItem('edge', {
id: 'edge',
source: 'circleNode',
target: 'circleNode',
type: 'loop',
loopCfg: {
position: 'top',
dist: 60,
clockwise: true,
},
style: { endArrow: true },
});
const edge2 = graph.addItem('edge', {
id: 'edge1',
source: 'circleNode',
target: 'circleNode',
type: 'loop',
loopCfg: {
position: 'top-left',
dist: 60,
clockwise: false,
},
style: { endArrow: true },
});
const edge3 = graph.addItem('edge', {
id: 'edge2',
source: 'circleNode',
target: 'circleNode',
type: 'loop',
loopCfg: {
position: 'top-right',
dist: 60,
},
style: { endArrow: true },
});
const edge4 = graph.addItem('edge', {
id: 'edge4',
source: 'circleNode',
target: 'circleNode',
type: 'loop',
loopCfg: {
position: 'right',
dist: 60,
clockwise: true,
},
style: { endArrow: true },
});
const edgeWithAnchor = graph.addItem('edge', {
id: 'edge5',
source: 'circleNode',
target: 'circleNode',
type: 'loop',
sourceAnchor: 0,
targetAnchor: 1,
loopCfg: {
position: 'bottom-right',
dist: 60,
clockwise: true,
},
style: { endArrow: true },
});
graph.addItem('edge', {
id: 'edge6',
source: 'circleNode',
target: 'circleNode',
type: 'loop',
loopCfg: {
position: 'bottom',
dist: 60,
clockwise: true,
},
style: { endArrow: true },
});
graph.addItem('edge', {
id: 'edge7',
source: 'circleNode',
target: 'circleNode',
type: 'loop',
loopCfg: {
position: 'bottom-left',
dist: 60,
clockwise: true,
},
style: { endArrow: true },
});
graph.addItem('edge', {
id: 'edge8',
source: 'circleNode',
target: 'circleNode',
type: 'loop',
loopCfg: {
position: 'left',
dist: 60,
clockwise: true,
},
style: { endArrow: true },
});
const edgeShape = edge1.getKeyShape().attr('path');
const edge2Shape = edge2.getKeyShape().attr('path');
expect(edge2Shape[0][1]).toEqual(edgeShape[0][1]);
expect(edge2Shape[0][2]).toEqual(edgeShape[0][2]);
expect(edge3.getKeyShape().attr('path')[1][0]).toEqual('C');
expect(edge3.getKeyShape().attr('path')[0][1]).toEqual(edgeShape[1][5]);
expect(edge4.getKeyShape().attr('path')[0][1]).toEqual(edge3.getKeyShape().attr('path')[1][5]);
expect(edge4.getKeyShape().attr('path')[0][2]).toEqual(edge3.getKeyShape().attr('path')[1][6]);
const pathWithAnchor = edgeWithAnchor.getKeyShape().attr('path');
expect(pathWithAnchor[0][1]).toEqual(139.5);
expect(pathWithAnchor[0][2]).toEqual(139.5);
expect(pathWithAnchor[1][0]).toEqual('C');
expect(pathWithAnchor[1][5]).toEqual(139.5);
expect(pathWithAnchor[1][6]).toEqual(160.5);
});
it('clear states', () => {
graph.clear();
const node = graph.addItem('node', { id: 'a', x: 50, y: 100, size: 50 });
graph.setItemState(node, 'a', true);
graph.setItemState(node, 'b', true);
expect(graph.findAllByState('node', 'a').length).toBe(1);
graph.clearItemStates(node, ['a', 'b']);
expect(graph.findAllByState('node', 'a').length).toBe(0);
expect(graph.findAllByState('node', 'b').length).toBe(0);
graph.setItemState(node, 'a', true);
graph.setItemState(node, 'b', true);
graph.clearItemStates('a', ['a']);
expect(graph.findAllByState('node', 'a').length).toBe(0);
expect(graph.findAllByState('node', 'b').length).toBe(1);
graph.clearItemStates(node, 'b');
expect(graph.findAllByState('node', 'b').length).toBe(0);
});
it('default node & edge style', () => {
const defaultGraph = new Graph({
container: div,
width: 500,
height: 500,
defaultNode: {
style: {
fill: 'red',
stroke: 'blue',
},
},
nodeStateStyles: {
default: {
fill: 'red',
stroke: 'blue',
},
selected: {
fill: 'green',
stroke: 'red',
},
},
defaultEdge: {
style: {
stroke: 'blue',
strokeOpacity: 0.5,
},
},
edgeStateStyles: {
default: {
stroke: 'blue',
strokeOpacity: 0.5,
},
selected: {
stroke: 'red',
strokeOpacity: 1,
},
active: {
stroke: 'green',
shadowColor: '#ccc',
},
},
});
const node = defaultGraph.addItem('node', {
id: 'node1',
x: 100,
y: 100,
type: 'rect',
label: 'test label',
style: {
stroke: '#666',
},
});
defaultGraph.on('node:click', e => {
e.item.setState(e.item, 'selected', true);
e.item.refresh();
});
defaultGraph.paint();
const keyShape = node.get('keyShape');
expect(keyShape.get('type')).toEqual('rect');
// addItem 时候 model 中的 style 会和 defaultNode 中定义的做 merge
expect(keyShape.attr('fill')).toEqual('red');
expect(keyShape.attr('stroke')).toEqual('#666');
defaultGraph.setItemState(node, 'selected', true);
expect(keyShape.attr('fill')).toEqual('green');
expect(keyShape.attr('fillStyle')).toBe(undefined);
expect(keyShape.attr('stroke')).toEqual('red');
expect(keyShape.attr('strokeStyle')).toBe(undefined);
defaultGraph.setItemState(node, 'selected', false);
// addItem 时候 model 中的 style 会和 defaultNode 中定义的做 merge
expect(keyShape.attr('fill')).toEqual('red');
expect(keyShape.attr('fillStyle')).toBe(undefined);
expect(keyShape.attr('stroke')).toEqual('#666');
expect(keyShape.attr('strokeStyle')).toBe(undefined);
defaultGraph.updateItem(node, { style: { fill: '#ccc', stroke: '#444' } });
expect(keyShape.attr('fill')).toEqual('#ccc');
defaultGraph.setItemState(node, 'selected', true);
expect(keyShape.attr('fill')).toEqual('green');
expect(keyShape.attr('fillStyle')).toBe(undefined);
expect(keyShape.attr('stroke')).toEqual('red');
expect(keyShape.attr('strokeStyle')).toBe(undefined);
defaultGraph.setItemState(node, 'selected', false);
expect(keyShape.attr('fill')).toEqual('#ccc');
expect(keyShape.attr('fillStyle')).toBe(undefined);
expect(keyShape.attr('stroke')).toEqual('#444');
expect(keyShape.attr('strokeStyle')).toBe(undefined);
defaultGraph.addItem('node', { id: 'node2' });
const edge = defaultGraph.addItem('edge', { id: 'edge', source: 'node1', target: 'node2' });
const edgeKeyShape = edge.get('keyShape');
expect(edgeKeyShape.attr('stroke')).toEqual('blue');
expect(edgeKeyShape.attr('strokeOpacity')).toEqual(0.5);
defaultGraph.setItemState(edge, 'selected', true);
expect(edgeKeyShape.attr('stroke')).toEqual('red');
expect(edgeKeyShape.attr('strokeOpacity')).toEqual(1);
defaultGraph.setItemState(edge, 'selected', false);
expect(edgeKeyShape.attr('stroke')).toEqual('blue');
expect(edgeKeyShape.attr('strokeOpacity')).toEqual(0.5);
// 测试default状态不存在的属性
expect(edgeKeyShape.attr('shadowColor')).toBe(undefined);
defaultGraph.setItemState(edge, 'active', true);
expect(edgeKeyShape.attr('stroke')).toEqual('green');
expect(edgeKeyShape.attr('shadowColor')).toEqual('#ccc');
defaultGraph.setItemState(edge, 'active', false);
expect(edgeKeyShape.attr('stroke')).toEqual('blue');
expect(edgeKeyShape.attr('shadowColor')).toBe(undefined);
defaultGraph.destroy();
});
it('graph with default cfg', () => {
const defaultGraph = new Graph({
container: div,
width: 500,
height: 500,
defaultNode: {
type: 'rect',
size: [60, 40],
color: '#ccc',
labelCfg: {
position: 'right',
offset: 5,
style: {
fontSize: 14,
fill: 'blue',
},
},
},
defaultEdge: {
type: 'cubic',
color: '#666',
},
});
const node = defaultGraph.addItem('node', { id: 'node1', x: 100, y: 150, label: '111' });
let model = node.get('model');
expect(model.id).toEqual('node1');
expect(model.x).toEqual(100);
expect(model.y).toEqual(150);
expect(model.type).toEqual('rect');
expect(model.size[0]).toEqual(60);
expect(model.size[1]).toEqual(40);
expect(model.color).toEqual('#ccc');
expect(model.labelCfg.position).toEqual('right');
expect(model.labelCfg.style.fill).toEqual('blue');
const node2 = defaultGraph.addItem('node', {
id: 'node2',
x: 150,
y: 100,
label: '222',
color: '#666',
type: 'circle',
});
model = node2.get('model');
expect(model.type).toEqual('circle');
expect(model.size[0]).toEqual(60);
expect(model.size[1]).toEqual(40);
expect(model.color).toEqual('#666');
model.size[1] = 50;
expect(model.size[1]).toEqual(50);
expect(node.get('model').size[1]).toEqual(40);
expect(model.labelCfg.position).toEqual('right');
expect(model.labelCfg.style.fill).toEqual('blue');
model.labelCfg.position = 'left';
model.labelCfg.style.fill = 'red';
expect(node.get('model').labelCfg.position).toEqual('right');
expect(node.get('model').labelCfg.style.fill).toEqual('blue');
const edge = defaultGraph.addItem('edge', {
id: 'edge',
source: 'node1',
target: 'node2',
type: 'line',
});
model = edge.get('model');
expect(model.id).toEqual('edge');
expect(model.source).toEqual('node1');
expect(model.type).toEqual('line');
expect(model.color).toEqual('#666');
defaultGraph.destroy();
expect(defaultGraph.destroyed).toBe(true);
});
});
describe('mapper fn', () => {
const graph = new Graph({
container: div,
width: 500,
height: 500,
defaultNode: {
type: 'circle',
style: {
fill: 'red',
opacity: 1,
},
},
});
it('node & edge mapper', () => {
graph.node(node => ({
id: `${node.id}Mapped`,
size: [30, 30],
label: node.id,
type: 'rect',
style: { fill: node.value === 100 ? '#666' : '#ccc' },
labelCfg: {
style: { fill: '#666' },
},
}));
graph.edge(edge => ({
id: `edge${edge.id}`,
label: edge.id,
labelCfg: {
position: 'start',
},
style: {
fill: '#ccc',
opacity: 0.5,
},
}));
const node: Item = graph.addItem('node', { id: 'node', x: 100, y: 100, value: 100 });
expect(node.get('id')).toEqual('nodeMapped');
let keyShape = node.getKeyShape();
expect(keyShape.attr('width')).toEqual(30);
expect(keyShape.attr('height')).toEqual(30);
expect(keyShape.attr('fill')).toEqual('#666');
const container = node.getContainer();
let label = container.find(element => element.get('className') === 'node-label');
expect(label).not.toBe(undefined);
expect(label.attr('text')).toEqual('node');
expect(label.attr('fill')).toEqual('#666');
graph.addItem('node', { id: 'node2', x: 200, y: 200 });
const edge = graph.addItem('edge', { id: 'edge', source: 'nodeMapped', target: 'node2Mapped' });
keyShape = edge.getKeyShape();
expect(keyShape.attr('fill')).toEqual('#ccc');
expect(keyShape.attr('opacity')).toEqual(0.5);
expect(keyShape.get('type')).toEqual('path');
label = edge.getContainer().find(element => element.get('className') === 'edge-label');
expect(label).not.toBe(undefined);
expect(label.attr('text')).toEqual('edge');
expect(label.attr('x')).toEqual(115.5);
expect(label.attr('y')).toEqual(100);
graph.updateItem(node, { value: 50 });
expect(node.getKeyShape().attr('fill')).toEqual('#ccc');
});
it('node & edge mapper with states', () => {
graph.node(node => ({
type: 'rect',
label: node.id,
style: {
fill: '#666',
opacity: 1,
},
stateStyles: {
selected: { fill: 'blue' },
custom: { fill: 'green', opacity: 0.5 },
},
}));
graph.edge(() => ({
stateStyles: {
selected: { lineWidth: 2 },
custom: { opacity: 0.5 },
},
}));
const node = graph.addItem('node', { id: 'node', x: 50, y: 50 });
let keyShape = node.getKeyShape();
expect(keyShape.attr('fill')).toEqual('#666');
expect(node.getContainer().find(element => element.get('className') === 'node-label')).not.toBe(
undefined,
);
graph.setItemState(node, 'selected', true);
expect(keyShape.attr('blue'));
graph.setItemState(node, 'custom', true);
expect(keyShape.attr('green'));
// clear all states of the item
graph.clearItemStates(node);
expect(keyShape.attr('fill')).toEqual('#666');
const edge = graph.addItem('edge', { id: 'edge2', source: 'node', target: 'node2Mapped' });
keyShape = edge.getKeyShape();
expect(keyShape.attr('stroke')).toEqual('rgb(224, 224, 224)');
expect(keyShape.attr('lineWidth')).toEqual(1);
expect(keyShape.attr('fillOpacity')).toEqual(1);
graph.setItemState(edge, 'selected', true);
expect(keyShape.attr('stroke')).toEqual('rgb(95, 149, 255)');
expect(keyShape.attr('lineWidth')).toEqual(2);
expect(keyShape.attr('fillOpacity')).toEqual(1);
graph.setItemState(edge, 'custom', true);
expect(keyShape.attr('stroke')).toEqual('rgb(95, 149, 255)');
expect(keyShape.attr('lineWidth')).toEqual(2);
expect(keyShape.attr('opacity')).toEqual(0.5);
});
});
xdescribe('plugins & layout', () => {
it('add & remove plugins', () => {
const graph = new Graph({
container: div,
height: 500,
width: 500,
});
const data = {
nodes: [
{
id: 'node',
label: 'node',
},
],
};
graph.data(data);
graph.render();
let plugins = graph.get('plugins');
expect(plugins.length).toBe(0);
const minimap = new Plugin.Minimap({
size: [200, 200],
});
graph.addPlugin(minimap);
plugins = graph.get('plugins');
expect(plugins.length).toBe(1);
graph.removePlugin(minimap);
plugins = graph.get('plugins');
expect(plugins.length).toBe(0);
graph.destroy();
expect(graph.destroyed).toBe(true);
});
});
describe('auto rotate label on edge', () => {
const graph = new Graph({
container: div,
width: 500,
height: 500,
modes: {
default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
},
});
const data = {
nodes: [
{
id: 'node1',
x: 50,
y: 50,
},
{
id: 'node2',
x: 80,
y: 150,
},
{
id: 'node3',
x: 180,
y: 120,
},
],
edges: [
{
source: 'node1',
target: 'node2',
label: 'node1-node2',
style: {
startArrow: true,
endArrow: true,
},
labelCfg: {
autoRotate: true,
},
},
{
source: 'node2',
target: 'node3',
label: 'node2-node3',
style: {
startArrow: true,
endArrow: true,
},
},
],
};
it('render', () => {
graph.data(data);
graph.render();
const edge1 = graph.getEdges()[0];
const label1 = edge1.get('group').get('children')[1];
const label1Matrix = label1.attr('matrix');
expect(label1Matrix[0]).toBe(0.2873478855664496);
expect(label1Matrix[1]).toBe(0.9578262852211201);
expect(label1Matrix[3]).toBe(-0.9578262852211201);
expect(label1Matrix[4]).toBe(0.2873478855664496);
expect(label1Matrix[6]).toBe(142.10501596029277);
expect(label1Matrix[7]).toBe(9.006502903982238);
const edge2 = graph.getEdges()[1];
const label2 = edge2.get('group').get('children')[1];
const label2Matrix = label2.attr('matrix');
expect(label2Matrix).toBe(null);
});
it('drag node', () => {
const node = graph.getNodes()[1];
graph.emit('node:dragstart', { x: 80, y: 150, item: node });
graph.emit('node:drag', { x: 200, y: 200, item: node });
graph.emit('node:dragend', { x: 200, y: 200, item: node });
const edge1 = graph.getEdges()[0];
const label1 = edge1.get('group').get('children')[1];
const label1Matrix = label1.attr('matrix');
expect(label1Matrix[0]).toBe(0.7071067811865476);
expect(label1Matrix[1]).toBe(0.7071067811865475);
expect(label1Matrix[3]).toBe(-0.7071067811865475);
expect(label1Matrix[4]).toBe(0.7071067811865476);
expect(label1Matrix[6]).toBe(124.99999999999999);
expect(label1Matrix[7]).toBe(-51.77669529663689);
const edge2 = graph.getEdges()[1];
const label2 = edge2.get('group').get('children')[1];
const label2Matrix = label2.attr('matrix');
expect(label2Matrix).toBe(null);
});
it('zoom and pan', () => {
graph.zoom(0.5);
graph.moveTo(100, 120);
const group = graph.get('group');
const groupMatrix = group.attr('matrix');
expect(groupMatrix[0]).toBe(0.5);
expect(groupMatrix[4]).toBe(0.5);
const bbox = graph.get('group').getCanvasBBox();
expect(bbox.x).toBe(100);
expect(bbox.y).toBe(120);
});
});
describe('auto rotate label on edge', () => {
const graph = new Graph({
container: div,
width: 500,
height: 500,
modes: {
default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
},
});
const data = {
nodes: [
{
id: 'node1',
x: 100,
y: 200,
},
{
id: 'node2',
x: 800,
y: 200,
},
],
edges: [
{
id: 'edge1',
target: 'node2',
source: 'node1',
},
],
};
it('downloadFullImage', () => {
graph.data(data);
graph.render();
graph.on('canvas:click', evt => {
graph.downloadFullImage('graph', {
backgroundColor: '#fff',
padding: [40, 10, 10, 10],
});
});
});
});
describe('node Neighbors', () => {
const graph = new Graph({
container: 'global-spec',
width: 500,
height: 500,
});
const data = {
nodes: [
{
id: 'A',
},
{
id: 'B',
},
{
id: 'C',
},
{
id: 'D',
},
{
id: 'E',
},
{
id: 'F',
},
{
id: 'G',
},
{
id: 'H',
},
],
edges: [
{
source: 'A',
target: 'B',
},
{
source: 'B',
target: 'C',
},
{
source: 'C',
target: 'G',
},
{
source: 'A',
target: 'D',
},
{
source: 'A',
target: 'E',
},
{
source: 'E',
target: 'F',
},
{
source: 'F',
target: 'D',
},
],
};
graph.data(data);
graph.render();
it('getSourceNeighbors', () => {
const neighbors = graph.getNeighbors('B', 'target');
expect(neighbors.length).toBe(1);
expect(neighbors[0].getID()).toEqual('C');
const neighborE = graph.getNeighbors('A', 'target');
expect(neighborE.length).toBe(3);
expect(neighborE[0].getID()).toEqual('B');
});
it('getTargetNeighbors', () => {
const neighbors = graph.getNeighbors('B', 'source');
expect(neighbors.length).toBe(1);
expect(neighbors[0].getID()).toEqual('A');
const neighborE = graph.getNeighbors('E', 'source');
expect(neighborE.length).toBe(1);
expect(neighborE[0].getID()).toEqual('A');
});
it('getNeighbors', () => {
const neighbors = graph.getNeighbors('B');
expect(neighbors.length).toBe(2);
expect(neighbors[0].getID()).toEqual('A');
expect(neighbors[1].getID()).toEqual('C');
});
});
describe('redo stack & undo stack', () => {
it('default stack is undefined', () => {
const graph = new Graph({
container: 'global-spec',
width: 500,
height: 500,
});
expect(graph.getUndoStack()).toBe(undefined);
expect(graph.getRedoStack()).toBe(undefined);
});
const graph = new Graph({
container: 'global-spec',
width: 500,
height: 500,
enabledStack: true,
});
it('undo & redo stack is not null', () => {
expect(graph.getUndoStack()).not.toBe(null);
expect(graph.getRedoStack()).not.toBe(null);
});
const data = {
nodes: [
{
id: 'node1',
label: 'node1',
x: 100,
y: 100,
},
{
id: 'node2',
label: 'node2',
x: 300,
y: 100,
},
],
};
graph.data(data);
graph.render();
it('fill undo stack', () => {
// redo 后,undo stack 有一条数据
let stackData = graph.getStackData();
let undoStack = stackData.undoStack;
let redoStack = stackData.redoStack;
expect(undoStack.length).toBe(1);
expect(undoStack[0].action).toEqual('render');
expect(undoStack[0].data.after.nodes.length).toEqual(2);
expect(redoStack.length).toBe(0);
// update 后,undo stack 中有 2 条数据,一条 render,一条 update
graph.update('node1', {
x: 120,
y: 200,
});
stackData = graph.getStackData();
undoStack = stackData.undoStack;
expect(undoStack.length).toBe(2);
let firstStackData = undoStack[0];
expect(firstStackData.action).toEqual('update');
expect(firstStackData.data.after.nodes[0].id).toEqual('node1');
expect(firstStackData.data.after.nodes[0].x).toEqual(120);
expect(firstStackData.data.after.nodes[0].y).toEqual(200);
// 执行 update 后,undo stack 中有3条数据
graph.update('node2', {
x: 120,
y: 350,
});
stackData = graph.getStackData();
undoStack = stackData.undoStack;
expect(undoStack.length).toBe(3);
firstStackData = undoStack[0];
expect(firstStackData.action).toEqual('update');
expect(firstStackData.data.after.nodes[0].id).toEqual('node2');
expect(firstStackData.data.after.nodes[0].x).toEqual(120);
expect(firstStackData.data.after.nodes[0].y).toEqual(350);
// addItem 后,undo 栈中有4条数据,1个render、2个update、1个add
graph.addItem('node', {
id: 'node3',
label: 'node3',
x: 150,
y: 150,
});
stackData = graph.getStackData();
undoStack = stackData.undoStack;
expect(undoStack.length).toBe(4);
firstStackData = undoStack[0];
expect(firstStackData.action).toEqual('add');
expect(firstStackData.data.after.nodes[0].id).toEqual('node3');
expect(firstStackData.data.after.nodes[0].x).toEqual(150);
expect(firstStackData.data.after.nodes[0].y).toEqual(150);
// hideItem 后,undo 栈中有5条数据,1个render、2个update、1个add、1个visible
graph.hideItem('node1');
stackData = graph.getStackData();
undoStack = stackData.undoStack;
expect(undoStack.length).toBe(5);
firstStackData = undoStack[0];
expect(firstStackData.action).toEqual('visible');
expect(firstStackData.data.after.nodes[0].id).toEqual('node1');
// remove 后,undo 栈中有6条数据,1个render、2个update、1个add、1个visible、1个delete
graph.remove('node2');
stackData = graph.getStackData();
undoStack = stackData.undoStack;
expect(undoStack.length).toBe(6);
firstStackData = undoStack[0];
expect(firstStackData.action).toEqual('delete');
expect(firstStackData.data.before.nodes[0].id).toEqual('node2');
expect(firstStackData.data.before.nodes[0].itemType).toEqual('node');
});
it('clear stack', () => {
graph.clearStack();
let stackData = graph.getStackData();
let undoStack = stackData.undoStack;
let redoStack = stackData.redoStack;
expect(undoStack.length).toBe(0);
expect(redoStack.length).toBe(0);
});
it('add edge', () => {
const source = graph.addItem('node', {
id: 'source',
color: '#666',
x: 50,
y: 50,
style: { lineWidth: 2, fill: '#666' },
});
const target = graph.addItem('node', {
id: 'target',
color: '#666',
x: 300,
y: 300,
type: 'rect',
style: { lineWidth: 2, fill: '#666' },
});
graph.addItem('edge', {
source: 'source',
target: 'target',
label: 'test label',
labelCfg: { autoRotate: true },
});
graph.destroy();
});
}); | the_stack |
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import cloneDeep from 'lodash/cloneDeep';
import { flatten } from 'underscore';
import React from 'react';
import { render } from '@testing-library/react';
import { ToasterContainer } from 'baseui/toast';
import * as GraphSlice from '../slice';
import { resetState } from '../../import/fileUpload/slice';
import * as Json from './constants/positive/json';
import { importJson } from '../processors/import';
import * as UiSlice from '../../ui/slice';
import * as GraphThunk from '../thunk';
import { Field, GraphData, Selection } from '../types';
import {
groupEdgesForImportation,
groupEdgesWithConfiguration,
} from '../processors/group-edges';
import { getGraph } from '../selectors';
const mockStore = configureStore([thunk]);
const getStore = () => {
const graphState = cloneDeep(GraphSlice.initialState);
const store = {
investigate: {
ui: {},
widget: {},
graph: {
present: graphState,
},
},
};
return store;
};
describe('Group Edges', () => {
let store;
beforeEach(() => {
render(<ToasterContainer />);
store = mockStore(getStore());
});
afterEach(() => {
store.clearActions();
});
describe('Group Edge For Importation', () => {
it('should perform group edge during importation', async (done) => {
// arrange
const importDataArr = [Json.simpleGraphWithGroupEdge];
const groupEdgeToggle = true;
// act
const batchDataPromises = importDataArr.map((graphData) => {
const { data } = graphData;
return importJson(
data,
GraphSlice.initialState.accessors,
groupEdgeToggle,
);
});
const graphDataArr = await Promise.all(batchDataPromises);
const [firstGraphData] = flatten(graphDataArr);
// group edge configuration arrangements
const groupEdgeConfig = {
availability: true,
toggle: groupEdgeToggle,
type: 'all',
};
firstGraphData.metadata.groupEdges = groupEdgeConfig;
const { graphData: modData, groupEdgeIds } = groupEdgesForImportation(
firstGraphData,
firstGraphData.metadata.groupEdges,
);
firstGraphData.metadata.groupEdges.ids = groupEdgeIds;
// expected results
const expectedActions = [
UiSlice.fetchBegin(),
GraphSlice.addQuery([firstGraphData]),
GraphSlice.processGraphResponse({
data: modData,
accessors: GraphSlice.initialState.accessors,
}),
UiSlice.updateToast('toast-0'),
resetState(),
UiSlice.clearError(),
UiSlice.fetchDone(),
UiSlice.closeModal(),
];
// assertions
return store
.dispatch(
GraphThunk.importJsonData(
importDataArr as any,
groupEdgeToggle,
GraphSlice.initialState.accessors,
),
)
.then(() => {
// perform assertion except process graph response due to random numbers.
setTimeout(() => {
store.getActions().forEach((actions, index) => {
if (actions.type !== 'graph/processGraphResponse') {
expect(actions).toEqual(expectedActions[index]);
}
});
done();
}, 50);
});
});
});
describe('Group Edges With Aggregation', () => {
describe('Group By All', () => {
const simpleGraphWithGroupEdge = Json.graphWithGroupEdge;
const importedGraphState = () => {
const store = {
investigate: {
ui: {},
widget: {},
graph: {
present: {
graphList: [simpleGraphWithGroupEdge],
graphFlatten: simpleGraphWithGroupEdge,
},
},
},
};
return store;
};
const store = mockStore(importedGraphState());
const graphIndex = 0;
let newGraphData: GraphData;
let newGroupEdgeIds = [];
beforeEach(() => {
const { graphList, graphFlatten } = getGraph(store.getState());
const selectedGraphList = graphList[graphIndex];
const { groupEdges } = selectedGraphList.metadata;
const { graphData, groupEdgeIds } = groupEdgesWithConfiguration(
selectedGraphList,
graphFlatten,
groupEdges,
);
newGraphData = graphData;
newGroupEdgeIds = groupEdgeIds;
});
afterEach(() => {
store.clearActions();
});
it('should display the correct title and visibility', async () => {
await store.dispatch(
GraphThunk.groupEdgesWithAggregation(graphIndex) as any,
);
store.getActions().forEach((actions) => {
const { payload, type } = actions;
if (type === 'graph/updateGraphFlatten') {
const { nodes, metadata } = payload;
expect(nodes).toEqual(newGraphData.nodes);
const { visible, title } = metadata;
expect(visible).toEqual(newGraphData.metadata.visible);
expect(title).toEqual(newGraphData.metadata.title);
}
});
});
it('should compute the correct grouped edges', async () => {
await store.dispatch(
GraphThunk.groupEdgesWithAggregation(graphIndex) as any,
);
store.getActions().forEach((actions) => {
const { payload, type } = actions;
if (type === 'graph/updateGraphFlatten') {
const { edges } = payload;
expect(edges).toEqual(newGraphData.edges);
}
});
});
it('should derive the correct group edge configurations', async () => {
await store.dispatch(
GraphThunk.groupEdgesWithAggregation(graphIndex) as any,
);
store.getActions().forEach((actions) => {
const { payload } = actions;
const { metadata, type } = payload;
if (type === 'graph/updateGraphFlatten') {
const { groupEdges } = metadata;
expect(groupEdges).toEqual(newGraphData.metadata.groupEdges);
}
});
});
it('should display the correct edge properties', async () => {
await store.dispatch(
GraphThunk.groupEdgesWithAggregation(graphIndex) as any,
);
const aggregatedEdgeFields: Field[] = [
{
analyzerType: 'INT',
format: '',
name: 'min numeric',
type: 'integer',
},
{
analyzerType: 'INT',
format: '',
name: 'max numeric',
type: 'integer',
},
{
analyzerType: 'INT',
format: '',
name: 'average numeric',
type: 'integer',
},
{
analyzerType: 'INT',
format: '',
name: 'count numeric',
type: 'integer',
},
{
analyzerType: 'INT',
format: '',
name: 'sum numeric',
type: 'integer',
},
{
analyzerType: 'STRING',
format: '',
name: 'first value',
type: 'string',
},
{
analyzerType: 'STRING',
format: '',
name: 'last value',
type: 'string',
},
{
analyzerType: 'STRING',
format: '',
name: 'most_frequent value',
type: 'string',
},
{
analyzerType: 'STRING',
format: '',
name: 'first date',
type: 'string',
},
{
analyzerType: 'STRING',
format: '',
name: 'last date',
type: 'string',
},
{
analyzerType: 'STRING',
format: '',
name: 'most_frequent date',
type: 'string',
},
];
const uniqueEdgeFields = [
...newGraphData.metadata.fields.edges,
...aggregatedEdgeFields,
];
const modData = cloneDeep(newGraphData);
Object.assign(modData.metadata.fields, {
edges: uniqueEdgeFields,
});
store.getActions().forEach((actions) => {
const { payload } = actions;
const { metadata, type } = payload;
if (type === 'graph/updateGraphFlatten') {
const { fields } = metadata;
expect(fields.edges).toEqual(modData.metadata.fields.edges);
}
});
});
it('should update valid group edge ids', async () => {
await store.dispatch(
GraphThunk.groupEdgesWithAggregation(graphIndex) as any,
);
store.getActions().forEach((actions) => {
const { payload, type } = actions;
if (type === 'graph/updateGroupEdgeIds') {
expect(newGroupEdgeIds).toEqual(payload.groupEdgeIds);
}
});
});
});
describe('Group By Types', () => {
const { graphWithGroupEdge } = Json;
const importedGraphState = () => {
const store = {
investigate: {
ui: {},
widget: {},
graph: {
present: {
graphList: [graphWithGroupEdge],
graphFlatten: graphWithGroupEdge,
},
},
},
};
return store;
};
const store = mockStore(importedGraphState());
const graphIndex = 0;
let newGraphData: GraphData;
let newGroupEdgeIds = [];
beforeEach(() => {
const { graphList, graphFlatten } = getGraph(store.getState());
const selectedGraphList = graphList[graphIndex];
const { groupEdges } = selectedGraphList.metadata;
const { graphData, groupEdgeIds } = groupEdgesWithConfiguration(
selectedGraphList,
graphFlatten,
groupEdges,
);
newGraphData = graphData;
newGroupEdgeIds = groupEdgeIds;
});
afterEach(() => {
store.clearActions();
});
it('should compute the correct grouped edges', async () => {
await store.dispatch(
GraphThunk.groupEdgesWithAggregation(graphIndex) as any,
);
store.getActions().forEach((actions) => {
const { payload, type } = actions;
if (type === 'graph/updateGraphFlatten') {
const { edges } = payload;
expect(edges).toEqual(newGraphData.edges);
}
});
});
it('should derive correct group edge configuration', async () => {
await store.dispatch(
GraphThunk.groupEdgesWithAggregation(graphIndex) as any,
);
store.getActions().forEach((actions) => {
const { payload, type } = actions;
if (type === 'graph/updateGraphFlatten') {
const { groupEdges } = payload.metadata;
expect(groupEdges).toEqual(newGraphData.metadata.groupEdges);
}
});
});
it('should update valid group edge ids', async () => {
await store.dispatch(
GraphThunk.groupEdgesWithAggregation(graphIndex) as any,
);
store.getActions().forEach((actions) => {
const { payload, type } = actions;
if (type === 'graph/updateGroupEdgeIds') {
expect(newGroupEdgeIds).toEqual(payload.groupEdgeIds);
}
});
});
});
});
describe('computeEdgeSelection', () => {
const { sampleGraphFlatten } = Json;
const aggregatedEdgeFields: Field[] = [
{
name: 'id',
format: '',
type: 'string',
analyzerType: 'string',
},
{
name: 'source',
format: '',
type: 'string',
analyzerType: 'string',
},
{
name: 'target',
format: '',
type: 'string',
analyzerType: 'string',
},
{
name: 'numeric',
format: '',
type: 'integer',
analyzerType: 'INT',
},
{
name: 'value',
format: '',
type: 'string',
analyzerType: 'STRING',
},
{
name: 'date',
format: '',
type: 'string',
analyzerType: 'STRING',
},
{
analyzerType: 'INT',
format: '',
name: 'min numeric',
type: 'integer',
},
{
analyzerType: 'INT',
format: '',
name: 'max numeric',
type: 'integer',
},
{
analyzerType: 'INT',
format: '',
name: 'average numeric',
type: 'integer',
},
{
analyzerType: 'INT',
format: '',
name: 'count numeric',
type: 'integer',
},
{
analyzerType: 'INT',
format: '',
name: 'sum numeric',
type: 'integer',
},
{
analyzerType: 'STRING',
format: '',
name: 'first value',
type: 'string',
},
{
analyzerType: 'STRING',
format: '',
name: 'last value',
type: 'string',
},
{
analyzerType: 'STRING',
format: '',
name: 'most_frequent value',
type: 'string',
},
{
analyzerType: 'STRING',
format: '',
name: 'first date',
type: 'string',
},
{
analyzerType: 'STRING',
format: '',
name: 'last date',
type: 'string',
},
{
analyzerType: 'STRING',
format: '',
name: 'most_frequent date',
type: 'string',
},
];
Object.assign((sampleGraphFlatten as any).metadata.fields, {
edges: aggregatedEdgeFields,
});
const importedGraphState = () => {
const store = {
investigate: {
ui: {},
widget: {},
graph: {
present: {
graphFlatten: sampleGraphFlatten,
edgeSelection: [
{
label: 'id',
id: 'id',
type: 'string',
selected: true,
},
{
label: 'source',
id: 'source',
type: 'string',
selected: true,
},
{
label: 'target',
id: 'target',
type: 'string',
selected: true,
},
],
},
},
},
};
return store;
};
const store = mockStore(importedGraphState());
beforeEach(() => {
store.dispatch(GraphThunk.computeEdgeSelection() as any);
});
afterEach(() => {
store.clearActions();
});
it('should append edge selection based on edge fields', () => {
const { edgeSelection, graphFlatten } = getGraph(store.getState());
const { edges: edgeFields } = graphFlatten.metadata.fields;
const computedEdgeSelection = edgeFields.map((edgeField: Field) => {
const { name, type } = edgeField;
const existingSelection = edgeSelection.find(
(selection: Selection) => selection.id === edgeField.name,
);
const isSelected: boolean = existingSelection?.selected ?? false;
return {
id: name,
label: name,
type,
selected: isSelected,
};
});
const expectedActions = [
GraphSlice.overwriteEdgeSelection(computedEdgeSelection),
];
expect(store.getActions()).toEqual(expectedActions);
});
});
}); | the_stack |
import { none, None, option, Option, some, Some } from '../index'
describe('option', () => {
it('should be a function', () => {
expect(typeof option).toBe('function')
})
it('should return `none` when null given', () => {
expect(option(null)).toBe(none)
})
it('should return `none` when undefined given', () => {
expect(option(undefined)).toBe(none)
})
it('should return `Some` instance when non-empty value given', () => {
expect(option(1)).toBeInstanceOf(Some)
expect(option('foo')).toBeInstanceOf(Some)
expect(option(new Date())).toBeInstanceOf(Some)
})
})
describe('some', () => {
it('should be a function', () => {
expect(typeof some).toBe('function')
})
it('should return `Some` instance', () => {
expect(some(null)).toBeInstanceOf(Some)
expect(some(undefined)).toBeInstanceOf(Some)
expect(some(1)).toBeInstanceOf(Some)
expect(some('bar')).toBeInstanceOf(Some)
expect(some(new Date())).toBeInstanceOf(Some)
})
})
describe('none', () => {
it('should be a `None` instance', () => {
expect(none).toBeInstanceOf(None)
})
})
describe('Some', () => {
it('should be instance of `Option`', () => {
expect(some('foo')).toBeInstanceOf(Option)
})
describe('#exists', () => {
it('should return true when the predicate return true', () => {
expect(some(1).exists(a => a === 1)).toBe(true)
})
it('should return false when the predicate return false', () => {
expect(some(1).exists(a => a !== 1)).toBe(false)
})
})
describe('#filter', () => {
const x = some('foo')
it('should return itself when the predicate return true', () => {
expect(x.filter(a => a === 'foo')).toBe(x)
})
it('should return `None` when the predicate return false', () => {
expect(x.filter(a => a === 'bar')).toBe(none)
})
})
describe('#filterNot', () => {
const x = some('foo')
it('should return `None` when the predicate return true', () => {
expect(x.filterNot(a => a === 'foo')).toBe(none)
})
it('should return itself when the predicate return false', () => {
expect(x.filterNot(a => a === 'bar')).toBe(x)
})
})
describe('#flatMap', () => {
it('should return the value that given function return', () => {
const f = (x: number): Option<string> => x === 2 ? some('foo') : none
expect(some(2).flatMap(f).get).toBe('foo')
expect(some(1).flatMap(f)).toBe(none)
})
})
describe('#fold', () => {
it('should return the value that given function return', () => {
expect(some(2).fold(() => -1)(x => x * 3)).toBe(6)
expect(some(5).fold(() => -1)(x => x * 4)).toBe(20)
})
})
describe('#forAll', () => {
it('should return true when the predicate return true', () => {
expect(some(3).forAll(x => x === 3)).toBe(true)
expect(some(8).forAll(x => x % 2 === 0)).toBe(true)
})
it('should return false when the predicate return false', () => {
expect(some(2).forAll(x => x === 3)).toBe(false)
expect(some(7).forAll(x => x % 2 === 0)).toBe(false)
})
})
describe('#forEach', () => {
it('should call the procedure', () => {
const spy = jest.fn()
some('foo').forEach(spy)
expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenCalledWith('foo')
})
})
describe('#get', () => {
it('should return the option\'s value', () => {
expect(some('bar').get).toBe('bar')
})
})
describe('#getOrElse', () => {
it('should return the option\'s value', () => {
expect(some(123).getOrElse(() => 456)).toBe(123)
})
})
describe('#getOrElseValue', () => {
it('should return the option\'s value', () => {
expect(some(123).getOrElseValue(456)).toBe(123)
})
})
describe('#isDefined', () => {
it('should be true', () => {
expect(some(new Date()).isDefined).toBe(true)
})
})
describe('#isEmpty', () => {
it('should be false', () => {
expect(some('typescript').isEmpty).toBe(false)
})
})
describe('#map', () => {
it('should return new `Some` instance with the value that the function return', () => {
const stub = jest.fn().mockReturnValueOnce(517)
expect(some(2008).map(stub).get).toBe(517)
expect(stub).toHaveBeenCalledTimes(1)
expect(stub).toHaveBeenCalledWith(2008)
})
})
describe('#match', () => {
it('should return the value that function `some` return', () => {
const ret = some(2).match({
some: x => x * 2,
none: () => 0
})
expect(ret).toBe(4)
})
it('should NOT call the `none` function', () => {
const spy = jest.fn()
some('foo').match({
some: x => x.length,
none: spy
})
expect(spy).not.toHaveBeenCalled()
})
})
describe('#nonEmpty', () => {
it('should be true', () => {
expect(some('option').nonEmpty).toBe(true)
})
})
describe('#orElse', () => {
it('should return itself', () => {
const x = some('foo')
expect(x.orElse(() => some('bar'))).toBe(x)
})
})
describe('#orElseValue', () => {
it('should return itself', () => {
const x = some('foo')
expect(x.orElseValue(some('bar'))).toBe(x)
})
})
describe('#orNull', () => {
it('should return the option\'s value', () => {
expect(some(2016).orNull).toBe(2016)
})
})
describe('#orUndefined', () => {
it('should return the option\'s value', () => {
expect(some(2019).orUndefined).toBe(2019)
})
})
describe('#toArray', () => {
it('should return an array of option\'s value', () => {
expect(some('js').toArray).toStrictEqual(['js'])
})
})
describe('#forComprehension', () => {
it('should flat map every method except the last, which is mapped', () => {
const nestedOptions = some({
anOption: some({
anotherOption: some({
finalValue: true
})
})
})
const result = nestedOptions.forComprehension(
obj => obj.anOption,
anOption => anOption.anotherOption,
anotherOption => anotherOption.finalValue
)
expect(result.get === true)
})
})
describe('#toString', () => {
it('should return the \'Some(2016)\' string when the value === 2016', () => {
expect(some(2016).toString() === 'Some(2016)')
})
it('should return the \'Some(false)\' string when the value === false', () => {
expect(some(false).toString() === 'Some(false)')
})
it('should return the \'Some(toto)\' string when the value === \'toto\'', () => {
expect(some('toto').toString() === 'Some(toto)')
})
})
})
describe('None', () => {
it('should be instance of `Option`', () => {
expect(none).toBeInstanceOf(Option)
})
describe('#exists', () => {
it('should return false', () => {
expect(none.exists(a => a === 1)).toBe(false)
expect(none.exists(a => a !== 1)).toBe(false)
})
})
describe('#filter', () => {
it('should return `none`', () => {
expect(none.filter(() => true) === none)
})
it('should NOT call the predicate', () => {
const stub = jest.fn().mockReturnValue(true)
none.filter(stub)
expect(stub).not.toHaveBeenCalled()
})
})
describe('#filterNot', () => {
it('should return `none`', () => {
expect(none.filter(() => false) === none)
})
it('should NOT call the predicate', () => {
const stub = jest.fn().mockReturnValue(false)
none.filterNot(stub)
expect(stub).not.toHaveBeenCalled()
})
})
describe('#flatMap', () => {
it('should return `none`', () => {
expect(none.flatMap(() => some(1)) === none)
})
it('should NOT call the function', () => {
const stub = jest.fn().mockReturnValue(some(1))
none.flatMap(stub)
expect(stub).not.toHaveBeenCalled()
})
})
describe('#fold', () => {
it('should return `ifEmpty`', () => {
const stub = jest.fn().mockReturnValue('foo')
expect(none.fold(stub)(() => 'bar') === 'foo')
expect(stub).toHaveBeenCalledTimes(1)
})
it('should NOT call the function', () => {
const stub = jest.fn().mockReturnValue('bar')
none.fold(() => 'foo')(stub)
expect(stub).not.toHaveBeenCalled()
})
})
describe('#forAll', () => {
it('should return true', () => {
expect(none.forAll(() => false)).toBe(true)
})
it('should NOT call the predicate', () => {
const stub = jest.fn().mockReturnValue(true)
none.forAll(stub)
expect(stub).not.toHaveBeenCalled()
})
})
describe('#forEach', () => {
it('should NOT call the procedure', () => {
const stub = jest.fn()
none.forEach(stub)
expect(stub).not.toHaveBeenCalled()
})
})
describe('#get', () => {
it('should throw an error', () => {
expect(() => none.get).toThrow('No such element')
})
})
describe('#getOrElse', () => {
it('should return the result of `defaultValue`', () => {
const option: Option<number> = none
expect(option.getOrElse(() => 123)).toBe(123)
})
})
describe('#getOrElseValue', () => {
it('should return `defaultValue`', () => {
const option: Option<number> = none
expect(option.getOrElseValue(123)).toBe(123)
})
})
describe('#isDefined', () => {
it('should be false', () => {
expect(none.isDefined).toBe(false)
})
})
describe('#isEmpty', () => {
it('should be true', () => {
expect(none.isEmpty).toBe(true)
})
})
describe('#map', () => {
it('should return `none`', () => {
expect(none.map(() => 1) === none)
})
it('should NOT call the function', () => {
const stub = jest.fn().mockReturnValue(1234)
none.map(stub)
expect(stub).not.toHaveBeenCalled()
})
})
describe('#match', () => {
it('should return the value that function `none` return', () => {
const option: Option<number> = none
const ret = option.match({
some: x => x * 2,
none: () => 1234
})
expect(ret === 1234)
})
it('should NOT call the `none` function', () => {
const spy = jest.fn()
none.match({
some: spy,
none: () => 'MOMOIRO CLOVER Z'
})
expect(spy).not.toHaveBeenCalled()
})
})
describe('#nonEmpty', () => {
it('should be false', () => {
expect(none.nonEmpty).toBe(false)
})
})
describe('#orElse', () => {
it('should return the result of `alternative`', () => {
const option: Option<string> = none
const alternative = some('foo')
expect(option.orElse(() => alternative)).toBe(alternative)
})
})
describe('#orElseValue', () => {
it('should return `alternative` value', () => {
const option: Option<string> = none
const alternative = some('foo')
expect(option.orElseValue(alternative)).toBe(alternative)
})
})
describe('#orNull', () => {
it('should return null', () => {
expect(none.orNull).toBeNull()
})
})
describe('#orUndefined', () => {
it('should return undefined', () => {
expect(none.orUndefined).toBeUndefined()
})
})
describe('#toArray', () => {
it('should return an empty array', () => {
expect(none.toArray).toStrictEqual([])
})
})
describe('#forComprehension', () => {
it('should return none', () => {
const nestedOptions = some({
anOption: some({
anotherOption: none
})
})
const result = nestedOptions.forComprehension(
obj => obj.anOption,
anOption => anOption.anotherOption,
anotherOption => anotherOption.finalValue
)
expect(result).toBe(none)
})
})
describe('#toString', () => {
it('should return \'None\'', () => {
expect(none.toString()).toBe('None')
})
})
}) | the_stack |
import {MDCFoundation} from '@material/base/foundation';
import {KEY} from '@material/dom/keyboard';
import {MDCChipActionFocusBehavior, MDCChipActionType} from '../action/constants';
import {MDCChipAnimation} from '../chip/constants';
import {MDCChipSetAdapter} from './adapter';
import {MDCChipSetAttributes, MDCChipSetEvents} from './constants';
import {ChipAnimationEvent, ChipInteractionEvent, ChipNavigationEvent, MDCChipSetInteractionEventDetail, MDCChipSetRemovalEventDetail, MDCChipSetSelectionEventDetail} from './types';
interface FocusAction {
action: MDCChipActionType;
index: number;
}
enum Operator {
INCREMENT,
DECREMENT,
}
/**
* MDCChipSetFoundation provides a foundation for all chips.
*/
export class MDCChipSetFoundation extends MDCFoundation<MDCChipSetAdapter> {
static override get defaultAdapter(): MDCChipSetAdapter {
return {
announceMessage: () => undefined,
emitEvent: () => undefined,
getAttribute: () => null,
getChipActionsAtIndex: () => [],
getChipCount: () => 0,
getChipIdAtIndex: () => '',
getChipIndexById: () => 0,
isChipFocusableAtIndex: () => false,
isChipSelectableAtIndex: () => false,
isChipSelectedAtIndex: () => false,
removeChipAtIndex: () => {},
setChipFocusAtIndex: () => undefined,
setChipSelectedAtIndex: () => undefined,
startChipAnimationAtIndex: () => undefined,
};
}
constructor(adapter?: Partial<MDCChipSetAdapter>) {
super({...MDCChipSetFoundation.defaultAdapter, ...adapter});
}
handleChipAnimation({detail}: ChipAnimationEvent) {
const {
chipID,
animation,
isComplete,
addedAnnouncement,
removedAnnouncement
} = detail;
const index = this.adapter.getChipIndexById(chipID);
if (animation === MDCChipAnimation.EXIT && isComplete) {
if (removedAnnouncement) {
this.adapter.announceMessage(removedAnnouncement);
}
this.removeAfterAnimation(index, chipID);
return;
}
if (animation === MDCChipAnimation.ENTER && isComplete && addedAnnouncement) {
this.adapter.announceMessage(addedAnnouncement);
return;
}
}
handleChipInteraction({detail}: ChipInteractionEvent) {
const {source, chipID, isSelectable, isSelected, shouldRemove} = detail;
const index = this.adapter.getChipIndexById(chipID);
if (shouldRemove) {
this.removeChip(index);
return;
}
this.focusChip(index, source, MDCChipActionFocusBehavior.FOCUSABLE);
this.adapter.emitEvent<MDCChipSetInteractionEventDetail>(
MDCChipSetEvents.INTERACTION, {
chipIndex: index,
chipID,
});
if (isSelectable) {
this.setSelection(index, source, !isSelected);
}
}
handleChipNavigation({detail}: ChipNavigationEvent) {
const {chipID, key, isRTL, source} = detail;
const index = this.adapter.getChipIndexById(chipID);
const toNextChip = (key === KEY.ARROW_RIGHT && !isRTL) ||
(key === KEY.ARROW_LEFT && isRTL);
if (toNextChip) {
// Start from the next chip so we increment the index
this.focusNextChipFrom(index + 1);
return;
}
const toPreviousChip = (key === KEY.ARROW_LEFT && !isRTL) ||
(key === KEY.ARROW_RIGHT && isRTL);
if (toPreviousChip) {
// Start from the previous chip so we decrement the index
this.focusPrevChipFrom(index - 1);
return;
}
if (key === KEY.ARROW_DOWN) {
// Start from the next chip so we increment the index
this.focusNextChipFrom(index + 1, source);
return;
}
if (key === KEY.ARROW_UP) {
// Start from the previous chip so we decrement the index
this.focusPrevChipFrom(index - 1, source);
return;
}
if (key === KEY.HOME) {
this.focusNextChipFrom(0, source);
return;
}
if (key === KEY.END) {
this.focusPrevChipFrom(this.adapter.getChipCount() - 1, source);
return;
}
}
/** Returns the unique selected indexes of the chips. */
getSelectedChipIndexes(): ReadonlySet<number> {
const selectedIndexes = new Set<number>();
const chipCount = this.adapter.getChipCount();
for (let i = 0; i < chipCount; i++) {
const actions = this.adapter.getChipActionsAtIndex(i);
for (const action of actions) {
if (this.adapter.isChipSelectedAtIndex(i, action)) {
selectedIndexes.add(i);
}
}
}
return selectedIndexes;
}
/** Sets the selected state of the chip at the given index and action. */
setChipSelected(
index: number, action: MDCChipActionType, isSelected: boolean) {
if (this.adapter.isChipSelectableAtIndex(index, action)) {
this.setSelection(index, action, isSelected);
}
}
/** Returns the selected state of the chip at the given index and action. */
isChipSelected(index: number, action: MDCChipActionType): boolean {
return this.adapter.isChipSelectedAtIndex(index, action);
}
/** Removes the chip at the given index. */
removeChip(index: number) {
// Early exit if the index is out of bounds
if (index >= this.adapter.getChipCount() || index < 0) return;
this.adapter.startChipAnimationAtIndex(index, MDCChipAnimation.EXIT);
this.adapter.emitEvent<MDCChipSetRemovalEventDetail>(
MDCChipSetEvents.REMOVAL, {
chipID: this.adapter.getChipIdAtIndex(index),
chipIndex: index,
isComplete: false,
});
}
addChip(index: number) {
// Early exit if the index is out of bounds
if (index >= this.adapter.getChipCount() || index < 0) return;
this.adapter.startChipAnimationAtIndex(index, MDCChipAnimation.ENTER);
}
/**
* Increments to find the first focusable chip.
*/
private focusNextChipFrom(
startIndex: number, targetAction?: MDCChipActionType) {
const chipCount = this.adapter.getChipCount();
for (let i = startIndex; i < chipCount; i++) {
const focusableAction =
this.getFocusableAction(i, Operator.INCREMENT, targetAction);
if (focusableAction) {
this.focusChip(
i, focusableAction,
MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED);
return;
}
}
}
/**
* Decrements to find the first focusable chip. Takes an optional target
* action that can be used to focus the first matching focusable action.
*/
private focusPrevChipFrom(
startIndex: number, targetAction?: MDCChipActionType) {
for (let i = startIndex; i > -1; i--) {
const focusableAction =
this.getFocusableAction(i, Operator.DECREMENT, targetAction);
if (focusableAction) {
this.focusChip(
i, focusableAction,
MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED);
return;
}
}
}
/** Returns the appropriate focusable action, or null if none exist. */
private getFocusableAction(
index: number, op: Operator,
targetAction?: MDCChipActionType): MDCChipActionType|null {
const actions = this.adapter.getChipActionsAtIndex(index);
// Reverse the actions if decrementing
if (op === Operator.DECREMENT) actions.reverse();
if (targetAction) {
return this.getMatchingFocusableAction(index, actions, targetAction);
}
return this.getFirstFocusableAction(index, actions);
}
/**
* Returs the first focusable action, regardless of type, or null if no
* focusable actions exist.
*/
private getFirstFocusableAction(index: number, actions: MDCChipActionType[]):
MDCChipActionType|null {
for (const action of actions) {
if (this.adapter.isChipFocusableAtIndex(index, action)) {
return action;
}
}
return null;
}
/**
* If the actions contain a focusable action that matches the target action,
* return that. Otherwise, return the first focusable action, or null if no
* focusable action exists.
*/
private getMatchingFocusableAction(
index: number, actions: MDCChipActionType[],
targetAction: MDCChipActionType): MDCChipActionType|null {
let focusableAction = null;
for (const action of actions) {
if (this.adapter.isChipFocusableAtIndex(index, action)) {
focusableAction = action;
}
// Exit and return the focusable action if it matches the target
if (focusableAction === targetAction) {
return focusableAction;
}
}
return focusableAction;
}
private focusChip(
index: number, action: MDCChipActionType,
focus: MDCChipActionFocusBehavior) {
this.adapter.setChipFocusAtIndex(index, action, focus);
const chipCount = this.adapter.getChipCount();
for (let i = 0; i < chipCount; i++) {
const actions = this.adapter.getChipActionsAtIndex(i);
for (const chipAction of actions) {
// Skip the action and index provided since we set it above
if (chipAction === action && i === index) continue;
this.adapter.setChipFocusAtIndex(
i, chipAction, MDCChipActionFocusBehavior.NOT_FOCUSABLE);
}
}
}
private supportsMultiSelect(): boolean {
return this.adapter.getAttribute(
MDCChipSetAttributes.ARIA_MULTISELECTABLE) === 'true';
}
private setSelection(
index: number, action: MDCChipActionType, isSelected: boolean) {
this.adapter.setChipSelectedAtIndex(index, action, isSelected);
this.adapter.emitEvent<MDCChipSetSelectionEventDetail>(
MDCChipSetEvents.SELECTION, {
chipID: this.adapter.getChipIdAtIndex(index),
chipIndex: index,
isSelected,
});
// Early exit if we support multi-selection
if (this.supportsMultiSelect()) {
return;
}
// If we get here, we ony support single selection. This means we need to
// unselect all chips
const chipCount = this.adapter.getChipCount();
for (let i = 0; i < chipCount; i++) {
const actions = this.adapter.getChipActionsAtIndex(i);
for (const chipAction of actions) {
// Skip the action and index provided since we set it above
if (chipAction === action && i === index) continue;
this.adapter.setChipSelectedAtIndex(i, chipAction, false);
}
}
}
private removeAfterAnimation(index: number, chipID: string) {
this.adapter.removeChipAtIndex(index);
this.adapter.emitEvent<MDCChipSetRemovalEventDetail>(
MDCChipSetEvents.REMOVAL, {
chipIndex: index,
isComplete: true,
chipID,
});
const chipCount = this.adapter.getChipCount();
// Early exit if we have an empty chip set
if (chipCount <= 0) return;
this.focusNearestFocusableAction(index);
}
/**
* Find the first focusable action by moving bidirectionally horizontally
* from the start index.
*
* Given chip set [A, B, C, D, E, F, G]...
* Let's say we remove chip "F". We don't know where the nearest focusable
* action is since any of them could be disabled. The nearest focusable
* action could be E, it could be G, it could even be A. To find it, we
* start from the source index (5 for "F" in this case) and move out
* horizontally, checking each chip at each index.
*
*/
private focusNearestFocusableAction(index: number) {
const chipCount = this.adapter.getChipCount();
let decrIndex = index;
let incrIndex = index;
while (decrIndex > -1 || incrIndex < chipCount) {
const focusAction = this.getNearestFocusableAction(
decrIndex, incrIndex, MDCChipActionType.TRAILING);
if (focusAction) {
this.focusChip(
focusAction.index, focusAction.action,
MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED);
return;
}
decrIndex--;
incrIndex++;
}
}
private getNearestFocusableAction(
decrIndex: number, incrIndex: number,
actionType?: MDCChipActionType): FocusAction|null {
const decrAction =
this.getFocusableAction(decrIndex, Operator.DECREMENT, actionType);
if (decrAction) {
return {
index: decrIndex,
action: decrAction,
};
}
// Early exit if the incremented and decremented indices are identical
if (incrIndex === decrIndex) return null;
const incrAction =
this.getFocusableAction(incrIndex, Operator.INCREMENT, actionType);
if (incrAction) {
return {
index: incrIndex,
action: incrAction,
};
}
return null;
}
}
// tslint:disable-next-line:no-default-export Needed for backward compatibility with MDC Web v0.44.0 and earlier.
export default MDCChipSetFoundation; | the_stack |
import { isNullish, isArray, assert } from '../support/Utils'
import { Element, Item, Collection } from '../data/Data'
import { Attribute } from './attributes/Attribute'
import { Attr } from './attributes/types/Attr'
import { String as Str } from './attributes/types/String'
import { Number as Num } from './attributes/types/Number'
import { Boolean as Bool } from './attributes/types/Boolean'
import { Uid } from './attributes/types/Uid'
import { Relation } from './attributes/relations/Relation'
import { HasOne } from './attributes/relations/HasOne'
import { BelongsTo } from './attributes/relations/BelongsTo'
import { HasMany } from './attributes/relations/HasMany'
import { HasManyBy } from './attributes/relations/HasManyBy'
import { MorphOne } from './attributes/relations/MorphOne'
import { MorphTo } from './attributes/relations/MorphTo'
export type ModelFields = Record<string, Attribute>
export type ModelSchemas = Record<string, ModelFields>
export type ModelRegistries = Record<string, ModelRegistry>
export type ModelRegistry = Record<string, () => Attribute>
export interface ModelOptions {
fill?: boolean
relations?: boolean
}
export class Model {
/**
* The name of the model.
*/
static entity: string
/**
* The primary key for the model.
*/
static primaryKey: string | string[] = 'id'
/**
* The schema for the model. It contains the result of the `fields`
* method or the attributes defined by decorators.
*/
protected static schemas: ModelSchemas = {}
/**
* The registry for the model. It contains predefined model schema generated
* by the property decorators and gets evaluated, and stored, on the `schema`
* property when registering models to the database.
*/
protected static registries: ModelRegistries = {}
/**
* The array of booted models.
*/
protected static booted: Record<string, boolean> = {}
/**
* Create a new model instance.
*/
constructor(attributes?: Element, options: ModelOptions = {}) {
this.$boot()
const fill = options.fill ?? true
fill && this.$fill(attributes, options)
}
/**
* Create a new model fields definition.
*/
static fields(): ModelFields {
return {}
}
/**
* Build the schema by evaluating fields and registry.
*/
protected static initializeSchema(): void {
this.schemas[this.entity] = {}
const registry = {
...this.fields(),
...this.registries[this.entity]
}
for (const key in registry) {
const attribute = registry[key]
this.schemas[this.entity][key] =
typeof attribute === 'function' ? attribute() : attribute
}
}
/**
* Set the attribute to the registry.
*/
static setRegistry<M extends typeof Model>(
this: M,
key: string,
attribute: () => Attribute
): M {
if (!this.registries[this.entity]) {
this.registries[this.entity] = {}
}
this.registries[this.entity][key] = attribute
return this
}
/**
* Clear the list of booted models so they can be re-booted.
*/
static clearBootedModels(): void {
this.booted = {}
this.schemas = {}
}
/**
* Clear registries.
*/
static clearRegistries(): void {
this.registries = {}
}
/**
* Create a new model instance without field values being populated.
*
* This method is mainly for the internal use when registering models to the
* database. Since all pre-registered models are for referencing its model
* setting during the various process, but the fields are not required.
*
* Use this method when you want create a new model instance for:
* - Registering model to a component (eg. Repository, Query, etc.)
* - Registering model to attributes (String, Has Many, etc.)
*/
static newRawInstance<M extends typeof Model>(this: M): InstanceType<M> {
return new this(undefined, { fill: false }) as InstanceType<M>
}
/**
* Create a new Attr attribute instance.
*/
static attr(value: any): Attr {
return new Attr(this.newRawInstance(), value)
}
/**
* Create a new String attribute instance.
*/
static string(value: string | null): Str {
return new Str(this.newRawInstance(), value)
}
/**
* Create a new Number attribute instance.
*/
static number(value: number | null): Num {
return new Num(this.newRawInstance(), value)
}
/**
* Create a new Boolean attribute instance.
*/
static boolean(value: boolean | null): Bool {
return new Bool(this.newRawInstance(), value)
}
/**
* Create a new Uid attribute instance.
*/
static uid(): Uid {
return new Uid(this.newRawInstance())
}
/**
* Create a new HasOne relation instance.
*/
static hasOne(
related: typeof Model,
foreignKey: string,
localKey?: string
): HasOne {
const model = this.newRawInstance()
localKey = localKey ?? model.$getLocalKey()
return new HasOne(model, related.newRawInstance(), foreignKey, localKey)
}
/**
* Create a new BelongsTo relation instance.
*/
static belongsTo(
related: typeof Model,
foreignKey: string,
ownerKey?: string
): BelongsTo {
const instance = related.newRawInstance()
ownerKey = ownerKey ?? instance.$getLocalKey()
return new BelongsTo(this.newRawInstance(), instance, foreignKey, ownerKey)
}
/**
* Create a new HasMany relation instance.
*/
static hasMany(
related: typeof Model,
foreignKey: string,
localKey?: string
): HasMany {
const model = this.newRawInstance()
localKey = localKey ?? model.$getLocalKey()
return new HasMany(model, related.newRawInstance(), foreignKey, localKey)
}
/**
* Create a new HasManyBy relation instance.
*/
static hasManyBy(
related: typeof Model,
foreignKey: string,
ownerKey?: string
): HasManyBy {
const instance = related.newRawInstance()
ownerKey = ownerKey ?? instance.$getLocalKey()
return new HasManyBy(this.newRawInstance(), instance, foreignKey, ownerKey)
}
/**
* Create a new MorphOne relation instance.
*/
static morphOne(
related: typeof Model,
id: string,
type: string,
localKey?: string
): MorphOne {
const model = this.newRawInstance()
localKey = localKey ?? model.$getLocalKey()
return new MorphOne(model, related.newRawInstance(), id, type, localKey)
}
/**
* Create a new MorphTo relation instance.
*/
static morphTo(
related: typeof Model[],
id: string,
type: string,
ownerKey: string = ''
): MorphTo {
const instance = this.newRawInstance()
const relatedModels = related.map((model) => model.newRawInstance())
return new MorphTo(instance, relatedModels, id, type, ownerKey)
}
/**
* Get the constructor for this model.
*/
$self(): typeof Model {
return this.constructor as typeof Model
}
/**
* Get the entity for this model.
*/
$entity(): string {
return this.$self().entity
}
/**
* Get the primary key for this model.
*/
$primaryKey(): string | string[] {
return this.$self().primaryKey
}
/**
* Get the model fields for this model.
*/
$fields(): ModelFields {
return this.$self().schemas[this.$entity()]
}
/**
* Create a new instance of this model. This method provides a convenient way
* to re-generate a fresh instance of this model. It's particularly useful
* during hydration through Query operations.
*/
$newInstance(attributes?: Element, options?: ModelOptions): this {
const self = this.$self()
const model = new self(attributes, options) as this
return model
}
/**
* Bootstrap this model.
*/
protected $boot(): void {
if (!this.$self().booted[this.$entity()]) {
this.$self().booted[this.$entity()] = true
this.$initializeSchema()
}
}
/**
* Build the schema by evaluating fields and registry.
*/
protected $initializeSchema(): void {
this.$self().initializeSchema()
}
/**
* Fill this model by the given attributes. Missing fields will be populated
* by the attributes default value.
*/
$fill(attributes: Element = {}, options: ModelOptions = {}): this {
const fields = this.$fields()
const fillRelation = options.relations ?? true
for (const key in fields) {
const attr = fields[key]
const value = attributes[key]
if (attr instanceof Relation && !fillRelation) {
continue
}
this.$fillField(key, attr, value)
}
return this
}
/**
* Fill the given attribute with a given value specified by the given key.
*/
protected $fillField(key: string, attr: Attribute, value: any): void {
if (value !== undefined) {
this[key] =
attr instanceof MorphTo
? attr.make(value, this[attr.getType()])
: attr.make(value)
return
}
if (this[key] === undefined) {
this[key] = attr.make()
}
}
/**
* Get the primary key field name.
*/
$getKeyName(): string | string[] {
return this.$primaryKey()
}
/**
* Get primary key value for the model. If the model has the composite key,
* it will return an array of ids.
*/
$getKey(record?: Element): string | number | (string | number)[] | null {
record = record ?? this
if (this.$hasCompositeKey()) {
return this.$getCompositeKey(record)
}
const id = record[this.$getKeyName() as string]
return isNullish(id) ? null : id
}
/**
* Check whether the model has composite key.
*/
$hasCompositeKey(): boolean {
return isArray(this.$getKeyName())
}
/**
* Get the composite key values for the given model as an array of ids.
*/
protected $getCompositeKey(record: Element): (string | number)[] | null {
let ids = [] as (string | number)[] | null
;(this.$getKeyName() as string[]).every((key) => {
const id = record[key]
if (isNullish(id)) {
ids = null
return false
}
;(ids as (string | number)[]).push(id)
return true
})
return ids === null ? null : ids
}
/**
* Get the index id of this model or for a given record.
*/
$getIndexId(record?: Element): string {
const target = record ?? this
const id = this.$getKey(target)
assert(id !== null, [
'The record is missing the primary key. If you want to persist record',
'without the primary key, please define the primary key field with the',
'`uid` attribute.'
])
return this.$stringifyId(id)
}
/**
* Stringify the given id.
*/
protected $stringifyId(id: string | number | (string | number)[]): string {
return isArray(id) ? JSON.stringify(id) : String(id)
}
/**
* Get the local key name for the model.
*/
$getLocalKey(): string {
// If the model has a composite key, we can't use it as a local key for the
// relation. The user must provide the key name explicitly, so we'll throw
// an error here.
assert(!this.$hasCompositeKey(), [
'Please provide the local key for the relationship. The model with the',
"composite key can't infer its local key."
])
return this.$getKeyName() as string
}
/**
* Get the relation instance for the given relation name.
*/
$getRelation(name: string): Relation {
const relation = this.$fields()[name]
assert(relation instanceof Relation, [
`Relationship [${name}] on model [${this.$entity()}] not found.`
])
return relation
}
/**
* Set the given relationship on the model.
*/
$setRelation(relation: string, model: Model | Model[] | null): this {
this[relation] = model
return this
}
/**
* Get the serialized model attributes.
*/
$getAttributes(): Element {
return this.$toJson(this, { relations: false })
}
/**
* Serialize this model, or the given model, as POJO.
*/
$toJson(model?: Model, options: ModelOptions = {}): Element {
model = model ?? this
const fields = model.$fields()
const withRelation = options.relations ?? true
const record: Element = {}
for (const key in fields) {
const attr = fields[key]
const value = model[key]
if (!(attr instanceof Relation)) {
record[key] = this.serializeValue(value)
continue
}
if (withRelation) {
record[key] = this.serializeRelation(value)
}
}
return record
}
/**
* Serialize the given value.
*/
protected serializeValue(value: any): any {
if (value === null) {
return null
}
if (isArray(value)) {
return this.serializeArray(value)
}
if (typeof value === 'object') {
return this.serializeObject(value)
}
return value
}
/**
* Serialize the given array to JSON.
*/
protected serializeArray(value: any[]): any[] {
return value.map((v) => this.serializeValue(v))
}
/**
* Serialize the given object to JSON.
*/
protected serializeObject(value: object): object {
const obj = {}
for (const key in value) {
obj[key] = this.serializeValue(value[key])
}
return obj
}
/**
* Serialize the given relation to JSON.
*/
protected serializeRelation(relation: Item): Element | null
protected serializeRelation(relation: Collection): Element[]
protected serializeRelation(relation: any): any {
if (relation === undefined) {
return undefined
}
if (relation === null) {
return null
}
return isArray(relation)
? relation.map((model) => model.$toJson())
: relation.$toJson()
}
/**
* Sanitize the given record. This method is similar to `$toJson` method, but
* the difference is that it doesn't instantiate the full model. The method
* is used to sanitize the record before persisting to the store.
*
* It removes fields that don't exist in the model field schema or if the
* field is relationship fields.
*
* Note that this method only sanitizes existing fields in the given record.
* It will not generate missing model fields. If you need to generate all
* model fields, use `$sanitizeAndFill` method instead.
*/
$sanitize(record: Element): Element {
const sanitizedRecord = {} as Element
const attrs = this.$fields()
for (const key in record) {
const attr = attrs[key]
const value = record[key]
if (attr !== undefined && !(attr instanceof Relation)) {
sanitizedRecord[key] = attr.make(value)
}
}
return sanitizedRecord
}
/**
* Same as `$sanitize` method, but it produces missing model fields with its
* default value.
*/
$sanitizeAndFill(record: Element): Element {
const sanitizedRecord = {} as Element
const attrs = this.$fields()
for (const key in attrs) {
const attr = attrs[key]
const value = record[key]
if (!(attr instanceof Relation)) {
sanitizedRecord[key] = attr.make(value)
}
}
return sanitizedRecord
}
} | the_stack |
export abstract class BaseNode {
abstract type: string
[name: string]: unknown;
equals(other: BaseNode, ignoredFields: Array<string> = ["span"]): boolean {
const thisKeys = new Set(Object.keys(this));
const otherKeys = new Set(Object.keys(other));
if (ignoredFields) {
for (const fieldName of ignoredFields) {
thisKeys.delete(fieldName);
otherKeys.delete(fieldName);
}
}
if (thisKeys.size !== otherKeys.size) {
return false;
}
for (const fieldName of thisKeys) {
if (!otherKeys.has(fieldName)) {
return false;
}
const thisVal = this[fieldName];
const otherVal = other[fieldName];
if (typeof thisVal !== typeof otherVal) {
return false;
}
if (thisVal instanceof Array && otherVal instanceof Array) {
if (thisVal.length !== otherVal.length) {
return false;
}
for (let i = 0; i < thisVal.length; ++i) {
if (!scalarsEqual(thisVal[i], otherVal[i], ignoredFields)) {
return false;
}
}
} else if (!scalarsEqual(thisVal, otherVal, ignoredFields)) {
return false;
}
}
return true;
}
clone(): BaseNode {
function visit(value: unknown): unknown {
if (value instanceof BaseNode) {
return value.clone();
}
if (Array.isArray(value)) {
return value.map(visit);
}
return value;
}
const clone = Object.create(this.constructor.prototype) as BaseNode;
for (const prop of Object.keys(this)) {
clone[prop] = visit(this[prop]);
}
return clone;
}
}
function scalarsEqual(
thisVal: unknown,
otherVal: unknown,
ignoredFields: Array<string>
): boolean {
if (thisVal instanceof BaseNode && otherVal instanceof BaseNode) {
return thisVal.equals(otherVal, ignoredFields);
}
return thisVal === otherVal;
}
/*
* Base class for AST nodes which can have Spans.
*/
export abstract class SyntaxNode extends BaseNode {
public span?: Span;
addSpan(start: number, end: number): void {
this.span = new Span(start, end);
}
}
export class Resource extends SyntaxNode {
public type = "Resource" as const;
public body: Array<Entry>;
constructor(body: Array<Entry> = []) {
super();
this.body = body;
}
}
export declare type Entry =
Message |
Term |
Comments |
Junk;
export class Message extends SyntaxNode {
public type = "Message" as const;
public id: Identifier;
public value: Pattern | null;
public attributes: Array<Attribute>;
public comment: Comment | null;
constructor(
id: Identifier,
value: Pattern | null = null,
attributes: Array<Attribute> = [],
comment: Comment | null = null
) {
super();
this.id = id;
this.value = value;
this.attributes = attributes;
this.comment = comment;
}
}
export class Term extends SyntaxNode {
public type = "Term" as const;
public id: Identifier;
public value: Pattern;
public attributes: Array<Attribute>;
public comment: Comment | null;
constructor(
id: Identifier,
value: Pattern,
attributes: Array<Attribute> = [],
comment: Comment | null = null
) {
super();
this.id = id;
this.value = value;
this.attributes = attributes;
this.comment = comment;
}
}
export class Pattern extends SyntaxNode {
public type = "Pattern" as const;
public elements: Array<PatternElement>;
constructor(elements: Array<PatternElement>) {
super();
this.elements = elements;
}
}
export declare type PatternElement = TextElement | Placeable;
export class TextElement extends SyntaxNode {
public type = "TextElement" as const;
public value: string;
constructor(value: string) {
super();
this.value = value;
}
}
export class Placeable extends SyntaxNode {
public type = "Placeable" as const;
public expression: Expression;
constructor(expression: Expression) {
super();
this.expression = expression;
}
}
/**
* A subset of expressions which can be used as outside of Placeables.
*/
export type InlineExpression =
StringLiteral |
NumberLiteral |
FunctionReference |
MessageReference |
TermReference |
VariableReference |
Placeable;
export declare type Expression = InlineExpression | SelectExpression;
// An abstract base class for Literals.
export abstract class BaseLiteral extends SyntaxNode {
public value: string;
constructor(value: string) {
super();
// The "value" field contains the exact contents of the literal,
// character-for-character.
this.value = value;
}
abstract parse(): { value: unknown }
}
export class StringLiteral extends BaseLiteral {
public type = "StringLiteral" as const;
parse(): { value: string } {
// Backslash backslash, backslash double quote, uHHHH, UHHHHHH.
const KNOWN_ESCAPES =
/(?:\\\\|\\"|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
function fromEscapeSequence(
match: string,
codepoint4: string,
codepoint6: string
): string {
switch (match) {
case "\\\\":
return "\\";
case "\\\"":
return "\"";
default: {
let codepoint = parseInt(codepoint4 || codepoint6, 16);
if (codepoint <= 0xD7FF || 0xE000 <= codepoint) {
// It's a Unicode scalar value.
return String.fromCodePoint(codepoint);
}
// Escape sequences reresenting surrogate code points are
// well-formed but invalid in Fluent. Replace them with U+FFFD
// REPLACEMENT CHARACTER.
return "�";
}
}
}
let value = this.value.replace(KNOWN_ESCAPES, fromEscapeSequence);
return { value };
}
}
export class NumberLiteral extends BaseLiteral {
public type = "NumberLiteral" as const;
parse(): { value: number; precision: number } {
let value = parseFloat(this.value);
let decimalPos = this.value.indexOf(".");
let precision = decimalPos > 0
? this.value.length - decimalPos - 1
: 0;
return { value, precision };
}
}
export declare type Literal = StringLiteral | NumberLiteral;
export class MessageReference extends SyntaxNode {
public type = "MessageReference" as const;
public id: Identifier;
public attribute: Identifier | null;
constructor(id: Identifier, attribute: Identifier | null = null) {
super();
this.id = id;
this.attribute = attribute;
}
}
export class TermReference extends SyntaxNode {
public type = "TermReference" as const;
public id: Identifier;
public attribute: Identifier | null;
public arguments: CallArguments | null;
constructor(
id: Identifier,
attribute: Identifier | null = null,
args: CallArguments | null = null
) {
super();
this.id = id;
this.attribute = attribute;
this.arguments = args;
}
}
export class VariableReference extends SyntaxNode {
public type = "VariableReference" as const;
public id: Identifier;
constructor(id: Identifier) {
super();
this.id = id;
}
}
export class FunctionReference extends SyntaxNode {
public type = "FunctionReference" as const;
public id: Identifier;
public arguments: CallArguments;
constructor(id: Identifier, args: CallArguments) {
super();
this.id = id;
this.arguments = args;
}
}
export class SelectExpression extends SyntaxNode {
public type = "SelectExpression" as const;
public selector: InlineExpression;
public variants: Array<Variant>;
constructor(selector: InlineExpression, variants: Array<Variant>) {
super();
this.selector = selector;
this.variants = variants;
}
}
export class CallArguments extends SyntaxNode {
public type = "CallArguments" as const;
public positional: Array<InlineExpression>;
public named: Array<NamedArgument>;
constructor(
positional: Array<InlineExpression> = [],
named: Array<NamedArgument> = []
) {
super();
this.positional = positional;
this.named = named;
}
}
export class Attribute extends SyntaxNode {
public type = "Attribute" as const;
public id: Identifier;
public value: Pattern;
constructor(id: Identifier, value: Pattern) {
super();
this.id = id;
this.value = value;
}
}
export class Variant extends SyntaxNode {
public type = "Variant" as const;
public key: Identifier | NumberLiteral;
public value: Pattern;
public default: boolean;
constructor(key: Identifier | NumberLiteral, value: Pattern, def: boolean) {
super();
this.key = key;
this.value = value;
this.default = def;
}
}
export class NamedArgument extends SyntaxNode {
public type = "NamedArgument" as const;
public name: Identifier;
public value: Literal;
constructor(name: Identifier, value: Literal) {
super();
this.name = name;
this.value = value;
}
}
export class Identifier extends SyntaxNode {
public type = "Identifier" as const;
public name: string;
constructor(name: string) {
super();
this.name = name;
}
}
export abstract class BaseComment extends SyntaxNode {
public content: string;
constructor(content: string) {
super();
this.content = content;
}
}
export class Comment extends BaseComment {
public type = "Comment" as const;
}
export class GroupComment extends BaseComment {
public type = "GroupComment" as const;
}
export class ResourceComment extends BaseComment {
public type = "ResourceComment" as const;
}
export declare type Comments =
Comment |
GroupComment |
ResourceComment;
export class Junk extends SyntaxNode {
public type = "Junk" as const;
public annotations: Array<Annotation>;
public content: string;
constructor(content: string) {
super();
this.annotations = [];
this.content = content;
}
addAnnotation(annotation: Annotation): void {
this.annotations.push(annotation);
}
}
export class Span extends BaseNode {
public type = "Span" as const;
public start: number;
public end: number;
constructor(start: number, end: number) {
super();
this.start = start;
this.end = end;
}
}
export class Annotation extends SyntaxNode {
public type = "Annotation" as const;
public code: string;
public arguments: Array<unknown>;
public message: string;
constructor(code: string, args: Array<unknown> = [], message: string) {
super();
this.code = code;
this.arguments = args;
this.message = message;
}
} | the_stack |
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule, FormControl } from '@angular/forms';
import { IconLoaderService } from '../../../index';
import { AmexioButtonComponent } from './../buttons/button.component';
import { AmexioDialpadComponent } from './dialpad.component';
import { AmexioLabelComponent } from '../label/label.component';
import { CommonIconComponent } from '../../base/components/common.icon.component';
describe('amexio-dialpad', () => {
let comp: AmexioDialpadComponent;
let fixture: ComponentFixture<AmexioDialpadComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [AmexioDialpadComponent, AmexioButtonComponent, CommonIconComponent, AmexioLabelComponent],
providers: [IconLoaderService],
});
fixture = TestBed.createComponent(AmexioDialpadComponent);
comp = fixture.componentInstance;
comp.value = '';
comp.btnArray1 = [0, 1, 2, 3, 4];
comp.btnArray2 = [5, 6, 7, 8, 9];
comp.type2Arr1 = [1, 2, 3];
comp.type2Arr2 = [4, 5, 6];
comp.type2Arr3 = [7, 8, 9];
});
it('ngOnInit() set text type password', () => {
comp.password = true;
comp.showpassword = true;
comp.ngOnInit();
expect(comp.textType).toEqual('password');
});
it('ngOnInit() set text type text', () => {
comp.password = false;
comp.showpassword = false;
comp.ngOnInit();
expect(comp.textType).toEqual('text');
});
it('ngOnInit() check minlength and maxlength and set iconfeedback to true', () => {
comp.minlen = 2;
comp.maxlen = 4;
comp.ngOnInit();
expect(comp.iconfeedback).toEqual(true);
});
it('ngOnInit() check minlength and maxlength and set iconfeedback to false', () => {
comp.minlen = 0;
comp.maxlen = 0;
comp.ngOnInit();
expect(comp.iconfeedback).toEqual(false);
});
it('ngOnInit() call generateRandomArray function and generateTyp1Arr function', () => {
comp.type = '2-rows';
comp.random = true;
comp.ngOnInit();
spyOn(comp, 'generateRandomArray').and.callThrough();
comp.randomArr = [1, 2, 3, 4, 5, 6, 7];
expect(comp.randomArr.length).toBeGreaterThanOrEqual(0);
comp.btnArray1 = [];
comp.btnArray2 = [];
expect(comp.btnArray1.length).toEqual(0);
expect(comp.btnArray2.length).toEqual(0);
spyOn(comp, 'generateTyp1Arr').and.callThrough();
});
it('ngOnInit() call generateRandomArray function and do not callgenerateTyp1Arr function', () => {
comp.type = '2-rows';
comp.random = true;
comp.ngOnInit();
spyOn(comp, 'generateRandomArray').and.callThrough();
comp.randomArr = [];
expect(comp.randomArr.length).toEqual(0);
expect(comp.btnArray1.length).not.toEqual(0);
expect(comp.btnArray2.length).not.toEqual(0);
expect(comp.generateTyp1Arr()).not.toHaveBeenCalled;
});
it('ngOnInit() check type classic and random true and call generateType2Arr function', () => {
comp.type = 'classic';
comp.random = true;
comp.ngOnInit();
spyOn(comp, 'generateType2Arr').and.callThrough();
});
it('ngOnInit() check type 2-row and random false and do not call generateType2Arr function', () => {
comp.type = '2-row';
comp.random = false;
comp.ngOnInit();
let spy = spyOn(comp, 'generateType2Arr');
expect(spy).not.toHaveBeenCalled();
});
it('generateTyp1Arr() if condition ', () => {
comp.randomArr = [0, 5, 4, 3, 2, 5, 1, 7, 8, 9];
comp.generateTyp1Arr();
comp.randomArr.forEach((element: any, index: any) => {
if ((index >= 0) && (index < 5)) {
comp.btnArray1.push(element);
} if (index > 4) {
comp.btnArray2.push(element);
}
});
});
it('generateTyp1Arr() else condition ', () => {
comp.randomArr = [];
comp.generateTyp1Arr();
comp.randomArr.forEach((element: any, index: any) => {
if ((index >= 0) && (index < 5)) {
comp.btnArray1.push(element);
} if (index > 4) {
comp.btnArray2.push(element);
}
});
});
it('getRandomNumber() if and isDuplicate true condition', () => {
const myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const num = myArray[Math.floor(Math.random() * myArray.length)];
let isDuplicate = true;
comp.randomArr = [0, 5, 4, 3, 2, 5, 1, 7, 8, 9];
comp.getRandomNumber();
expect(comp.randomArr.length).toBeGreaterThan(0);
comp.randomArr.forEach((element: any) => {
if (num === element) {
expect(isDuplicate).toEqual(true);
}
});
isDuplicate = true;
return comp.getRandomNumber();
});
it('getRandomNumber() if and isDuplicate false condition', () => {
const myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const num = myArray[Math.floor(Math.random() * myArray.length)];
let isDuplicate = false;
comp.randomArr = [0, 5, 4, 3, 2, 5, 1, 7, 8, 9];
comp.getRandomNumber();
expect(comp.randomArr.length).toBeGreaterThan(0);
comp.randomArr.forEach((element: any) => {
if (num != element) {
}
});
isDuplicate = false;
return num;
});
it('getRandomNumber() else ', () => {
const myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const num = myArray[Math.floor(Math.random() * myArray.length)];
comp.randomArr = [];
comp.getRandomNumber();
return num;
});
it('generateTyp2Arry() if condition ', () => {
comp.randomArr = [0, 5, 4, 3, 2, 5, 1, 7, 8, 9];
comp.generateTyp2Arry();
comp.randomArr.forEach((element: any, index: any) => {
if ((index >= 0) && (index < 3)) {
comp.type2Arr1.push(element);
}
if ((index > 2) && (index < 6)) {
comp.type2Arr2.push(element);
}
if ((index > 5) && (index < 9)) {
comp.type2Arr3.push(element);
}
comp.lastDigit = comp.randomArr[comp.randomArr.length - 1];
});
});
it('generateTyp2Arry() else condition ', () => {
comp.randomArr = [];
comp.generateTyp2Arry();
comp.randomArr.forEach((element: any, index: any) => {
if ((index <= 0) && (index > 3)) {
}
if ((index < 2) && (index > 6)) {
}
if ((index < 5) && (index > 9)) {
}
comp.lastDigit = comp.randomArr[comp.randomArr.length - 1];
});
});
it('validateMin() if if check ', () => {
comp.minlen = 2;
comp.value = 'abcd';
comp.isValid = true;
comp.validateMin();
expect(comp.isValid).toEqual(true);
});
it('validateMin() if if else check ', () => {
comp.minlen = 2;
comp.value = '';
comp.isValid = false;
comp.validateMin();
expect(comp.isValid).toEqual(false);
});
it('validateMin() if else check ', () => {
comp.minlen = undefined;
comp.maxlen = undefined;
comp.isValid = false;
comp.validateMin();
expect(comp.isValid).toEqual(false);
});
it('validateMax() if if check ', () => {
comp.maxlen = 4;
comp.value = 'ab';
comp.isValid = true;
comp.validateMax();
expect(comp.isValid).toEqual(true);
});
it('validateMax() if if else check ', () => {
comp.maxlen = 4;
comp.value = 'abcdef';
comp.isValid = false;
comp.validateMax();
expect(comp.isValid).toEqual(false);
});
it('validateMax() if else check ', () => {
comp.minlen = undefined;
comp.maxlen = undefined;
comp.isValid = false;
comp.validateMax();
expect(comp.isValid).toEqual(false);
});
it('validateMinMax() if if if condition ', () => {
comp.minlen = 2;
comp.maxlen = 5;
comp.value = 'abc';
comp.iconfeedback = true;
comp.isValid = true;
comp.validateMinMax();
expect(comp.isValid).toEqual(true);
comp.validateMin();
comp.validateMax();
});
it('validateMinMax() if if else condition ', () => {
comp.isValid = true;
comp.minlen = 2;
comp.maxlen = 5;
comp.value = '1';
comp.iconfeedback = true;
comp.validateMinMax();
expect(comp.isValid).toEqual(false);
comp.validateMin();
comp.validateMax();
});
it('validateMinMax() if else condition ', () => {
comp.value = '1';
comp.iconfeedback = false;
comp.validateMinMax();
let min = spyOn(comp, 'validateMin');
expect(min).not.toHaveBeenCalled();
let max = spyOn(comp, 'validateMax');
expect(max).not.toHaveBeenCalled();
});
it('getBtnData() if condition ', () => {
let data = 3;
comp.isValid = true;
comp.iconfeedback = true;
comp.getBtnData(data);
comp.value = comp.value + data;
comp.emitBtnData(data);
comp.valueChange.emit(comp.value);
comp.validateMinMax();
expect(comp.cls).toEqual('greencls');
});
it('getBtnData() else if condition ', () => {
let data = 3;
comp.isValid = false;
comp.iconfeedback = true;
comp.getBtnData(data);
comp.value = comp.value + data;
comp.emitBtnData(data);
comp.valueChange.emit(comp.value);
comp.validateMinMax();
expect(comp.cls).toEqual('redcls');
});
it('getBtnData() else condition ', () => {
let data = 3;
comp.isValid = false;
comp.iconfeedback = false;
comp.getBtnData(data);
comp.value = comp.value + data;
comp.emitBtnData(data);
comp.valueChange.emit(comp.value);
comp.validateMinMax();
expect(comp.cls).toBeUndefined();
});
it('eraseData() if condition', () => {
comp.value = '123';
comp.isValid = true;
comp.iconfeedback = true;
comp.eraseData();
let str;
str = comp.value.slice(0, -1);
comp.value = str;
expect(comp.cls).toEqual('greencls');
});
it('eraseData() else if condition', () => {
comp.value = '123';
comp.isValid = false;
comp.iconfeedback = true;
comp.eraseData();
let str;
str = comp.value.slice(0, -1);
comp.value = str;
expect(comp.cls).toEqual('redcls');
expect(comp.iconfeedback).toEqual(true);
comp.cls = 'redcls';
});
it('eraseData() if if condition', () => {
comp.value = '';
comp.isValid = true;
comp.iconfeedback = true;
comp.eraseData();
let str;
str = comp.value.slice(0, -1);
comp.value = str;
expect(comp.isValid).toBeNull();
expect(comp.cls).toEqual('redcls');
});
it('eraseData() else condition', () => {
comp.value = '123' + '123';
comp.isValid = false;
comp.iconfeedback = false;
comp.eraseData();
let str;
str = comp.value.slice(0, -1);
comp.value = str;
expect(comp.cls).toBeUndefined();
});
it('emitBtnData()', () => {
let keycode;
const obj = { key: keycode, data: comp.value };
comp.emitBtnData(keycode)
comp.onClick.emit(obj);
});
it('clearData() if condition', () => {
comp.value = '';
comp.minlen = 2;
comp.maxlen = 4;
comp.isValid = null;
const object = { data: comp.value };
comp.onClick.emit(object);
comp.valueChange.emit(comp.value);
comp.clearData();
expect(comp.isValid).toBeNull();
expect(comp.cls).toEqual('redcls');
});
it('clearData() else condition', () => {
comp.value = '';
comp.minlen = 2;
comp.maxlen = undefined;
comp.isValid = null;
const object = { data: comp.value };
comp.onClick.emit(object);
comp.valueChange.emit(comp.value);
comp.clearData();
expect(comp.cls).toEqual('redcls');
});
it('clearData() else condition', () => {
comp.value = '';
comp.minlen = undefined;
comp.maxlen = undefined;
comp.isValid = null;
const object = { data: comp.value };
comp.onClick.emit(object);
comp.valueChange.emit(comp.value);
comp.clearData();
expect(comp.cls).toEqual('nonecls');
});
it('clearData() else condition', () => {
comp.value = '';
comp.minlen = undefined;
comp.maxlen = 4;
comp.isValid = null;
const object = { data: comp.value };
comp.onClick.emit(object);
comp.valueChange.emit(comp.value);
comp.clearData();
expect(comp.cls).toEqual('redcls');
});
it('onToggle If call ', () => {
comp.toggleShow();
comp.show = true;
comp.show = !comp.show;
expect(comp.textType).toEqual('text');
})
it('onToggle else call ', () => {
comp.show = !comp.show;
comp.toggleShow();
comp.show = false;
expect(comp.textType).toEqual('password');
})
// it('generateType2Arr method randomArr less than 1 Condition', () => {
// comp.generateType2Arr();
// comp.generateRandomArray();
// comp.randomArr = [];
// // expect(comp.randomArr).toBe([]);
// expect(comp.generateTyp2Arry()).not.toHaveBeenCalled;
// })
// it('generateType2Arr method If Condition', () => {
// comp.generateType2Arr();
// comp.generateRandomArray();
// comp.randomArr = [0, 5, 4, 3, 2, 5, 1, 7, 8, 9];
// expect(comp.randomArr.length).toBeGreaterThanOrEqual(1);
// comp.type2Arr1 = [];
// comp.type2Arr2 = [];
// comp.type2Arr3 = [];
// expect(comp.type2Arr1).toEqual([]);
// expect(comp.type2Arr2).toEqual([]);
// expect(comp.type2Arr3).toEqual([]);
// expect(comp.generateTyp2Arry()).toHaveBeenCalled;
// })
}); | the_stack |
import { groups, sort, sum } from 'd3-array'
import React, { ComponentPropsWithoutRef } from 'react'
import useGetLatest from '../hooks/useGetLatest'
import useIsomorphicLayoutEffect from '../hooks/useIsomorphicLayoutEffect'
import Bar, { getPrimary } from '../seriesTypes/Bar'
import Line from '../seriesTypes/Line'
//
import {
Axis,
AxisDimensions,
AxisOptions,
AxisOptionsWithScaleType,
BuildAxisOptions,
ChartContextValue,
ChartOptions,
Datum,
GridDimensions,
RequiredChartOptions,
Series,
UserSerie,
} from '../types'
import {
materializeStyles,
getSeriesStatus,
getDatumStatus,
} from '../utils/Utils'
import buildAxisLinear from '../utils/buildAxis.linear'
import { ChartContextProvider } from '../utils/chartContext'
import AxisLinear from './AxisLinear'
// import Brush from './Brush'
import Cursors from './Cursors'
import Tooltip, { defaultTooltip } from './Tooltip'
import Voronoi from './Voronoi'
//
//
const defaultColorScheme = [
'#0f83ab',
'#faa43a',
'#fd6868',
'#53cfc9',
'#a2d925',
'#decf3f',
'#734fe9',
'#cd82ad',
'#006d92',
'#de7c00',
'#f33232',
'#3f9a80',
'#53c200',
'#d7af00',
'#4c26c9',
'#d44d99',
]
const defaultPadding = 5
function defaultChartOptions<TDatum>(
options: ChartOptions<TDatum>
): RequiredChartOptions<TDatum> {
return {
...options,
initialWidth: options.initialWidth ?? 300,
initialHeight: options.initialHeight ?? 200,
getSeriesOrder:
options.getSeriesOrder ?? ((series: Series<TDatum>[]) => series),
interactionMode: options.interactionMode ?? 'primary',
showVoronoi: options.showVoronoi ?? false,
defaultColors: options.defaultColors ?? defaultColorScheme,
useIntersectionObserver: options.useIntersectionObserver ?? true,
intersectionObserverRootMargin:
options.intersectionObserverRootMargin ?? '1000px',
primaryCursor: options.primaryCursor ?? true,
secondaryCursor: options.secondaryCursor ?? true,
padding: options.padding ?? defaultPadding,
}
}
export function Chart<TDatum>({
options: userOptions,
className,
style = {},
...rest
}: ComponentPropsWithoutRef<'div'> & { options: ChartOptions<TDatum> }) {
const options = defaultChartOptions(userOptions)
const [chartElement, setContainerElement] =
React.useState<HTMLDivElement | null>(null)
const containerEl = chartElement?.parentElement
const nearestScrollableParent = React.useMemo(() => {
const run = (el?: Element | null): Element | null => {
if (!el) {
return null
}
const grandParent = el.parentElement
if (!grandParent) {
return null
}
if (grandParent.scrollHeight > grandParent.clientHeight) {
const { overflow } = window.getComputedStyle(grandParent)
if (overflow.includes('scroll') || overflow.includes('auto')) {
return grandParent
}
}
return run(grandParent)
}
return run(containerEl)
}, [containerEl])
const [{ width, height }, setDims] = React.useState({
width: options.initialWidth,
height: options.initialHeight,
})
useIsomorphicLayoutEffect(() => {
if (containerEl) {
const computed = window.getComputedStyle(containerEl)
if (!['relative', 'absolute', 'fixed'].includes(computed.position)) {
containerEl.style.position = 'relative'
}
}
}, [containerEl])
React.useEffect(() => {
if (!containerEl) {
return
}
const observer = new ResizeObserver(() => {
const rect = containerEl?.getBoundingClientRect()
const styles = window.getComputedStyle(containerEl)
if (rect) {
setDims({
width:
rect.width -
parseInt(styles.borderLeftWidth) -
parseInt(styles.borderRightWidth),
height:
rect.height -
parseInt(styles.borderTopWidth) -
parseInt(styles.borderBottomWidth),
})
}
})
observer.observe(containerEl)
return () => {
observer.unobserve(containerEl)
}
}, [containerEl])
const [isIntersecting, setIsIntersecting] = React.useState(true)
React.useEffect(() => {
if (!containerEl || !options.useIntersectionObserver) return
let observer = new IntersectionObserver(
entries => {
for (let entry of entries) {
if (entry.isIntersecting) {
setIsIntersecting(true)
} else {
setIsIntersecting(false)
}
}
},
{
root: nearestScrollableParent,
rootMargin: options.intersectionObserverRootMargin,
}
)
observer.observe(containerEl)
return () => {
observer.unobserve(containerEl)
}
}, [
containerEl,
nearestScrollableParent,
options.intersectionObserverRootMargin,
options.useIntersectionObserver,
])
return (
<div
ref={setContainerElement}
{...rest}
className={`ReactChart ${className || ''}`}
style={{
fontFamily: 'sans-serif',
...style,
position: 'absolute',
width,
height,
}}
>
{isIntersecting ? (
<ChartInner options={options} {...{ width, height }} />
) : null}
</div>
)
}
function ChartInner<TDatum>({
options,
width,
height,
}: {
options: RequiredChartOptions<TDatum>
width: number
height: number
}) {
if (!options.primaryAxis) {
throw new Error('A primaryAxis is required')
}
if (!options.secondaryAxes.length) {
throw new Error('At least one secondaryAxis is required')
}
const primaryAxisOptions = React.useMemo((): BuildAxisOptions<TDatum> => {
const firstValue = getFirstDefinedValue(options.primaryAxis, options.data)
const axisOptions = axisOptionsWithScaleType(
options.primaryAxis,
firstValue
)
return { position: 'bottom', ...axisOptions }
}, [options.data, options.primaryAxis])
const secondaryAxesOptions = React.useMemo(() => {
return options.secondaryAxes.map(
(secondaryAxis, i): BuildAxisOptions<TDatum> => {
const firstValue = getFirstDefinedValue(secondaryAxis, options.data)
const axisOptions = axisOptionsWithScaleType(secondaryAxis, firstValue)
if (!axisOptions.elementType) {
if (primaryAxisOptions.scaleType === 'band') {
axisOptions.elementType = 'bar'
} else if (axisOptions.stacked) {
axisOptions.elementType = 'area'
}
}
if (
typeof axisOptions.stacked === 'undefined' &&
axisOptions.elementType &&
['area'].includes(axisOptions.elementType)
) {
axisOptions.stacked = true
}
return {
position: !i ? 'left' : 'right',
...axisOptions,
}
}
)
}, [options.data, options.secondaryAxes, primaryAxisOptions])
// Resolve Tooltip Option
const tooltipOptions = React.useMemo(() => {
const tooltipOptions = defaultTooltip(options?.tooltip)
tooltipOptions.groupingMode =
tooltipOptions.groupingMode ??
(() => {
if (options.interactionMode === 'closest') {
return 'single'
}
return 'primary'
})()
return tooltipOptions
}, [options.interactionMode, options?.tooltip])
options = {
...options,
tooltip: tooltipOptions,
}
//
const svgRef = React.useRef<SVGSVGElement>(null)
const getOptions = useGetLatest({ ...options, tooltip: tooltipOptions })
const axisDimensionsState = React.useState<AxisDimensions>({
left: {},
right: {},
top: {},
bottom: {},
})
const [axisDimensions] = axisDimensionsState
const isInteractingState = React.useState<boolean>(false)
const [isInteracting] = isInteractingState
const focusedDatumState = React.useState<Datum<TDatum> | null>(null)
const [focusedDatum] = focusedDatumState
// useAtom<Datum<TDatum> | null>(focusedDatumAtom)
const gridDimensions = React.useMemo((): GridDimensions => {
const padding = {
left:
typeof options.padding === 'object'
? options.padding.left ?? defaultPadding
: options.padding,
right:
typeof options.padding === 'object'
? options.padding.right ?? defaultPadding
: options.padding,
bottom:
typeof options.padding === 'object'
? options.padding.bottom ?? defaultPadding
: options.padding,
top:
typeof options.padding === 'object'
? options.padding.top ?? defaultPadding
: options.padding,
}
const left =
padding.left +
Math.max(
sum(Object.values(axisDimensions.left), d => d.width),
sum(Object.values(axisDimensions.top), d => d.paddingLeft),
sum(Object.values(axisDimensions.bottom), d => d.paddingLeft)
)
const top =
padding.top +
Math.max(
sum(Object.values(axisDimensions.top), d => d.height),
sum(Object.values(axisDimensions.left), d => d.paddingTop),
sum(Object.values(axisDimensions.right), d => d.paddingTop)
)
const right =
padding.right +
Math.max(
sum(Object.values(axisDimensions.right), d => d.width),
sum(Object.values(axisDimensions.top), d => d.paddingRight),
sum(Object.values(axisDimensions.bottom), d => d.paddingRight)
)
const bottom =
padding.bottom +
Math.max(
sum(Object.values(axisDimensions.bottom), d => d.height),
sum(Object.values(axisDimensions.left), d => d.paddingBottom),
sum(Object.values(axisDimensions.right), d => d.paddingBottom)
)
const gridWidth = Math.max(0, width - left - right)
const gridHeight = Math.max(0, height - top - bottom)
return { left, top, right, bottom, width: gridWidth, height: gridHeight }
}, [
options.padding,
axisDimensions.left,
axisDimensions.top,
axisDimensions.bottom,
axisDimensions.right,
width,
height,
])
const series = React.useMemo(() => {
const series: Series<TDatum>[] = []
const indicesByAxisId: Record<string, number> = {}
for (
let seriesIndex = 0;
seriesIndex < options.data.length;
seriesIndex++
) {
const originalSeries = options.data[seriesIndex]
const seriesId = originalSeries.id ?? seriesIndex + ''
const seriesLabel = originalSeries.label ?? `Series ${seriesIndex + 1}`
const secondaryAxisId = originalSeries.secondaryAxisId
const originalDatums = originalSeries.data
const datums = []
indicesByAxisId[`${secondaryAxisId}`] =
indicesByAxisId[`${secondaryAxisId}`] ?? 0
const seriesIndexPerAxis = indicesByAxisId[`${secondaryAxisId}`]
indicesByAxisId[`${secondaryAxisId}`]++
for (
let datumIndex = 0;
datumIndex < originalDatums.length;
datumIndex++
) {
const originalDatum = originalDatums[datumIndex]
datums[datumIndex] = {
originalSeries,
seriesIndex,
seriesIndexPerAxis,
seriesId,
seriesLabel,
secondaryAxisId,
index: datumIndex,
originalDatum,
}
}
series[seriesIndex] = {
originalSeries,
index: seriesIndex,
id: seriesId,
label: seriesLabel,
indexPerAxis: seriesIndexPerAxis,
secondaryAxisId,
datums,
}
}
return series
}, [options.data])
let allDatums = React.useMemo(() => {
return series.map(s => s.datums).flat(2)
}, [series])
const primaryAxis = React.useMemo(() => {
return buildAxisLinear<TDatum>(
true,
primaryAxisOptions,
series,
allDatums,
gridDimensions,
width,
height
)
}, [allDatums, gridDimensions, height, primaryAxisOptions, series, width])
const secondaryAxes = React.useMemo(() => {
return secondaryAxesOptions.map(secondaryAxis => {
return buildAxisLinear<TDatum>(
false,
secondaryAxis,
series,
allDatums,
gridDimensions,
width,
height
)
})
}, [allDatums, gridDimensions, height, secondaryAxesOptions, series, width])
const [datumsByInteractionGroup, datumsByTooltipGroup] = React.useMemo(() => {
if (!isInteracting) {
return [new Map(), new Map()]
}
const datumsByInteractionGroup = new Map<any, Datum<TDatum>[]>()
const datumsByTooltipGroup = new Map<any, Datum<TDatum>[]>()
const allBarAndNotStacked = secondaryAxes.every(
d => d.elementType === 'bar' && !d.stacked
)
let getInteractionPrimary = (datum: Datum<TDatum>) => {
if (allBarAndNotStacked) {
const secondaryAxis = secondaryAxes.find(
d => d.id === datum.secondaryAxisId
)!
if (secondaryAxis.elementType === 'bar' && !secondaryAxis.stacked) {
return getPrimary(datum, primaryAxis, secondaryAxis)
}
}
return datum.primaryValue
}
let getInteractionKey = (datum: Datum<TDatum>) =>
`${getInteractionPrimary(datum)}`
let getTooltipKey = (datum: Datum<TDatum>) => `${datum.primaryValue}`
if (options.interactionMode === 'closest') {
getInteractionKey = datum =>
`${getInteractionPrimary(datum)}_${datum.secondaryValue}`
}
if (tooltipOptions.groupingMode === 'single') {
getTooltipKey = datum => `${datum.primaryValue}_${datum.secondaryValue}`
} else if (tooltipOptions.groupingMode === 'secondary') {
getTooltipKey = datum => `${datum.secondaryValue}`
} else if (tooltipOptions.groupingMode === 'series') {
getTooltipKey = datum => `${datum.seriesIndex}`
}
allDatums.forEach(datum => {
const interactionKey = (getInteractionKey as Function)(datum)
const tooltipKey = (getTooltipKey as Function)(datum)
if (!datumsByInteractionGroup.has(interactionKey)) {
datumsByInteractionGroup.set(interactionKey, [])
}
if (!datumsByTooltipGroup.has(tooltipKey)) {
datumsByTooltipGroup.set(tooltipKey, [])
}
datumsByInteractionGroup.get(interactionKey)!.push(datum)
datumsByTooltipGroup.get(tooltipKey)!.push(datum)
})
datumsByInteractionGroup.forEach((value, key) => {
datumsByInteractionGroup.set(
key,
sortDatumsBySecondaryPx(value, secondaryAxes)
)
})
datumsByTooltipGroup.forEach((value, key) => {
datumsByTooltipGroup.set(
key,
sortDatumsBySecondaryPx(value, secondaryAxes)
)
})
allDatums.forEach(datum => {
const interactionKey = (getInteractionKey as Function)(datum)
const tooltipKey = (getTooltipKey as Function)(datum)
datum.interactiveGroup = datumsByInteractionGroup.get(interactionKey)
datum.tooltipGroup = datumsByTooltipGroup.get(tooltipKey)
})
return [datumsByInteractionGroup, datumsByTooltipGroup]
}, [
isInteracting,
allDatums,
options.interactionMode,
primaryAxis,
secondaryAxes,
tooltipOptions.groupingMode,
])
const getSeriesStatusStyle = React.useCallback(
(series: Series<TDatum>, focusedDatum: Datum<TDatum> | null) => {
const base = {
color:
getOptions().defaultColors[
series.index % getOptions().defaultColors.length
],
}
const status = getSeriesStatus(series, focusedDatum)
const statusStyles = getOptions().getSeriesStyle?.(series, status) ?? {}
series.style = materializeStyles(statusStyles, base)
return series.style
},
[getOptions]
)
const getDatumStatusStyle = React.useCallback(
(datum: Datum<TDatum>, focusedDatum: Datum<TDatum> | null) => {
const base = {
...series[datum.seriesIndex]?.style,
color:
getOptions().defaultColors[
datum.seriesIndex % getOptions().defaultColors.length
],
}
const status = getDatumStatus(datum as Datum<TDatum>, focusedDatum)
const statusStyles =
getOptions().getDatumStyle?.(datum as Datum<TDatum>, status) ?? {}
datum.style = materializeStyles(statusStyles, base)
return datum.style
},
[getOptions, series]
)
// Reverse the stack order for proper z-indexing
let orderedSeries = React.useMemo(() => {
const reversedSeries = [...series].reverse()
return getOptions().getSeriesOrder(reversedSeries)
}, [getOptions, series])
useIsomorphicLayoutEffect(() => {
if (
svgRef.current &&
svgRef.current.parentElement &&
!svgRef.current.parentElement.style.position
) {
svgRef.current.parentElement.style.position = 'relative'
}
})
const contextValue: ChartContextValue<TDatum> = {
getOptions,
gridDimensions,
primaryAxis,
secondaryAxes,
series,
orderedSeries,
datumsByInteractionGroup,
datumsByTooltipGroup,
width,
height,
getSeriesStatusStyle,
getDatumStatusStyle,
axisDimensionsState,
focusedDatumState,
svgRef,
isInteractingState,
}
const seriesByAxisId = React.useMemo(
() =>
sort(
groups(orderedSeries, d => d.secondaryAxisId),
([key]) => secondaryAxes.findIndex(axis => axis.id === key)
),
[orderedSeries, secondaryAxes]
)
// eslint-disable-next-line react-hooks/exhaustive-deps
let getSeriesInfo = () => ({
primaryAxis,
secondaryAxes,
seriesByAxisId,
})
let getMemoizedSeriesInfo = React.useCallback(
() => ({
primaryAxis,
secondaryAxes,
seriesByAxisId,
}),
[primaryAxis, secondaryAxes, seriesByAxisId]
)
if (options.memoizeSeries) {
getSeriesInfo = getMemoizedSeriesInfo
}
const seriesEl = React.useMemo(() => {
const { primaryAxis, secondaryAxes, seriesByAxisId } = getSeriesInfo()
return seriesByAxisId.map(([axisId, series]) => {
const secondaryAxis = secondaryAxes.find(d => d.id === axisId)
if (!secondaryAxis) {
return null
}
const { elementType } = secondaryAxis
const Component = (() => {
if (
elementType === 'line' ||
elementType === 'bubble' ||
elementType === 'area'
) {
return Line
}
if (elementType === 'bar') {
return Bar
}
throw new Error('Invalid elementType')
})()
if (primaryAxis.isInvalid || secondaryAxis.isInvalid) {
return null
}
return (
<Component
key={axisId ?? '__default__'}
primaryAxis={primaryAxis}
secondaryAxis={secondaryAxis}
series={series}
/>
)
})
}, [getSeriesInfo])
return (
<ChartContextProvider value={useGetLatest(contextValue)}>
<div>
<svg
ref={svgRef}
style={{
width,
height,
overflow: options.brush ? 'hidden' : 'visible',
}}
onClick={e => options.onClickDatum?.(focusedDatum, e)}
onMouseEnter={() => {
isInteractingState[1](true)
}}
onMouseLeave={() => {
isInteractingState[1](false)
}}
>
<g className="axes">
{[primaryAxis, ...secondaryAxes].map(axis => (
<AxisLinear key={[axis.position, axis.id].join('')} {...axis} />
))}
</g>
<g
className="Series"
style={{
pointerEvents: 'none',
}}
>
{seriesEl}
</g>
<Voronoi />
{options.renderSVG?.() ?? null}
</svg>
<Cursors />
<Tooltip />
</div>
</ChartContextProvider>
)
}
function getFirstDefinedValue<TDatum>(
options: AxisOptions<TDatum>,
data: UserSerie<TDatum>[]
) {
let firstDefinedValue: Date | number | string | undefined
data.some(serie => {
return serie.data.some(originalDatum => {
const value = options.getValue(originalDatum)
if (value !== null && typeof value !== 'undefined') {
firstDefinedValue = value
return true
}
})
})
return firstDefinedValue
}
function axisOptionsWithScaleType<TDatum>(
options: AxisOptions<TDatum>,
firstValue: Date | number | string | undefined
): AxisOptionsWithScaleType<TDatum> {
let scaleType = options.scaleType
if (!options.scaleType) {
if (typeof firstValue === 'number') {
scaleType = 'linear'
} else if (typeof (firstValue as Date)?.getMonth === 'function') {
scaleType = 'time'
} else if (
typeof firstValue === 'string' ||
typeof firstValue === 'boolean'
) {
scaleType = 'band'
} else {
throw new Error('Invalid scale type: Unable to infer type from data')
}
}
return { ...options, scaleType } as AxisOptionsWithScaleType<TDatum>
}
function sortDatumsBySecondaryPx<TDatum>(
datums: Datum<TDatum>[],
secondaryAxes: Axis<TDatum>[]
) {
return [...datums].sort((a, b) => {
const aAxis = secondaryAxes.find(d => d.id === a.secondaryAxisId)
const bAxis = secondaryAxes.find(d => d.id === b.secondaryAxisId)
const aPx =
aAxis?.scale(aAxis.stacked ? a.stackData?.[1] : a.secondaryValue) ?? NaN
const bPx =
bAxis?.scale(bAxis.stacked ? b.stackData?.[1] : b.secondaryValue) ?? NaN
return aPx - bPx
})
} | the_stack |
import ArgumentError from "openfl/errors/ArgumentError";
import IllegalOperationError from "openfl/errors/IllegalOperationError";
import StringUtil from "./../../starling/utils/StringUtil";
import Point from "openfl/geom/Point";
import Vector3D from "openfl/geom/Vector3D";
import Rectangle from "openfl/geom/Rectangle";
import MatrixUtil from "./../../starling/utils/MatrixUtil";
import MathUtil from "./../../starling/utils/MathUtil";
import Starling from "./../../starling/core/Starling";
import MissingContextError from "./../../starling/errors/MissingContextError";
import ByteArray from "openfl/utils/ByteArray";
import MeshStyle from "./../../starling/styles/MeshStyle";
import VertexDataFormat from "./../../starling/rendering/VertexDataFormat";
import VertexBuffer3D from "openfl/display3D/VertexBuffer3D";
import Matrix from "openfl/geom/Matrix";
import Matrix3D from "openfl/geom/Matrix3D";
declare namespace starling.rendering
{
/** The VertexData class manages a raw list of vertex information, allowing direct upload
* to Stage3D vertex buffers. <em>You only have to work with this class if you're writing
* your own rendering code (e.g. if you create custom display objects).</em>
*
* <p>To render objects with Stage3D, you have to organize vertices and indices in so-called
* vertex- and index-buffers. Vertex buffers store the coordinates of the vertices that make
* up an object; index buffers reference those vertices to determine which vertices spawn
* up triangles. Those buffers reside in graphics memory and can be accessed very
* efficiently by the GPU.</p>
*
* <p>Before you can move data into the buffers, you have to set it up in conventional
* memory — that is, in a Vector or a ByteArray. Since it's quite cumbersome to manually
* create and manipulate those data structures, the IndexData and VertexData classes provide
* a simple way to do just that. The data is stored sequentially (one vertex or index after
* the other) so that it can easily be uploaded to a buffer.</p>
*
* <strong>Vertex Format</strong>
*
* <p>The VertexData class requires a custom format string on initialization, or an instance
* of the VertexDataFormat class. Here is an example:</p>
*
* <listing>
* vertexData = new VertexData("position:number2, color:bytes4");
* vertexData.setPoint(0, "position", 320, 480);
* vertexData.setColor(0, "color", 0xff00ff);</listing>
*
* <p>This instance is set up with two attributes: "position" and "color". The keywords
* after the colons depict the format and size of the data that each property uses; in this
* case, we store two floats for the position (for the x- and y-coordinates) and four
* bytes for the color. Please refer to the VertexDataFormat documentation for details.</p>
*
* <p>The attribute names are then used to read and write data to the respective positions
* inside a vertex. Furthermore, they come in handy when copying data from one VertexData
* instance to another: attributes with equal name and data format may be transferred between
* different VertexData objects, even when they contain different sets of attributes or have
* a different layout.</p>
*
* <strong>Colors</strong>
*
* <p>Always use the format <code>bytes4</code> for color data. The color access methods
* expect that format, since it's the most efficient way to store color data. Furthermore,
* you should always include the string "color" (or "Color") in the name of color data;
* that way, it will be recognized as such and will always have its value pre-filled with
* pure white at full opacity.</p>
*
* <strong>Premultiplied Alpha</strong>
*
* <p>Per default, color values are stored with premultiplied alpha values, which
* means that the <code>rgb</code> values were multiplied with the <code>alpha</code> values
* before saving them. You can change this behavior with the <code>premultipliedAlpha</code>
* property.</p>
*
* <p>Beware: with premultiplied alpha, the alpha value always affects the resolution of
* the RGB channels. A small alpha value results in a lower accuracy of the other channels,
* and if the alpha value reaches zero, the color information is lost altogether.</p>
*
* <strong>Tinting</strong>
*
* <p>Some low-end hardware is very sensitive when it comes to fragment shader complexity.
* Thus, Starling optimizes shaders for non-tinted meshes. The VertexData class keeps track
* of its <code>tinted</code>-state, at least at a basic level: whenever you change color
* or alpha value of a vertex to something different than white (<code>0xffffff</code>) with
* full alpha (<code>1.0</code>), the <code>tinted</code> property is enabled.</p>
*
* <p>However, that value is not entirely accurate: when you restore the color of just a
* range of vertices, or copy just a subset of vertices to another instance, the property
* might wrongfully indicate a tinted mesh. If that's the case, you can either call
* <code>updateTinted()</code> or assign a custom value to the <code>tinted</code>-property.
* </p>
*
* @see VertexDataFormat
* @see IndexData
*/
export class VertexData
{
/** Creates an empty VertexData object with the given format and initial capacity.
*
* @param format
*
* Either a VertexDataFormat instance or a String that describes the data format.
* Refer to the VertexDataFormat class for more information. If you don't pass a format,
* the default <code>MeshStyle.VERTEX_FORMAT</code> will be used.
*
* @param initialCapacity
*
* The initial capacity affects just the way the internal ByteArray is allocated, not the
* <code>numIndices</code> value, which will always be zero when the constructor returns.
* The reason for this behavior is the peculiar way in which ByteArrays organize their
* memory:
*
* <p>The first time you set the length of a ByteArray, it will adhere to that:
* a ByteArray with length 20 will take up 20 bytes (plus some overhead). When you change
* it to a smaller length, it will stick to the original value, e.g. with a length of 10
* it will still take up 20 bytes. However, now comes the weird part: change it to
* anything above the original length, and it will allocate 4096 bytes!</p>
*
* <p>Thus, be sure to always make a generous educated guess, depending on the planned
* usage of your VertexData instances.</p>
*/
public constructor(format?:any, initialCapacity?:number);
/** Explicitly frees up the memory used by the ByteArray. */
public clear():void;
/** Creates a duplicate of the vertex data object. */
public clone():VertexData;
/** Copies the vertex data (or a range of it, defined by 'vertexID' and 'numVertices')
* of this instance to another vertex data object, starting at a certain target index.
* If the target is not big enough, it will be resized to fit all the new vertices.
*
* <p>If you pass a non-null matrix, the 2D position of each vertex will be transformed
* by that matrix before storing it in the target object. (The position being either an
* attribute with the name "position" or, if such an attribute is not found, the first
* attribute of each vertex. It must consist of two float values containing the x- and
* y-coordinates of the vertex.)</p>
*
* <p>Source and target do not need to have the exact same format. Only properties that
* exist in the target will be copied; others will be ignored. If a property with the
* same name but a different format exists in the target, an exception will be raised.
* Beware, though, that the copy-operation becomes much more expensive when the formats
* differ.</p>
*/
public copyTo(target:VertexData, targetVertexID?:number, matrix?:Matrix,
vertexID?:number, numVertices?:number):void;
/** Copies a specific attribute of all contained vertices (or a range of them, defined by
* 'vertexID' and 'numVertices') to another VertexData instance. Beware that both name
* and format of the attribute must be identical in source and target.
* If the target is not big enough, it will be resized to fit all the new vertices.
*
* <p>If you pass a non-null matrix, the specified attribute will be transformed by
* that matrix before storing it in the target object. It must consist of two float
* values.</p>
*/
public copyAttributeTo(target:VertexData, targetVertexID:number, attrName:string,
matrix?:Matrix, vertexID?:number, numVertices?:number):void;
/** Optimizes the ByteArray so that it has exactly the required capacity, without
* wasting any memory. If your VertexData object grows larger than the initial capacity
* you passed to the constructor, call this method to avoid the 4k memory problem. */
public trim():void;
/** Returns a string representation of the VertexData object,
* describing both its format and size. */
public toString():string;
// read / write attributes
/** Reads an unsigned integer value from the specified vertex and attribute. */
public getUnsignedInt(vertexID:number, attrName:string):number;
/** Writes an unsigned integer value to the specified vertex and attribute. */
public setUnsignedInt(vertexID:number, attrName:string, value:number):void;
/** Reads a float value from the specified vertex and attribute. */
public getFloat(vertexID:number, attrName:string):number;
/** Writes a float value to the specified vertex and attribute. */
public setFloat(vertexID:number, attrName:string, value:number):void;
/** Reads a Point from the specified vertex and attribute. */
public getPoint(vertexID:number, attrName:string, out?:Point):Point;
/** Writes the given coordinates to the specified vertex and attribute. */
public setPoint(vertexID:number, attrName:string, x:number, y:number):void;
/** Reads a Vector3D from the specified vertex and attribute.
* The 'w' property of the Vector3D is ignored. */
public getPoint3D(vertexID:number, attrName:string, out?:Vector3D):Vector3D;
/** Writes the given coordinates to the specified vertex and attribute. */
public setPoint3D(vertexID:number, attrName:string, x:number, y:number, z:number):void;
/** Reads a Vector3D from the specified vertex and attribute, including the fourth
* coordinate ('w'). */
public getPoint4D(vertexID:number, attrName:string, out?:Vector3D):Vector3D;
/** Writes the given coordinates to the specified vertex and attribute. */
public setPoint4D(vertexID:number, attrName:string,
x:number, y:number, z:number, w?:number):void;
/** Reads an RGB color from the specified vertex and attribute (no alpha). */
public getColor(vertexID:number, attrName?:string):number;
/** Writes the RGB color to the specified vertex and attribute (alpha is not changed). */
public setColor(vertexID:number, attrName:string, color:number):void;
/** Reads the alpha value from the specified vertex and attribute. */
public getAlpha(vertexID:number, attrName?:string):number;
/** Writes the given alpha value to the specified vertex and attribute (range 0-1). */
public setAlpha(vertexID:number, attrName:string, alpha:number):void;
// bounds helpers
/** Calculates the bounds of the 2D vertex positions identified by the given name.
* The positions may optionally be transformed by a matrix before calculating the bounds.
* If you pass an 'out' Rectangle, the result will be stored in this rectangle
* instead of creating a new object. To use all vertices for the calculation, set
* 'numVertices' to '-1'. */
public getBounds(attrName?:string, matrix?:Matrix,
vertexID?:number, numVertices?:number, out?:Rectangle):Rectangle;
/** Calculates the bounds of the 2D vertex positions identified by the given name,
* projected into the XY-plane of a certain 3D space as they appear from the given
* camera position. Note that 'camPos' is expected in the target coordinate system
* (the same that the XY-plane lies in).
*
* <p>If you pass an 'out' Rectangle, the result will be stored in this rectangle
* instead of creating a new object. To use all vertices for the calculation, set
* 'numVertices' to '-1'.</p> */
public getBoundsProjected(attrName:string, matrix:Matrix3D,
camPos:Vector3D, vertexID?:number, numVertices?:number,
out?:Rectangle):Rectangle;
/** Indicates if color attributes should be stored premultiplied with the alpha value.
* Changing this value does <strong>not</strong> modify any existing color data.
* If you want that, use the <code>setPremultipliedAlpha</code> method instead.
* @default true */
public premultipliedAlpha:boolean;
protected get_premultipliedAlpha():boolean;
protected set_premultipliedAlpha(value:boolean):boolean;
/** Changes the way alpha and color values are stored. Optionally updates all existing
* vertices. */
public setPremultipliedAlpha(value:boolean, updateData:boolean):void;
/** Updates the <code>tinted</code> property from the actual color data. This might make
* sense after copying part of a tinted VertexData instance to another, since not each
* color value is checked in the process. An instance is tinted if any vertices have a
* non-white color or are not fully opaque. */
public updateTinted(attrName?:string):boolean;
// modify multiple attributes
/** Transforms the 2D positions of subsequent vertices by multiplication with a
* transformation matrix. */
public transformPoints(attrName:string, matrix:Matrix,
vertexID?:number, numVertices?:number):void;
/** Translates the 2D positions of subsequent vertices by a certain offset. */
public translatePoints(attrName:string, deltaX:number, deltaY:number,
vertexID?:number, numVertices?:number):void;
/** Multiplies the alpha values of subsequent vertices by a certain factor. */
public scaleAlphas(attrName:string, factor:number,
vertexID?:number, numVertices?:number):void;
/** Writes the given RGB and alpha values to the specified vertices. */
public colorize(attrName?:string, color?:number, alpha?:number,
vertexID?:number, numVertices?:number):void;
// format helpers
/** Returns the format of a certain vertex attribute, identified by its name.
* Typical values: <code>float1, float2, float3, float4, bytes4</code>. */
public getFormat(attrName:string):string;
/** Returns the size of a certain vertex attribute in bytes. */
public getSize(attrName:string):number;
/** Returns the size of a certain vertex attribute in 32 bit units. */
public getSizeIn32Bits(attrName:string):number;
/** Returns the offset (in bytes) of an attribute within a vertex. */
public getOffset(attrName:string):number;
/** Returns the offset (in 32 bit units) of an attribute within a vertex. */
public getOffsetIn32Bits(attrName:string):number;
/** Indicates if the VertexData instances contains an attribute with the specified name. */
public hasAttribute(attrName:string):boolean;
// VertexBuffer helpers
/** Creates a vertex buffer object with the right size to fit the complete data.
* Optionally, the current data is uploaded right away. */
public createVertexBuffer(upload?:boolean,
bufferUsage?:string):VertexBuffer3D;
/** Uploads the complete data (or a section of it) to the given vertex buffer. */
public uploadToVertexBuffer(buffer:VertexBuffer3D, vertexID?:number, numVertices?:number):void;
// properties
/** The total number of vertices. If you make the object bigger, it will be filled up with
* <code>1.0</code> for all alpha values and zero for everything else. */
public numVertices:number;
protected get_numVertices():number;
protected set_numVertices(value:number):number;
/** The raw vertex data; not a copy! */
public readonly rawData:ByteArray;
protected get_rawData():ByteArray;
/** The format that describes the attributes of each vertex.
* When you assign a different format, the raw data will be converted accordingly,
* i.e. attributes with the same name will still point to the same data.
* New properties will be filled up with zeros (except for colors, which will be
* initialized with an alpha value of 1.0). As a side-effect, the instance will also
* be trimmed. */
public format:VertexDataFormat;
protected get_format():VertexDataFormat;
protected set_format(value:VertexDataFormat):VertexDataFormat;
/** Indicates if the mesh contains any vertices that are not white or not fully opaque.
* If <code>false</code> (and the value wasn't modified manually), the result is 100%
* accurate; <code>true</code> represents just an educated guess. To be entirely sure,
* you may call <code>updateTinted()</code>.
*/
public tinted:boolean;
protected get_tinted():boolean;
protected set_tinted(value:boolean):boolean;
/** The format string that describes the attributes of each vertex. */
public readonly formatString:string;
protected get_formatString():string;
/** The size (in bytes) of each vertex. */
public readonly vertexSize:number;
protected get_vertexSize():number;
/** The size (in 32 bit units) of each vertex. */
public readonly vertexSizeIn32Bits:number;
protected get_vertexSizeIn32Bits():number;
/** The size (in bytes) of the raw vertex data. */
public readonly size:number;
protected get_size():number;
/** The size (in 32 bit units) of the raw vertex data. */
public readonly sizeIn32Bits:number;
protected get_sizeIn32Bits():number;
}
}
export default starling.rendering.VertexData; | the_stack |
import { Api } from "./api";
import * as crypto from 'crypto';
import { container } from "tsyringe";
import { ProfileData } from "../types/profile";
import { ApiResponse } from "../types/api";
import { Hwid, SelectedProfile, MarketFilter, BarterItem, ItemDestination } from "../types/tarkov";
import { Localization } from "../types/i18n";
import { TraderData } from "../types/traders";
import { ItemsList } from "../types/item";
import { Weather } from "../types/weather";
import { Messages } from "../types/messages";
import { MessageAttachements } from "../types/MessageAttachements";
import { MarketOffers, OfferData } from "../types/market";
import { Profile } from "./profile";
import { Trader } from "./trader";
import { MarketOffer } from "./marketOffer";
/** Tarkov API Wrapper */
export class Tarkov {
private hwid: Hwid; // Users HWID
private api: Api; // Our HTTP Client for making requests
profiles: ProfileData[] = [];
profile!: Profile;
localization!: Localization;
itemsList!: ItemsList;
traders!: Trader[];
constructor(hwid?: Hwid) {
// Use the provided hwid or generate one
this.hwid = hwid || this.generateHwid();
// Setup our API
this.api = container.resolve(Api);
this.profile = container.resolve(Profile);
console.log(` > Initialized Tarkov API Wrapper`);
console.log(` > HWID: ${this.hwid}`);
console.log(` > Launcher Version: ${this.launcherVersion}`);
console.log(` > Game Version: ${this.gameVersion}`);
}
/*
* Getter/Setters
*/
get launcherVersion() {
return this.api.launcherVersion;
}
get gameVersion() {
return this.api.gameVersion;
}
get session() {
return this.api.session;
}
set session(session) {
this.api.session = session;
}
/*
* Public Functions
*/
/**
* Login to tarkov
* @async
* @param {string} email Your Tarkov account email
* @param {string} password Your Tarkov account password
* @param {string} [twoFactor] 2FA Code sent to your account email
*/
/**
* Create a new tarkov session
*
* @param email - Tarkov Account Email
* @param password - Tarkov Account Password
* @param twoFactor - twoFactor activation code sent to your account email
*
* @beta
*/
public async login(email: string, password: string, twoFactor?: string) {
const hash = crypto.createHash('md5').update(password).digest('hex');
if (twoFactor !== undefined) {
try {
await this.activateHardware(email, twoFactor);
} catch ({ err, errmsg }) {
return console.error(`[API Error] ${errmsg}`);
}
}
const body = JSON.stringify({
email,
pass: hash,
hwCode: this.hwid,
captcha: null,
});
try {
const result: ApiResponse = await this.api.launcher.post('launcher/login', {
searchParams: {
launcherVersion: this.launcherVersion,
branch: 'live',
},
body,
});
if (result.body.err === 0) {
await this.exchangeAccessToken(result.body.data.access_token);
return;
}
console.error(`[API Error] ${result.body.errmsg}`);
return result.body;
} catch (error) {
console.log('[Login] ', error);
}
}
/**
* Get an array of profiles
* @async
*/
public async getProfiles(): Promise<ProfileData[]> {
const result: ApiResponse<ProfileData[]> = await this.api.prod.post('client/game/profile/list');
this.profiles = result.body.data;
return this.profiles;
}
/**
* Select a profile
* @async
* @param {string} profileId
*/
public async selectProfile(profile: ProfileData): Promise<Profile> {
this.profile.selectProfile(profile);
return this.profile;
}
/**
* Get all traders
* @async
*/
public async getTraders(): Promise<Trader[]> {
const result: ApiResponse<TraderData[]> = await this.api.trading.post('client/trading/api/getTradersList');
this.traders = result.body.data.map(trader => new Trader(trader));
return this.traders;
}
/**
* Get a trader by id
* @async
* @param {string} id The traders ID
*/
public async getTrader(id: string): Promise<TraderData> {
const result: ApiResponse<TraderData> = await this.api.trading.post(`client/trading/api/getTrader/${id}`);
return new Trader(result.body.data);
}
/**
* Get all messages
* @async
* @param {number} [type] The type of message to filter by - OPTIONAL
*/
public async getMessages(type?: number): Promise<Messages[]> {
const result: ApiResponse<Messages[]> = await this.api.prod.post('client/mail/dialog/list');
// Optionally filter by type
if (type) {
return result.body.data.filter((dialog: Messages) => dialog.type === type);
}
return result.body.data;
}
/**
* Get message attachements
* @async
* @param {string} id Message ID to get attachements for
*/
public async getMessageAttachments(id?: string): Promise<MessageAttachements> {
const body = JSON.stringify({ dialogId: id });
const result: ApiResponse<MessageAttachements> = await this.api.prod.post('client/mail/dialog/getAllAttachments', { body });
return result.body.data;
}
/**
* Get all items
* @async
*/
public async getItems(): Promise<ItemsList> {
const body = JSON.stringify({ crc : 0 });
const result: ApiResponse<ItemsList> = await this.api.prod.post('client/items', { body });
this.itemsList = result.body.data;
return result.body.data;
}
/**
* Get weather
* @async
*/
public async getWeather(): Promise<Weather> {
const result: ApiResponse<Weather> = await this.api.prod.post('client/weather');
return result.body.data;
}
/**
* Keep Alive
* @async
*/
public async keepAlive(): Promise<any> {
const result: ApiResponse<any> = await this.api.prod.post('client/game/keepalive');
return result.body.data;
}
/**
* get localization table
* @async
* @param {string} language language code, example: English = en
*/
public async getI18n(language: string): Promise<Localization> {
const result: ApiResponse<Localization> = await this.api.prod.post(`client/locale/${language}`);
this.localization = result.body.data;
return result.body.data;
}
/**
* Search offers from Flea Market.
* @async
* @param {Number} page - starting page, example: start searching from page 0.
* @param {Number} limit - limit how many results to show. Example: 15.
* @param {MarketFilter} filter - Market Filter
* @param {Number} [filter.sortType=5] - ID = 0, Barter = 2, Mechant Rating = 3, Price = 5, Expiry = 6
* @param {Number} [filter.sortDirection=0] - Ascending = 0, Descending = 1
* @param {Number} [filter.currency=0] - All = 0, RUB = 1, USD = 2, EUR = 3
* @param {Number} [filter.priceFrom=0] - Won't show offers below this number
* @param {Number} [filter.priceTo=0] - Won't show offers higher than this number
* @param {Number} [filter.quantityFrom=0] - Minimum items in the stack
* @param {Number} [filter.quantityTo=0] - Max number of items in the stack
* @param {Number} [filter.conditionFrom=0] - Won't show offers where item won't match minium condition
* @param {Number} [filter.conditionTo=100] - Won't show offers where item won't match maxium condition
* @param {Boolean} [filter.oneHourExpiration=false] - Show items that are expiring within hour
* @param {Boolean} [filter.removeBartering=true] - Should we hide bartering offers
* @param {Number} [filter.offerOwnerType=0] - Any owner = 0, Listed by traders = 1, Listed by players = 2
* @param {Boolean} [filter.onlyFunctional=true] - Hide weapons that are inoperable
* @param {String} [filter.handbookId=""] - item id you are searching
* @param {String} [filter.linkedSearchId=""] - if you are performing linked item search, include item id
* @param {String} [filter.neededSearchId=""] - if you are performing required item search, include item id
*/
public async searchMarket(page: number, limit: number, filter: MarketFilter): Promise<MarketOffers> {
if (!filter.handbookId) throw new Error('handbookId is required');
const body = JSON.stringify({
page: page,
limit: limit,
sortType: 5,
sortDirection: 0,
currency: 0,
priceFrom: 0,
priceTo: 0,
quantityFrom: 0,
quantityTo: 0,
conditionFrom: 0,
conditionTo: 100,
oneHourExpiration: false,
removeBartering: true,
offerOwnerType: 0,
onlyFunctional: true,
updateOfferCount: true,
handbookId: '',
linkedSearchId: '',
neededSearchId: '',
tm: 1,
...filter,
});
const result: ApiResponse<MarketOffers> = await this.api.ragfair.post('client/ragfair/find', { body });
return {
...result.body.data,
offers: [
...result.body.data.offers.map((offer: OfferData) => new MarketOffer(offer)),
]
};
}
/**
* Offer a list of items
* @async
* @param {array} items Array of item ids
* @param {object} requirements
* @param {String} requirement._tpl - Items schema id. Also known _tpl. Ex. Rouble_id
* @param {String} requirement.price - On what price you want to sell.
* @param {boolean} sellAll - Sell all in one piece. Default false
*/
public async offerItem(items: string[], requirements: { _tpl: string, price: number }, sellAll: boolean = false): Promise<any> {
const body = JSON.stringify({
data: [{
Action: "RagFairAddOffer",
sellInOnePiece: sellAll,
items: items, // Array of item_ids
requirements: [{
_tpl: requirements._tpl,
count: requirements.price,
level: 0,
side: 0,
onlyFunctional: false,
}],
tm: 2,
}],
});
const result: ApiResponse<any> = await this.api.prod.post('client/game/profile/items/moving', { body });
// Update our local inventory state
this.profile.handleChanges(result.body.data.items);
return result.body.data;
}
/**
* Stack an item
* UNTESTED
* @async
* @param {string} fromId id of item to move
* @param {string} toId id of item to move onto
*/
public async stackItem(fromId: string, toId: string): Promise<any> {
const body = JSON.stringify({
data: [{
Action: 'Merge',
item: fromId,
with: toId,
}],
tm: 2,
});
const result: ApiResponse<any> = await this.api.prod.post('client/game/profile/items/moving', { body });
return result.body.data;
}
/**
* Move an item
* UNTESTED
* @async
* @param {string} itemId collect item id
* @param {ItemDestination} destination - info where to move. {id, container, location:{x,y,r} }
* @param {String} destination.id - item id where we move
* @param {String} [destination.container="hideout"] - 'main' = container, 'hideout' = stash
* @param {Object} [destination.location={x:0,y:0,r:0}] - {x, y, r} x & y locations, topleft is 0,0. r = 0 or 1.
*/
public async moveItem(itemId: string, destination: ItemDestination): Promise<any> {
const body = JSON.stringify({
data: [{
Action: 'Move',
item: itemId,
to: {
container: 'hideout', // main = container, hideout = stash
location: { x: 0, y: 0, r: 0 }, // try to put to topleft if empty
...destination,
},
}],
tm: 2,
});
const result: ApiResponse<any> = await this.api.prod.post('client/game/profile/items/moving', { body });
return result.body.data;
}
/**
* Collect an item
* UNTESTED
* @async
* @param {string} itemId collect item id
* @param {string} stashId players stashId. Get it from `profile.inventory.stash`
* @param {string} attachmentId attachments id
*/
public async collectItem(itemId: string, stashId: string, attachmentId: string): Promise<any> {
const body = JSON.stringify({
data: [{
Action: 'Move',
item: itemId,
to:{
id: stashId,
container: 'hideout',
},
fromOwner: {
id: attachmentId,
type: 'Mail'
}
}]
});
const result: ApiResponse<any> = await this.api.prod.post('client/game/profile/items/moving', { body });
return result.body.data;
}
/*
* Private Functions
*/
/**
* Exchanges the access token for a session id
* @param {string} access_token JWT from @login
*/
private async exchangeAccessToken(access_token: string) {
const body = JSON.stringify({
version: {
major: this.gameVersion,
game: 'live',
backend: '6'
},
hwCode: this.hwid,
});
try {
const result: ApiResponse = await this.api.prod.post('launcher/game/start', {
searchParams: {
launcherVersion: this.launcherVersion,
branch: 'live',
},
headers: {
Host: 'prod.escapefromtarkov.com',
'Authorization': access_token,
},
body,
unityAgent: false,
appVersion: false,
requestId: false,
bsgSession: false,
} as any);
if (result.body.err === 0) {
this.session = result.body.data;
console.log('New session started!', this.session);
return true;
}
throw `Invalid status code ${result.body.err}`;
} catch (error) {
throw error;
}
}
/**
* Activates a new HWID with a 2fa code
* @param {string} email Account Email
* @param {string} twoFactor 2FA Code from email
*/
private async activateHardware(email: string, twoFactor: string) {
const body = JSON.stringify({
email,
hwCode: this.hwid,
activateCode: twoFactor,
});
try {
await this.api.launcher.post('launcher/hardwareCode/activate', {
searchParams: {
launcherVersion: this.launcherVersion,
},
body,
});
} catch (error) {
console.log(`Activate Hardware Failed`);
throw error;
}
}
// TODO: move this to a HWID class
private generateHwid(): Hwid {
const random_hash = () => {
let hash = crypto.createHash('sha1').update(Math.random().toString()).digest('hex');
return hash;
}
const short_hash = () => {
let hash = random_hash();
return hash.substring(0, hash.length - 8);
}
return `#1-${random_hash()}:${random_hash()}:${random_hash()}-${random_hash()}-${random_hash()}-${random_hash()}-${random_hash()}-${short_hash()}`;
}
} | the_stack |
import {
Client,
Others,
Presence,
LiveObject,
LiveMap,
Room,
User,
LiveList,
} from "@liveblocks/client";
import * as React from "react";
type LiveblocksProviderProps = {
children: React.ReactNode;
client: Client;
};
const ClientContext = React.createContext<Client | null>(null);
const RoomContext = React.createContext<Room | null>(null);
/**
* Makes the Liveblocks client available in the component hierarchy below.
*/
export function LiveblocksProvider(props: LiveblocksProviderProps) {
return (
<ClientContext.Provider value={props.client}>
{props.children}
</ClientContext.Provider>
);
}
/**
* Returns the client of the nearest LiveblocksProvider above in the react component tree
*/
function useClient(): Client {
const client = React.useContext(ClientContext);
if (client == null) {
throw new Error("LiveblocksProvider is missing from the react tree");
}
return client;
}
type RoomProviderProps<TStorageRoot> = {
/**
* The id of the room you want to connect to
*/
id: string;
/**
* A callback that let you initialize the default presence when entering the room.
* If ommited, the default presence will be an empty object
*/
defaultPresence?: () => Presence;
defaultStorageRoot?: TStorageRoot;
children: React.ReactNode;
};
/**
* Makes a Room available in the component hierarchy below.
* When this component is unmounted, the current user leave the room.
* That means that you can't have 2 RoomProvider with the same room id in your react tree.
*/
export function RoomProvider<TStorageRoot>({
id,
children,
defaultPresence,
defaultStorageRoot,
}: RoomProviderProps<TStorageRoot>) {
const client = useClient();
React.useEffect(() => {
return () => {
client.leave(id);
};
}, [client, id]);
const room =
client.getRoom(id) ||
client.enter(id, {
defaultPresence: defaultPresence ? defaultPresence() : undefined,
defaultStorageRoot,
});
return <RoomContext.Provider value={room}>{children}</RoomContext.Provider>;
}
/**
* Returns the room of the nearest RoomProvider above in the react component tree
*/
export function useRoom() {
const room = React.useContext(RoomContext);
if (room == null) {
throw new Error("RoomProvider is missing from the react tree");
}
return room;
}
/**
* Returns the presence of the current user of the current room, and a function to update it.
* It is different from the setState function returned by the useState hook from React.
* You don't need to pass the full presence object to update it.
*
* @example
* import { useMyPresence } from "@liveblocks/react";
*
* const [myPresence, updateMyPresence] = useMyPresence();
* updateMyPresence({ x: 0 });
* updateMyPresence({ y: 0 });
*
* // At the next render, "myPresence" will be equal to "{ x: 0, y: 0 }"
*/
export function useMyPresence<T extends Presence>(): [
T,
(overrides: Partial<T>, options?: { addToHistory: boolean }) => void
] {
const room = useRoom();
const presence = room.getPresence<T>();
const [, update] = React.useState(0);
React.useEffect(() => {
function onMyPresenceChange() {
update((x) => x + 1);
}
const unsubscribe = room.subscribe("my-presence", onMyPresenceChange);
return () => {
unsubscribe();
};
}, [room]);
const setPresence = React.useCallback(
(overrides: Partial<T>, options?: { addToHistory: boolean }) =>
room.updatePresence(overrides, options),
[room]
);
return [presence, setPresence];
}
/**
* useUpdateMyPresence is similar to useMyPresence but it only returns the function to update the current user presence.
* If you don't use the current user presence in your component, but you need to update it (e.g. live cursor), it's better to use useUpdateMyPresence to avoid unnecessary renders.
*
* @example
* import { useUpdateMyPresence } from "@liveblocks/react";
*
* const updateMyPresence = useUpdateMyPresence();
* updateMyPresence({ x: 0 });
* updateMyPresence({ y: 0 });
*
* // At the next render, the presence of the current user will be equal to "{ x: 0, y: 0 }"
*/
export function useUpdateMyPresence<T extends Presence>(): (
overrides: Partial<T>,
options?: { addToHistory: boolean }
) => void {
const room = useRoom();
return React.useCallback(
(overrides: Partial<T>, options?: { addToHistory: boolean }) => {
room.updatePresence(overrides, options);
},
[room]
);
}
/**
* Returns an object that lets you get information about all the the users currently connected in the room.
*
* @example
* import { useOthers } from "@liveblocks/react";
*
* const others = useOthers();
*
* // Example to map all cursors in jsx
* {
* others.map(({ connectionId, presence }) => {
* if(presence == null || presence.cursor == null) {
* return null;
* }
* return <Cursor key={connectionId} cursor={presence.cursor} />
* })
* }
*/
export function useOthers<T extends Presence>(): Others<T> {
const room = useRoom();
const [, update] = React.useState(0);
React.useEffect(() => {
function onOthersChange() {
update((x) => x + 1);
}
const unsubscribe = room.subscribe("others", onOthersChange);
return () => {
unsubscribe();
};
}, [room]);
return room.getOthers();
}
/**
* Returns a callback that lets you broadcast custom events to other users in the room
*
* @example
* import { useBroadcastEvent } from "@liveblocks/react";
*
* const broadcast = useBroadcastEvent();
*
* broadcast({ type: "CUSTOM_EVENT", data: { x: 0, y: 0 } });
*/
export function useBroadcastEvent() {
const room = useRoom();
return React.useCallback(
(event: any) => {
room.broadcastEvent(event);
},
[room]
);
}
/**
* useErrorListener is a react hook that lets you react to potential room connection errors.
*
* @example
* import { useErrorListener } from "@liveblocks/react";
*
* useErrorListener(er => {
* console.error(er);
* })
*/
export function useErrorListener(callback: (er: Error) => void) {
const room = useRoom();
const savedCallback = React.useRef(callback);
React.useEffect(() => {
savedCallback.current = callback;
});
React.useEffect(() => {
const listener = (e: Error) => savedCallback.current(e);
const unsubscribe = room.subscribe("error", listener);
return () => {
unsubscribe();
};
}, [room]);
}
/**
* useEventListener is a react hook that lets you react to event broadcasted by other users in the room.
*
* @example
* import { useEventListener } from "@liveblocks/react";
*
* useEventListener(({ connectionId, event }) => {
* if (event.type === "CUSTOM_EVENT") {
* // Do something
* }
* });
*/
export function useEventListener<TEvent>(
callback: ({
connectionId,
event,
}: {
connectionId: number;
event: TEvent;
}) => void
) {
const room = useRoom();
const savedCallback = React.useRef(callback);
React.useEffect(() => {
savedCallback.current = callback;
});
React.useEffect(() => {
const listener = (e: { connectionId: number; event: TEvent }) =>
savedCallback.current(e);
const unsubscribe = room.subscribe("event", listener);
return () => {
unsubscribe();
};
}, [room]);
}
/**
* Gets the current user once it is connected to the room.
*
* @example
* import { useSelf } from "@liveblocks/react";
*
* const user = useSelf();
*/
export function useSelf<
TPresence extends Presence = Presence
>(): User<TPresence> | null {
const room = useRoom();
const [, update] = React.useState(0);
React.useEffect(() => {
function onChange() {
update((x) => x + 1);
}
const unsubscribePresence = room.subscribe("my-presence", onChange);
const unsubscribeConnection = room.subscribe("connection", onChange);
return () => {
unsubscribePresence();
unsubscribeConnection();
};
}, [room]);
return room.getSelf<TPresence>();
}
export function useStorage<TRoot extends Record<string, any>>(): [
root: LiveObject<TRoot> | null
] {
const room = useRoom();
const [root, setState] = React.useState<LiveObject<TRoot> | null>(null);
React.useEffect(() => {
let didCancel = false;
async function fetchStorage() {
const storage = await room.getStorage<TRoot>();
if (!didCancel) {
setState(storage.root);
}
}
fetchStorage();
return () => {
didCancel = true;
};
}, [room]);
return [root];
}
/**
* Returns the LiveMap associated with the provided key. If the LiveMap does not exist, a new empty LiveMap will be created.
* The hook triggers a re-render if the LiveMap is updated, however it does not triggers a re-render if a nested CRDT is updated.
*
* @param key The storage key associated with the LiveMap
* @param entries Optional entries that are used to create the LiveMap for the first time
* @returns null while the storage is loading, otherwise, returns the LiveMap associated to the storage
*
* @example
* const emptyMap = useMap("mapA");
* const mapWithItems = useMap("mapB", [["keyA", "valueA"], ["keyB", "valueB"]]);
*/
export function useMap<TKey extends string, TValue>(
key: string,
entries?: readonly (readonly [TKey, TValue])[] | null | undefined
): LiveMap<TKey, TValue> | null {
return useCrdt(key, new LiveMap(entries));
}
/**
* Returns the LiveList associated with the provided key. If the LiveList does not exist, a new LiveList will be created.
* The hook triggers a re-render if the LiveList is updated, however it does not triggers a re-render if a nested CRDT is updated.
*
* @param key The storage key associated with the LiveList
* @param items Optional items that are used to create the LiveList for the first time
* @returns null while the storage is loading, otherwise, returns the LiveList associated to the storage
*
* @example
* const emptyList = useList("listA");
* const listWithItems = useList("listB", ["a", "b", "c"]);
*/
export function useList<TValue>(
key: string,
items?: TValue[] | undefined
): LiveList<TValue> | null {
return useCrdt<LiveList<TValue>>(key, new LiveList(items));
}
/**
* Returns the LiveObject associated with the provided key. If the LiveObject does not exist, it will be created with the initialData parameter.
* The hook triggers a re-render if the LiveObject is updated, however it does not triggers a re-render if a nested CRDT is updated.
*
* @param key The storage key associated with the LiveObject
* @param initialData Optional data that is used to create the LiveObject for the first time
* @returns null while the storage is loading, otherwise, returns the LveObject associated to the storage
*
* @example
* const object = useObject("obj", {
* company: "Liveblocks",
* website: "https://liveblocks.io"
* });
*/
export function useObject<TData>(
key: string,
initialData?: TData
): LiveObject<TData> | null {
return useCrdt(key, new LiveObject(initialData));
}
/**
* Returns a function that undoes the last operation executed by the current client.
* It does not impact operations made by other clients.
*/
export function useUndo() {
return useRoom().history.undo;
}
/**
* Returns a function that redoes the last operation executed by the current client.
* It does not impact operations made by other clients.
*/
export function useRedo() {
return useRoom().history.redo;
}
/**
* Returns a function that batches modifications made during the given function.
* All the modifications are sent to other clients in a single message.
* All the modifications are merged in a single history item (undo/redo).
* All the subscribers are called only after the batch is over.
*/
export function useBatch() {
return useRoom().batch;
}
/**
* Returns the room.history
*/
export function useHistory() {
return useRoom().history;
}
function useCrdt<T>(key: string, initialCrdt: T): T | null {
const room = useRoom();
const [root] = useStorage();
const [, setCount] = React.useState(0);
React.useEffect(() => {
if (root == null) {
return;
}
let crdt: null | T = root.get(key);
if (crdt == null) {
crdt = initialCrdt;
root.set(key, crdt);
}
function onChange() {
setCount((x) => x + 1);
}
function onRootChange() {
const newCrdt = root!.get(key);
if (newCrdt !== crdt) {
unsubscribeCrdt();
crdt = newCrdt;
unsubscribeCrdt = room.subscribe(
crdt as any /* AbstractCrdt */,
onChange
);
setCount((x) => x + 1);
}
}
let unsubscribeCrdt = room.subscribe(
crdt as any /* AbstractCrdt */,
onChange
);
const unsubscribeRoot = room.subscribe(
root as any /* AbstractCrdt */,
onRootChange
);
setCount((x) => x + 1);
return () => {
unsubscribeRoot();
unsubscribeCrdt();
};
}, [root, room]);
return root?.get(key) ?? null;
} | the_stack |
import {
Allure,
AllureConfig,
AllureGroup,
AllureRuntime,
AllureStep,
AllureTest,
AttachmentOptions,
ContentType,
ExecutableItemWrapper,
isPromise,
Label,
LabelName,
Stage,
Status,
StepInterface,
} from "allure-js-commons";
// eslint-disable-next-line no-undef
import FailedExpectation = jasmine.FailedExpectation;
const findAnyError = (expectations?: FailedExpectation[]): FailedExpectation | null => {
expectations = expectations || [];
if (expectations.length > 0) {
return expectations[0];
}
return null;
};
const findMessageAboutThrow = (expectations?: FailedExpectation[]): FailedExpectation | null => {
for (const e of expectations || []) {
if (e.matcherName === "") {
return e;
}
}
return null;
};
/* eslint-disable no-shadow */
enum SpecStatus {
PASSED = "passed",
FAILED = "failed",
BROKEN = "broken",
PENDING = "pending",
DISABLED = "disabled",
EXCLUDED = "excluded",
}
type JasmineBeforeAfterFn = (action: (done: DoneFn) => void, timeout?: number) => void;
export class JasmineAllureReporter implements jasmine.CustomReporter {
private groupStack: AllureGroup[] = [];
private labelStack: Label[][] = [[]];
private runningTest: AllureTest | null = null;
private stepStack: AllureStep[] = [];
private runningExecutable: ExecutableItemWrapper | null = null;
private readonly runtime: AllureRuntime;
constructor(config: AllureConfig) {
this.runtime = new AllureRuntime(config);
this.installHooks();
}
get currentGroup(): AllureGroup {
const currentGroup = this.getCurrentGroup();
if (currentGroup === null) {
throw new Error("No active group");
}
return currentGroup;
}
getInterface(): Allure {
return new JasmineAllureInterface(this, this.runtime);
}
get currentTest(): AllureTest {
if (this.runningTest === null) {
throw new Error("No active test");
}
return this.runningTest;
}
get currentExecutable(): ExecutableItemWrapper | null {
return this.runningExecutable;
}
writeAttachment(
content: Buffer | string,
options: ContentType | string | AttachmentOptions,
): string {
return this.runtime.writeAttachment(content, options);
}
jasmineStarted(): void {}
suiteStarted(suite: jasmine.CustomReporterResult): void {
const name = suite.description;
const group = (this.getCurrentGroup() || this.runtime).startGroup(name);
this.groupStack.push(group);
this.labelStack.push([]);
}
specStarted(spec: jasmine.CustomReporterResult): void {
let currentGroup = this.getCurrentGroup();
if (currentGroup === null) {
throw new Error("No active suite");
}
currentGroup = currentGroup.startGroup("Test wrapper"); // needed to hold beforeEach/AfterEach
this.groupStack.push(currentGroup);
const name = spec.description;
const allureTest = currentGroup.startTest(name);
if (this.runningTest != null) {
throw new Error("Test is starting before other ended!");
}
this.runningTest = allureTest;
allureTest.fullName = spec.fullName;
allureTest.historyId = spec.fullName;
allureTest.stage = Stage.RUNNING;
// ignore wrapper, index + 1
if (this.groupStack.length > 1) {
allureTest.addLabel(LabelName.PARENT_SUITE, this.groupStack[0].name);
}
if (this.groupStack.length > 2) {
allureTest.addLabel(LabelName.SUITE, this.groupStack[1].name);
}
if (this.groupStack.length > 3) {
allureTest.addLabel(LabelName.SUB_SUITE, this.groupStack[2].name);
}
// TODO: if more depth add something to test name
for (const labels of this.labelStack) {
for (const label of labels) {
allureTest.addLabel(label.name, label.value);
}
}
}
specDone(spec: jasmine.CustomReporterResult): void {
const currentTest = this.runningTest;
if (currentTest === null) {
throw new Error("specDone while no test is running");
}
if (this.stepStack.length > 0) {
// eslint-disable-next-line no-console
console.error("Allure reporter issue: step stack is not empty on specDone");
for (const step of this.stepStack.reverse()) {
step.status = Status.BROKEN;
step.stage = Stage.INTERRUPTED;
step.detailsMessage = "Timeout";
step.endStep();
}
this.stepStack = [];
}
if (
spec.status === SpecStatus.PENDING ||
spec.status === SpecStatus.DISABLED ||
spec.status === SpecStatus.EXCLUDED
) {
currentTest.status = Status.SKIPPED;
currentTest.stage = Stage.PENDING;
currentTest.detailsMessage = spec.pendingReason || "Suite disabled";
}
currentTest.stage = Stage.FINISHED;
if (spec.status === SpecStatus.PASSED) {
currentTest.status = Status.PASSED;
}
if (spec.status === SpecStatus.BROKEN) {
currentTest.status = Status.BROKEN;
}
if (spec.status === SpecStatus.FAILED) {
currentTest.status = Status.FAILED;
}
const exceptionInfo =
findMessageAboutThrow(spec.failedExpectations) || findAnyError(spec.failedExpectations);
if (exceptionInfo !== null) {
currentTest.detailsMessage = exceptionInfo.message;
currentTest.detailsTrace = exceptionInfo.stack;
}
currentTest.endTest();
this.runningTest = null;
this.currentGroup.endGroup(); // popping the test wrapper
this.groupStack.pop();
}
suiteDone(): void {
if (this.runningTest !== null) {
// eslint-disable-next-line no-console
console.error("Allure reporter issue: running test on suiteDone");
}
const currentGroup = this.getCurrentGroup();
if (currentGroup === null) {
throw new Error("No active suite");
}
currentGroup.endGroup();
this.groupStack.pop();
this.labelStack.pop();
}
jasmineDone(): void {}
addLabel(name: string, value: string): void {
if (this.labelStack.length) {
this.labelStack[this.labelStack.length - 1].push({ name, value });
}
}
pushStep(step: AllureStep): void {
this.stepStack.push(step);
}
popStep(): void {
this.stepStack.pop();
}
get currentStep(): AllureStep | null {
if (this.stepStack.length > 0) {
return this.stepStack[this.stepStack.length - 1];
}
return null;
}
private getCurrentGroup(): AllureGroup | null {
if (this.groupStack.length === 0) {
return null;
}
return this.groupStack[this.groupStack.length - 1];
}
private installHooks(): void {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const reporter = this;
// eslint-disable-next-line no-eval
const jasmineBeforeAll: JasmineBeforeAfterFn = eval("global.beforeAll");
// eslint-disable-next-line no-eval
const jasmineAfterAll: JasmineBeforeAfterFn = eval("global.afterAll");
// eslint-disable-next-line no-eval
const jasmineBeforeEach: JasmineBeforeAfterFn = eval("global.beforeEach");
// eslint-disable-next-line no-eval
const jasmineAfterEach: JasmineBeforeAfterFn = eval("global.afterEach");
const makeWrapperAll = (wrapped: JasmineBeforeAfterFn, fun: () => ExecutableItemWrapper) => {
return (action: (done: DoneFn) => void, timeout?: number): void => {
wrapped((done) => {
reporter.runningExecutable = fun();
let ret;
if (action.length > 0) {
// function takes done callback
ret = reporter.runningExecutable.wrap(
() =>
// eslint-disable-next-line no-undef
new Promise((resolve, reject) => {
const t: any = resolve;
t.fail = reject;
action(t);
}),
)();
} else {
ret = reporter.runningExecutable.wrap(action)();
}
if (isPromise(ret)) {
(ret as Promise<any>)
.then(() => {
reporter.runningExecutable = null;
done();
})
.catch((e) => {
reporter.runningExecutable = null;
done.fail(e);
});
} else {
reporter.runningExecutable = null;
done();
}
}, timeout);
};
};
const wrapperBeforeAll = makeWrapperAll(jasmineBeforeAll, () =>
reporter.currentGroup.addBefore(),
);
const wrapperAfterAll = makeWrapperAll(jasmineAfterAll, () => reporter.currentGroup.addAfter());
const wrapperBeforeEach = makeWrapperAll(jasmineBeforeEach, () =>
reporter.currentGroup.addBefore(),
);
const wrapperAfterEach = makeWrapperAll(jasmineAfterEach, () =>
reporter.currentGroup.addAfter(),
);
// eslint-disable-next-line no-eval
eval("global.beforeAll = wrapperBeforeAll;");
// eslint-disable-next-line no-eval
eval("global.afterAll = wrapperAfterAll;");
// eslint-disable-next-line no-eval
eval("global.beforeEach = wrapperBeforeEach;");
// eslint-disable-next-line no-eval
eval("global.afterEach = wrapperAfterEach;");
}
}
export class JasmineAllureInterface extends Allure {
constructor(private readonly reporter: JasmineAllureReporter, runtime: AllureRuntime) {
super(runtime);
}
label(name: string, value: string): void {
try {
this.reporter.currentTest.addLabel(name, value);
} catch {
this.reporter.addLabel(name, value);
}
}
step<T>(name: string, body: (step: StepInterface) => T): T {
const wrappedStep = this.startStep(name);
let result;
try {
result = wrappedStep.run(body);
} catch (err) {
wrappedStep.setError(err as Error);
wrappedStep.endStep();
throw err;
}
if (isPromise(result)) {
const promise = result as any as Promise<any>;
return promise
.then((a) => {
wrappedStep.endStep();
return a;
})
.catch((e: Error) => {
wrappedStep.setError(e);
wrappedStep.endStep();
throw e;
}) as any as T;
} else {
wrappedStep.endStep();
return result;
}
}
logStep(name: string, status?: Status): void {
const step = this.startStep(name);
step.setStatus(status);
step.endStep();
}
attachment(
name: string,
content: Buffer | string,
options: ContentType | string | AttachmentOptions,
): void {
const file = this.reporter.writeAttachment(content, options);
this.currentExecutable.addAttachment(name, options, file);
}
testAttachment(
name: string,
content: Buffer | string,
options: ContentType | string | AttachmentOptions,
): void {
const file = this.reporter.writeAttachment(content, options);
this.currentTest.addAttachment(name, options, file);
}
protected get currentExecutable(): ExecutableItemWrapper {
return (
this.reporter.currentStep || this.reporter.currentExecutable || this.reporter.currentTest
);
}
protected get currentTest(): AllureTest {
return this.reporter.currentTest;
}
private startStep(name: string): WrappedStep {
const allureStep: AllureStep = this.currentExecutable.startStep(name);
this.reporter.pushStep(allureStep);
return new WrappedStep(this.reporter, allureStep);
}
}
class WrappedStep {
// needed?
constructor(
private readonly reporter: JasmineAllureReporter,
private readonly step: AllureStep,
) {}
startStep(name: string): WrappedStep {
const step = this.step.startStep(name);
this.reporter.pushStep(step);
return new WrappedStep(this.reporter, step);
}
setStatus(status?: Status): void {
this.step.status = status;
}
setError(error: Error): void {
this.step.status = Status.FAILED;
this.step.detailsMessage = error.message;
this.step.detailsTrace = error.stack;
}
endStep(): void {
this.reporter.popStep();
this.step.endStep();
}
run<T>(body: (step: StepInterface) => T): T {
return this.step.wrap(body)();
}
} | the_stack |
* Classes and functions for model management across multiple storage mediums.
*
* Supported client actions:
* - Listing models on all registered storage mediums.
* - Remove model by URL from any registered storage mediums, by using URL
* string.
* - Moving or copying model from one path to another in the same medium or from
* one medium to another, by using URL strings.
*/
import {assert} from '../util';
import {IORouterRegistry} from './router_registry';
import {ModelArtifactsInfo, ModelStoreManager} from './types';
const URL_SCHEME_SUFFIX = '://';
export class ModelStoreManagerRegistry {
// Singleton instance.
private static instance: ModelStoreManagerRegistry;
private managers: {[scheme: string]: ModelStoreManager};
private constructor() {
this.managers = {};
}
private static getInstance(): ModelStoreManagerRegistry {
if (ModelStoreManagerRegistry.instance == null) {
ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();
}
return ModelStoreManagerRegistry.instance;
}
/**
* Register a save-handler router.
*
* @param saveRouter A function that maps a URL-like string onto an instance
* of `IOHandler` with the `save` method defined or `null`.
*/
static registerManager(scheme: string, manager: ModelStoreManager) {
assert(scheme != null, () => 'scheme must not be undefined or null.');
if (scheme.endsWith(URL_SCHEME_SUFFIX)) {
scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));
}
assert(scheme.length > 0, () => 'scheme must not be an empty string.');
const registry = ModelStoreManagerRegistry.getInstance();
assert(
registry.managers[scheme] == null,
() => `A model store manager is already registered for scheme '${
scheme}'.`);
registry.managers[scheme] = manager;
}
static getManager(scheme: string): ModelStoreManager {
const manager = this.getInstance().managers[scheme];
if (manager == null) {
throw new Error(`Cannot find model manager for scheme '${scheme}'`);
}
return manager;
}
static getSchemes(): string[] {
return Object.keys(this.getInstance().managers);
}
}
/**
* Helper method for parsing a URL string into a scheme and a path.
*
* @param url E.g., 'localstorage://my-model'
* @returns A dictionary with two fields: scheme and path.
* Scheme: e.g., 'localstorage' in the example above.
* Path: e.g., 'my-model' in the example above.
*/
function parseURL(url: string): {scheme: string, path: string} {
if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {
throw new Error(
`The url string provided does not contain a scheme. ` +
`Supported schemes are: ` +
`${ModelStoreManagerRegistry.getSchemes().join(',')}`);
}
return {
scheme: url.split(URL_SCHEME_SUFFIX)[0],
path: url.split(URL_SCHEME_SUFFIX)[1],
};
}
async function cloneModelInternal(
sourceURL: string, destURL: string,
deleteSource = false): Promise<ModelArtifactsInfo> {
assert(
sourceURL !== destURL,
() => `Old path and new path are the same: '${sourceURL}'`);
const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);
assert(
loadHandlers.length > 0,
() => `Copying failed because no load handler is found for source URL ${
sourceURL}.`);
assert(
loadHandlers.length < 2,
() => `Copying failed because more than one (${loadHandlers.length}) ` +
`load handlers for source URL ${sourceURL}.`);
const loadHandler = loadHandlers[0];
const saveHandlers = IORouterRegistry.getSaveHandlers(destURL);
assert(
saveHandlers.length > 0,
() => `Copying failed because no save handler is found for destination ` +
`URL ${destURL}.`);
assert(
saveHandlers.length < 2,
() => `Copying failed because more than one (${loadHandlers.length}) ` +
`save handlers for destination URL ${destURL}.`);
const saveHandler = saveHandlers[0];
const sourceScheme = parseURL(sourceURL).scheme;
const sourcePath = parseURL(sourceURL).path;
const sameMedium = sourceScheme === parseURL(sourceURL).scheme;
const modelArtifacts = await loadHandler.load();
// If moving within the same storage medium, remove the old model as soon as
// the loading is done. Without doing this, it is possible that the combined
// size of the two models will cause the cloning to fail.
if (deleteSource && sameMedium) {
await ModelStoreManagerRegistry.getManager(sourceScheme)
.removeModel(sourcePath);
}
const saveResult = await saveHandler.save(modelArtifacts);
// If moving between mediums, the deletion is done after the save succeeds.
// This guards against the case in which saving to the destination medium
// fails.
if (deleteSource && !sameMedium) {
await ModelStoreManagerRegistry.getManager(sourceScheme)
.removeModel(sourcePath);
}
return saveResult.modelArtifactsInfo;
}
/**
* List all models stored in registered storage mediums.
*
* For a web browser environment, the registered mediums are Local Storage and
* IndexedDB.
*
* ```js
* // First create and save a model.
* const model = tf.sequential();
* model.add(tf.layers.dense(
* {units: 1, inputShape: [10], activation: 'sigmoid'}));
* await model.save('localstorage://demo/management/model1');
*
* // Then list existing models.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Delete the model.
* await tf.io.removeModel('localstorage://demo/management/model1');
*
* // List models again.
* console.log(JSON.stringify(await tf.io.listModels()));
* ```
*
* @returns A `Promise` of a dictionary mapping URLs of existing models to
* their model artifacts info. URLs include medium-specific schemes, e.g.,
* 'indexeddb://my/model/1'. Model artifacts info include type of the
* model's topology, byte sizes of the topology, weights, etc.
*
* @doc {
* heading: 'Models',
* subheading: 'Management',
* namespace: 'io',
* ignoreCI: true
* }
*/
async function listModels(): Promise<{[url: string]: ModelArtifactsInfo}> {
const schemes = ModelStoreManagerRegistry.getSchemes();
const out: {[url: string]: ModelArtifactsInfo} = {};
for (const scheme of schemes) {
const schemeOut =
await ModelStoreManagerRegistry.getManager(scheme).listModels();
for (const path in schemeOut) {
const url = scheme + URL_SCHEME_SUFFIX + path;
out[url] = schemeOut[path];
}
}
return out;
}
/**
* Remove a model specified by URL from a reigstered storage medium.
*
* ```js
* // First create and save a model.
* const model = tf.sequential();
* model.add(tf.layers.dense(
* {units: 1, inputShape: [10], activation: 'sigmoid'}));
* await model.save('localstorage://demo/management/model1');
*
* // Then list existing models.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Delete the model.
* await tf.io.removeModel('localstorage://demo/management/model1');
*
* // List models again.
* console.log(JSON.stringify(await tf.io.listModels()));
* ```
*
* @param url A URL to a stored model, with a scheme prefix, e.g.,
* 'localstorage://my-model-1', 'indexeddb://my/model/2'.
* @returns ModelArtifactsInfo of the deleted model (if and only if deletion
* is successful).
* @throws Error if deletion fails, e.g., if no model exists at `path`.
*
* @doc {
* heading: 'Models',
* subheading: 'Management',
* namespace: 'io',
* ignoreCI: true
* }
*/
async function removeModel(url: string): Promise<ModelArtifactsInfo> {
const schemeAndPath = parseURL(url);
const manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme);
return manager.removeModel(schemeAndPath.path);
}
/**
* Copy a model from one URL to another.
*
* This function supports:
*
* 1. Copying within a storage medium, e.g.,
* `tf.io.copyModel('localstorage://model-1', 'localstorage://model-2')`
* 2. Copying between two storage mediums, e.g.,
* `tf.io.copyModel('localstorage://model-1', 'indexeddb://model-1')`
*
* ```js
* // First create and save a model.
* const model = tf.sequential();
* model.add(tf.layers.dense(
* {units: 1, inputShape: [10], activation: 'sigmoid'}));
* await model.save('localstorage://demo/management/model1');
*
* // Then list existing models.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Copy the model, from Local Storage to IndexedDB.
* await tf.io.copyModel(
* 'localstorage://demo/management/model1',
* 'indexeddb://demo/management/model1');
*
* // List models again.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Remove both models.
* await tf.io.removeModel('localstorage://demo/management/model1');
* await tf.io.removeModel('indexeddb://demo/management/model1');
* ```
*
* @param sourceURL Source URL of copying.
* @param destURL Destination URL of copying.
* @returns ModelArtifactsInfo of the copied model (if and only if copying
* is successful).
* @throws Error if copying fails, e.g., if no model exists at `sourceURL`, or
* if `oldPath` and `newPath` are identical.
*
* @doc {
* heading: 'Models',
* subheading: 'Management',
* namespace: 'io',
* ignoreCI: true
* }
*/
async function copyModel(
sourceURL: string, destURL: string): Promise<ModelArtifactsInfo> {
const deleteSource = false;
return cloneModelInternal(sourceURL, destURL, deleteSource);
}
/**
* Move a model from one URL to another.
*
* This function supports:
*
* 1. Moving within a storage medium, e.g.,
* `tf.io.moveModel('localstorage://model-1', 'localstorage://model-2')`
* 2. Moving between two storage mediums, e.g.,
* `tf.io.moveModel('localstorage://model-1', 'indexeddb://model-1')`
*
* ```js
* // First create and save a model.
* const model = tf.sequential();
* model.add(tf.layers.dense(
* {units: 1, inputShape: [10], activation: 'sigmoid'}));
* await model.save('localstorage://demo/management/model1');
*
* // Then list existing models.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Move the model, from Local Storage to IndexedDB.
* await tf.io.moveModel(
* 'localstorage://demo/management/model1',
* 'indexeddb://demo/management/model1');
*
* // List models again.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Remove the moved model.
* await tf.io.removeModel('indexeddb://demo/management/model1');
* ```
*
* @param sourceURL Source URL of moving.
* @param destURL Destination URL of moving.
* @returns ModelArtifactsInfo of the copied model (if and only if copying
* is successful).
* @throws Error if moving fails, e.g., if no model exists at `sourceURL`, or
* if `oldPath` and `newPath` are identical.
*
* @doc {
* heading: 'Models',
* subheading: 'Management',
* namespace: 'io',
* ignoreCI: true
* }
*/
async function moveModel(
sourceURL: string, destURL: string): Promise<ModelArtifactsInfo> {
const deleteSource = true;
return cloneModelInternal(sourceURL, destURL, deleteSource);
}
export {moveModel, copyModel, removeModel, listModels}; | the_stack |
import leven from "leven";
import {
allNamedEntitiesSetOnly,
allNamedEntitiesSetOnlyCaseInsensitive,
entStartsWith,
entEndsWith,
brokenNamedEntities,
decode,
maxLength,
uncertain,
} from "all-named-html-entities";
import { left, right, rightSeq, leftSeq } from "string-left-right";
import {
isObj,
isStr,
isNumeric,
resemblesNumericEntity,
removeGappedFromMixedCases,
isLatinLetterOrNumberOrHash,
} from "./util";
import { version as v } from "../package.json";
const version: string = v;
import { Ranges } from "../../../scripts/common";
const allRules = [...allNamedEntitiesSetOnly]
.map((ruleName) => `bad-html-entity-malformed-${ruleName}`)
.concat(
[...allNamedEntitiesSetOnly].map(
(ruleName) => `bad-html-entity-encoded-${ruleName}`
)
)
.concat([
"bad-html-entity-unrecognised",
"bad-html-entity-multiple-encoding",
"bad-html-entity-encoded-numeric",
"bad-html-entity-malformed-numeric",
"bad-html-entity-other",
]);
interface Obj {
[key: string]: any;
}
interface cbObj {
rangeFrom: number;
rangeTo: number;
rangeValEncoded: string | null;
rangeValDecoded: string | null;
ruleName: string;
entityName: string | null;
}
interface Opts {
decode: boolean;
cb: null | ((obj: cbObj) => void);
entityCatcherCb: null | ((from: number, to: number) => void);
textAmpersandCatcherCb: null | ((idx: number) => void);
progressFn: null | ((percDone: number) => void);
}
function fixEnt(str: string, originalOpts?: Partial<Opts>): Ranges {
console.log(
`061 fixEnt: ${`\u001b[${33}m${`str`}\u001b[${39}m`} = ${JSON.stringify(
str,
null,
0
)};\n${`\u001b[${33}m${`originalOpts`}\u001b[${39}m`} = ${JSON.stringify(
originalOpts,
null,
4
)}`
);
//
//
//
//
//
// THE PROGRAM
//
//
//
//
//
// insurance:
// ---------------------------------------------------------------------------
if (typeof str !== "string") {
throw new Error(
`string-fix-broken-named-entities: [THROW_ID_01] the first input argument must be string! It was given as:\n${JSON.stringify(
str,
null,
4
)} (${typeof str}-type)`
);
}
const defaults: Opts = {
decode: false,
cb: ({ rangeFrom, rangeTo, rangeValEncoded, rangeValDecoded }: cbObj) =>
rangeValDecoded || rangeValEncoded
? [
rangeFrom,
rangeTo,
isObj(originalOpts) && (originalOpts as Obj).decode
? rangeValDecoded
: rangeValEncoded,
]
: [rangeFrom, rangeTo],
textAmpersandCatcherCb: null,
progressFn: null,
entityCatcherCb: null,
};
if (originalOpts && !isObj(originalOpts)) {
throw new Error(
`string-fix-broken-named-entities: [THROW_ID_02] the second input argument must be a plain object! I was given as:\n${JSON.stringify(
originalOpts,
null,
4
)} (${typeof originalOpts}-type)`
);
}
const opts = { ...defaults, ...originalOpts };
console.log(
`125 ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify(
opts,
null,
4
)}`
);
if (opts.cb && typeof opts.cb !== "function") {
throw new TypeError(
`string-fix-broken-named-entities: [THROW_ID_03] opts.cb must be a function (or falsey)! Currently it's: ${typeof opts.cb}, equal to: ${JSON.stringify(
opts.cb,
null,
4
)}`
);
}
if (opts.entityCatcherCb && typeof opts.entityCatcherCb !== "function") {
throw new TypeError(
`string-fix-broken-named-entities: [THROW_ID_04] opts.entityCatcherCb must be a function (or falsey)! Currently it's: ${typeof opts.entityCatcherCb}, equal to: ${JSON.stringify(
opts.entityCatcherCb,
null,
4
)}`
);
}
if (opts.progressFn && typeof opts.progressFn !== "function") {
throw new TypeError(
`string-fix-broken-named-entities: [THROW_ID_05] opts.progressFn must be a function (or falsey)! Currently it's: ${typeof opts.progressFn}, equal to: ${JSON.stringify(
opts.progressFn,
null,
4
)}`
);
}
if (
opts.textAmpersandCatcherCb &&
typeof opts.textAmpersandCatcherCb !== "function"
) {
throw new TypeError(
`string-fix-broken-named-entities: [THROW_ID_06] opts.textAmpersandCatcherCb must be a function (or falsey)! Currently it's: ${typeof opts.textAmpersandCatcherCb}, equal to: ${JSON.stringify(
opts.textAmpersandCatcherCb,
null,
4
)}`
);
}
console.log(
`172 fixEnt: FINAL ${`\u001b[${33}m${`opts`}\u001b[${39}m`} used: ${JSON.stringify(
opts,
null,
4
)}`
);
// state flags
// ---------------------------------------------------------------------------
// this is what we'll return, process by default callback or user's custom-one
const rangesArr2: cbObj[] = [];
let percentageDone: number | undefined;
let lastPercentageDone: number | undefined;
// allocate all 100 of progress to the main loop below
const len = str.length + 1;
let counter = 0;
// doNothingUntil can be either falsey or truthy: index number or boolean true
// If it's number, it's instruction to avoid actions until that index is
// reached when traversing. If it's boolean, it means we don't know when we'll
// stop, we just turn on the flag (permanently, for now).
let doNothingUntil: number | null | boolean = null;
// catch letter sequences, possibly separated with whitespace. Non-letter
// breaks the sequence. Main aim is to catch names of encoded HTML entities
// for example, nbsp from " "
let letterSeqStartAt: number | null = null;
let brokenNumericEntityStartAt = null;
const ampPositions: number[] = [];
function pingAmps(untilIdx?: number, loopIndexI?: number) {
if (
typeof opts.textAmpersandCatcherCb === "function" &&
ampPositions.length
) {
console.log(`212 loop`);
while (ampPositions.length) {
const currentAmp = ampPositions.shift() as number;
console.log(
`216 SET ${`\u001b[${36}m${`currentAmp`}\u001b[${39}m`} = ${JSON.stringify(
currentAmp,
null,
4
)}`
);
if (
// batch dumping, cases like end of string reached:
untilIdx === undefined ||
// submit all ampersands caught up to this entity:
currentAmp < untilIdx ||
// also, we might on a new ampersand, for example:
// <span>& &</span>
// ^
// we're here
currentAmp === loopIndexI
) {
console.log(
`234 ${`\u001b[${32}m${`PING`}\u001b[${39}m`} opts.textAmpersandCatcherCb() with ${`\u001b[${35}m${currentAmp}\u001b[${39}m`}`
);
// ping each ampersand's index, starting from zero index:
opts.textAmpersandCatcherCb(currentAmp);
} // else, it gets discarded without action
}
}
}
// |
// |
// |
// |
// |
// |
// |
// T H E L O O P S T A R T S
// |
// |
// \ | /
// \ | /
// \ | /
// \ | /
// \| /
// V
// differently from regex-based approach, we aim to traverse the string only once:
for (let i = 0; i <= len; i++) {
if (opts.progressFn) {
percentageDone = Math.floor((counter / len) * 100);
/* istanbul ignore else */
if (percentageDone !== lastPercentageDone) {
lastPercentageDone = percentageDone;
opts.progressFn(percentageDone);
}
}
// |
// |
// |
// |
// |
// PART 1. FRONTAL LOGGING
// |
// |
// |
// |
// |
console.log(
`282 fixEnt: \n\u001b[${36}m${`===============================`}\u001b[${39}m \u001b[${35}m${`str[ ${i} ] = ${
str[i] && str[i].trim().length
? str[i]
: JSON.stringify(str[i], null, 4)
}`}\u001b[${39}m \u001b[${36}m${`===============================`}\u001b[${39}m\n`
);
// |
// |
// |
// |
// |
// PART 3. RULES AT THE TOP
// |
// |
// |
// |
// |
if (doNothingUntil) {
if (typeof doNothingUntil === "number" && i >= doNothingUntil) {
doNothingUntil = null;
console.log(
`305 fixEnt: RESET ${`\u001b[${33}m${`doNothingUntil`}\u001b[${39}m`} = null`
);
} else {
console.log(`308 fixEnt: continue`);
counter += 1;
continue;
}
}
// |
// |
// |
// |
// |
// PART 3. RULES AT THE MIDDLE
// |
// |
// |
// |
// |
// escape latch for text chunks
if (letterSeqStartAt !== null && i - letterSeqStartAt > 50) {
letterSeqStartAt = null;
console.log(
`330 ${`\u001b[${31}m${`WIPE letterSeqStartAt`}\u001b[${39}m`}`
);
}
// Catch the end of a latin letter sequence.
if (
letterSeqStartAt !== null &&
(!str[i] ||
(str[i].trim().length && !isLatinLetterOrNumberOrHash(str[i])))
) {
console.log(
`341 fixEnt: ${`\u001b[${36}m${`██ letterSeqStartAt = ${letterSeqStartAt}`}\u001b[${39}m`}`
);
if (i > letterSeqStartAt + 1) {
const potentialEntity = str.slice(letterSeqStartAt, i);
console.log(
`346 fixEnt: ${`\u001b[${35}m${`██ CARVED A SEQUENCE: ${potentialEntity}`}\u001b[${39}m`}`
);
const whatsOnTheLeft = left(str, letterSeqStartAt);
const whatsEvenMoreToTheLeft = whatsOnTheLeft
? left(str, whatsOnTheLeft)
: null;
//
//
//
//
// CASE 1 - CHECK FOR MISSING SEMICOLON
//
//
//
//
if (
str[whatsOnTheLeft as number] === "&" &&
(!str[i] || str[i] !== ";")
) {
console.log(
`369 ${`\u001b[${35}m${`semicol might be missing`}\u001b[${39}m`}`
);
// check, what's the index of the character to the right of
// str[whatsOnTheLeft], is it any of the known named HTML entities.
const firstChar: number | null = letterSeqStartAt;
/* istanbul ignore next */
const secondChar: number | null = letterSeqStartAt
? right(str, letterSeqStartAt)
: null;
console.log(
`379 firstChar = str[${firstChar}] = ${
str[firstChar]
}; secondChar = str[${secondChar}] = ${str[secondChar as number]}`
);
// we'll tap the "entStartsWith" from npm package "all-named-html-entities"
// which gives a plain object of named entities, all grouped by first
// and second character first. This reduces amount of matching needed.
console.log(
`387 ██ ${
secondChar !== null &&
Object.prototype.hasOwnProperty.call(
entStartsWith,
str[firstChar]
) &&
Object.prototype.hasOwnProperty.call(
entStartsWith[str[firstChar]],
str[secondChar]
)
}`
);
// mind you, there can be overlapping variations of entities, for
// example, ∠ and Å. Now, if you match "ang" from "∠",
// starting from the left side (like we do using "entStartsWith"),
// when there is "Å", answer will also be positive. And we can't
// rely on semicolon being on the right because we are actually
// catching MISSING semicolons here.
// The only way around this is to match all entities that start here
// and pick the one with the biggest character length.
// TODO - set up the case-insensitive matching here:
/* istanbul ignore else */
if (
Object.prototype.hasOwnProperty.call(
entStartsWith,
str[firstChar as number]
) &&
Object.prototype.hasOwnProperty.call(
entStartsWith[str[firstChar]],
str[secondChar as number]
)
) {
console.log(`421`);
let tempEnt = "";
let tempRes;
let temp1 = (entStartsWith as Obj)[str[firstChar as number]][
str[secondChar as number] as string
].reduce((gatheredSoFar: any[], oneOfKnownEntities: string) => {
// find all entities that match on the right of here
// rightSeq could theoretically give positive answer, zero index,
// but it's impossible here, so we're fine to match "if true".
tempRes = rightSeq(
str,
(letterSeqStartAt as number) - 1,
...oneOfKnownEntities.split("")
);
if (tempRes) {
return gatheredSoFar.concat([
{ tempEnt: oneOfKnownEntities, tempRes },
]);
}
return gatheredSoFar;
}, []);
console.log(
`444 ${`\u001b[${35}m${`temp1 BEFORE filtering = ${JSON.stringify(
temp1,
null,
4
)}`}\u001b[${39}m`}`
);
temp1 = removeGappedFromMixedCases(str, temp1);
console.log(
`452 ${`\u001b[${35}m${`temp1 AFTER filtering = ${JSON.stringify(
temp1,
null,
4
)}`}\u001b[${39}m`}`
);
/* istanbul ignore else */
if (temp1) {
({ tempEnt, tempRes } = temp1);
}
console.log(
`464 ${`\u001b[${33}m${`tempEnt`}\u001b[${39}m`} = ${tempEnt}; ${`\u001b[${33}m${`tempRes`}\u001b[${39}m`} = ${JSON.stringify(
tempRes,
null,
4
)}`
);
console.log(
`472 ${`\u001b[${33}m${`["&"].includes(str[tempRes.rightmostChar + 1])`}\u001b[${39}m`} = ${
tempRes && tempRes.rightmostChar
? JSON.stringify(
["&"].includes(str[tempRes.rightmostChar + 1]),
null,
4
)
: ""
}`
);
if (
tempEnt &&
(!Object.keys(uncertain).includes(tempEnt) ||
!str[tempRes.rightmostChar + 1] ||
["&"].includes(str[tempRes.rightmostChar + 1]) ||
(((uncertain[tempEnt] as Obj).addSemiIfAmpPresent === true ||
((uncertain[tempEnt] as Obj).addSemiIfAmpPresent &&
(!str[tempRes.rightmostChar + 1] ||
!str[tempRes.rightmostChar + 1].trim().length))) &&
str[tempRes.leftmostChar - 1] === "&"))
) {
console.log(
`494 ${`\u001b[${35}m${`entity ${tempEnt} is indeed on the left of index ${i}, the situation is: ${JSON.stringify(
tempRes,
null,
4
)}`}\u001b[${39}m`}`
);
const decodedEntity = decode(`&${tempEnt};`);
console.log(`503 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `bad-html-entity-malformed-${tempEnt}`,
entityName: tempEnt,
rangeFrom: whatsOnTheLeft || 0,
rangeTo: tempRes.rightmostChar + 1,
rangeValEncoded: `&${tempEnt};`,
rangeValDecoded: decodedEntity as string,
});
// release all ampersands
console.log(
`515 ███████████████████████████████████████ release ampersands`
);
console.log(
`518 FIY, ${`\u001b[${33}m${`tempRes`}\u001b[${39}m`} = ${JSON.stringify(
tempRes,
null,
4
)}`
);
pingAmps(whatsOnTheLeft || 0, i);
} else {
console.log(`526 ELSE, it was just a legit ampersand`);
}
}
} else if (
str[whatsOnTheLeft as number] !== "&" &&
str[whatsEvenMoreToTheLeft as number] !== "&" &&
str[i] === ";"
) {
//
//
//
//
// CASE 2 - CHECK FOR MISSING AMPERSAND
//
//
//
//
console.log(
`545 ${`\u001b[${35}m${`ampersand might be missing`}\u001b[${39}m`}`
);
// check, what's on the left of str[i], is it any of known named HTML
// entities. There are two thousand of them so we'll match by last
// two characters. For posterity, we assume there can be any amount of
// whitespace between characters and we need to tackle it as well.
const lastChar = left(str, i);
const secondToLast = left(str, lastChar);
// we'll tap the "entEndsWith" from npm package "all-named-html-entities"
// which gives a plain object of named entities, all grouped by first
// and second character first. This reduces amount of matching needed.
if (
secondToLast !== null &&
Object.prototype.hasOwnProperty.call(
entEndsWith,
str[lastChar as number]
) &&
Object.prototype.hasOwnProperty.call(
entEndsWith[str[lastChar as number]],
str[secondToLast]
)
) {
console.log(`568`);
let tempEnt = "";
let tempRes;
let temp1 = (entEndsWith as Obj)[str[lastChar as number] as string][
str[secondToLast as number] as string
].reduce((gatheredSoFar: any[], oneOfKnownEntities: string) => {
// find all entities that match on the right of here
// rightSeq could theoretically give positive answer, zero index,
// but it's impossible here, so we're fine to match "if true".
tempRes = leftSeq(str, i, ...oneOfKnownEntities.split(""));
if (
tempRes &&
!(
oneOfKnownEntities === "block" &&
str[left(str, letterSeqStartAt) as number] === ":"
)
) {
return gatheredSoFar.concat([
{ tempEnt: oneOfKnownEntities, tempRes },
]);
}
return gatheredSoFar;
}, []);
console.log(
`594 ${`\u001b[${35}m${`temp1 BEFORE filtering = ${JSON.stringify(
temp1,
null,
4
)}`}\u001b[${39}m`}`
);
temp1 = removeGappedFromMixedCases(str, temp1);
console.log(
`602 ${`\u001b[${35}m${`temp1 AFTER filtering = ${JSON.stringify(
temp1,
null,
4
)}`}\u001b[${39}m`}`
);
/* istanbul ignore else */
if (temp1) {
({ tempEnt, tempRes } = temp1);
}
console.log(
`614 ${`\u001b[${33}m${`tempEnt`}\u001b[${39}m`} = ${tempEnt} - ${`\u001b[${33}m${`tempRes`}\u001b[${39}m`} = ${JSON.stringify(
tempRes,
null,
4
)}`
);
console.log(
`622 letterSeqStartAt = ${letterSeqStartAt}; str[letterSeqStartAt] = ${
str[letterSeqStartAt]
}; tempRes.leftmostChar = ${
tempRes && tempRes.leftmostChar
? tempRes.leftmostChar
: "undefined"
}; str[tempRes.leftmostChar - 1] = ${
tempRes && tempRes.leftmostChar
? str[tempRes.leftmostChar - 1]
: "undefined"
}`
);
if (
tempEnt &&
(!Object.keys(uncertain).includes(tempEnt) ||
(uncertain as Obj)[tempEnt].addAmpIfSemiPresent === true ||
((uncertain as Obj)[tempEnt].addAmpIfSemiPresent &&
(!tempRes.leftmostChar ||
(isStr(str[tempRes.leftmostChar - 1]) &&
!str[tempRes.leftmostChar - 1].trim().length))))
) {
console.log(
`644 ${`\u001b[${35}m${`entity ${tempEnt} is indeed on the left of index ${i}, the situation is: ${JSON.stringify(
tempRes,
null,
4
)}`}\u001b[${39}m`}`
);
const decodedEntity = decode(`&${tempEnt};`);
console.log(`653 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `bad-html-entity-malformed-${tempEnt}`,
entityName: tempEnt,
rangeFrom: tempRes.leftmostChar,
rangeTo: i + 1,
rangeValEncoded: `&${tempEnt};`,
rangeValDecoded: decodedEntity as string,
});
pingAmps(tempRes.leftmostChar, i);
} else {
console.log(
`665 ${`\u001b[${31}m${`██`}\u001b[${39}m`} "${tempEnt}" is among uncertain entities`
);
}
} else if (brokenNumericEntityStartAt !== null) {
// we have a malformed numeric entity reference, like #x26; without
// an ampersand but with the rest of characters
// 1. push the issue:
console.log(`673 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: "bad-html-entity-malformed-numeric",
entityName: null,
rangeFrom: brokenNumericEntityStartAt,
rangeTo: i + 1,
rangeValEncoded: null,
rangeValDecoded: null,
});
pingAmps(brokenNumericEntityStartAt, i);
// 2. reset marker:
brokenNumericEntityStartAt = null;
console.log(
`687 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} brokenNumericEntityStartAt = null`
);
}
} else if (
str[i] === ";" &&
(str[whatsOnTheLeft as number] === "&" ||
(str[whatsOnTheLeft as number] === ";" &&
str[whatsEvenMoreToTheLeft as number] === "&"))
) {
//
//
//
//
// CASE 3 - CHECK FOR MESSY ENTITIES OR REQUESTED DECODING
//
//
//
//
console.log(
`706 ${`\u001b[${32}m${`██ looks like some sort of HTML entitity!`}\u001b[${39}m`}`
);
let startOfTheSeq = (letterSeqStartAt as number) - 1;
console.log(
`711 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`startOfTheSeq`}\u001b[${39}m`} = ${JSON.stringify(
startOfTheSeq,
null,
4
)}`
);
if (
!str[letterSeqStartAt - 1].trim() &&
str[whatsOnTheLeft as number] === "&"
) {
startOfTheSeq = whatsOnTheLeft as number;
console.log(
`723 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`startOfTheSeq`}\u001b[${39}m`} = ${JSON.stringify(
startOfTheSeq,
null,
4
)}`
);
}
// find out more: is it legit, unrecognised or numeric...
/* istanbul ignore else */
if (str.slice((whatsOnTheLeft as number) + 1, i).trim().length > 1) {
console.log(
`736 ${`\u001b[${90}m${`so there are some characters in between: & and ;`}\u001b[${39}m`}`
);
// Maybe it's a numeric entity?
// we can simply check, does entity start with a hash but that
// would be naive because this is a tool to catch and fix errors
// and hash might be missing or mis-typed
// So, we have confirmed ampersand, something in between and then
// confirmed semicolon.
// First, we extracted the contents of all this, "situation.charTrimmed".
// By the way, Character-trimmed string where String.trim() is
// applied to each character. This is needed so that our tool could
// recognise whitespace gaps anywhere in the input. Imagine, for
// example, "&# 85;" with rogue space. Errors like that require
// constant trimming on the algorithm side.
// We are going to describe numeric entity as
// * something that starts with ampersand
// * ends with semicolon
// - has no letter characters AND at least one number character OR
// - has more numeric characters than letters
const situation = resemblesNumericEntity(
str,
(whatsOnTheLeft as number) + 1,
i
);
console.log(
`767 ${`\u001b[${33}m${`situation`}\u001b[${39}m`} = ${JSON.stringify(
situation,
null,
4
)}`
);
if (situation.probablyNumeric) {
console.log(
`776 ${`\u001b[${32}m${`██ seems like a numeric HTML entity!`}\u001b[${39}m`}`
);
// 1. TACKLE HEALTHY DECIMAL NUMERIC CHARACTER REFERENCE ENTITIES:
if (
/* istanbul ignore next */
situation.probablyNumeric &&
situation.charTrimmed[0] === "#" &&
!situation.whitespaceCount &&
// decimal:
((!situation.lettersCount &&
situation.numbersCount > 0 &&
!situation.othersCount) ||
// hexidecimal:
((situation.numbersCount || situation.lettersCount) &&
situation.charTrimmed[1] === "x" &&
!situation.othersCount))
) {
// if it's a healthy decimal numeric character reference:
const decodedEntitysValue = String.fromCharCode(
parseInt(
situation.charTrimmed.slice(
situation.probablyNumeric === "deci" ? 1 : 2
),
situation.probablyNumeric === "deci" ? 10 : 16
)
);
console.log(
`804 ${`\u001b[${32}m${`██ it's a ${
situation.probablyNumeric === "hexi" ? "hexi" : ""
}decimal numeric entity reference: "${decodedEntitysValue}"`}\u001b[${39}m`}`
);
if (
situation.probablyNumeric === "deci" &&
parseInt(situation.numbersValue, 10) > 918015
) {
console.log(`813 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `bad-html-entity-malformed-numeric`,
entityName: null,
rangeFrom: whatsOnTheLeft || 0,
rangeTo: i + 1,
rangeValEncoded: null,
rangeValDecoded: null,
});
} else if (opts.decode) {
// unless decoding was requested, no further action is needed:
console.log(`824 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `bad-html-entity-encoded-numeric`,
entityName: situation.charTrimmed,
rangeFrom: whatsOnTheLeft || 0,
rangeTo: i + 1,
rangeValEncoded: `&${situation.charTrimmed};`,
rangeValDecoded: decodedEntitysValue,
});
}
console.log(`835 pingAmps()`);
pingAmps(whatsOnTheLeft || 0, i);
} else {
// RAISE A GENERIC ERROR
console.log(`839 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `bad-html-entity-malformed-numeric`,
entityName: null,
rangeFrom: whatsOnTheLeft || 0,
rangeTo: i + 1,
rangeValEncoded: null,
rangeValDecoded: null,
});
pingAmps(whatsOnTheLeft || 0, i);
}
// also call the general entity callback if it's given
if (opts.entityCatcherCb) {
console.log(`853 call opts.entityCatcherCb()`);
opts.entityCatcherCb(whatsOnTheLeft as number, i + 1);
}
} else {
console.log(
`858 ${`\u001b[${32}m${`it's either named or some sort of messed up HTML entity`}\u001b[${39}m`}`
);
//
//
//
//
// NAMED ENTITIES CLAUSES BELOW
//
//
//
//
// happy path:
const potentialEntityOnlyNonWhitespaceChars = Array.from(
potentialEntity
)
.filter((char) => char.trim().length)
.join("");
if (
potentialEntityOnlyNonWhitespaceChars.length <= maxLength &&
allNamedEntitiesSetOnlyCaseInsensitive.has(
potentialEntityOnlyNonWhitespaceChars.toLowerCase()
)
) {
console.log(
`886 ${`\u001b[${32}m${`MATCHED HEALTHY "${potentialEntityOnlyNonWhitespaceChars}"!!!`}\u001b[${39}m`}`
);
console.log(
`890 FIY, ${`\u001b[${33}m${`ampPositions`}\u001b[${39}m`} = ${JSON.stringify(
ampPositions,
null,
4
)}`
);
console.log(
`898 FIY, ${`\u001b[${33}m${`whatsOnTheLeft`}\u001b[${39}m`} = ${JSON.stringify(
whatsOnTheLeft,
null,
4
)}`
);
if (
// first, check is the letter case allright
typeof potentialEntityOnlyNonWhitespaceChars === "string" &&
!allNamedEntitiesSetOnly.has(
potentialEntityOnlyNonWhitespaceChars
)
) {
console.log(
`913 ${`\u001b[${31}m${`a problem with letter case!`}\u001b[${39}m`}`
);
const matchingEntitiesOfCorrectCaseArr = [
...allNamedEntitiesSetOnly,
].filter(
(ent) =>
ent.toLowerCase() ===
potentialEntityOnlyNonWhitespaceChars.toLowerCase()
);
console.log(
`924 ${`\u001b[${32}m${`EXTRACTED`}\u001b[${39}m`}: ${`\u001b[${33}m${`matchingEntitiesOfCorrectCaseArr`}\u001b[${39}m`} = ${JSON.stringify(
matchingEntitiesOfCorrectCaseArr,
null,
4
)}`
);
if (matchingEntitiesOfCorrectCaseArr.length === 1) {
console.log(`932 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `bad-html-entity-malformed-${matchingEntitiesOfCorrectCaseArr[0]}`,
entityName: matchingEntitiesOfCorrectCaseArr[0],
rangeFrom: whatsOnTheLeft as number,
rangeTo: i + 1,
rangeValEncoded: `&${matchingEntitiesOfCorrectCaseArr[0]};`,
rangeValDecoded: decode(
`&${matchingEntitiesOfCorrectCaseArr[0]};`
),
});
pingAmps(whatsOnTheLeft as number, i);
} else {
console.log(`945 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `bad-html-entity-unrecognised`,
entityName: null,
rangeFrom: whatsOnTheLeft as number,
rangeTo: i + 1,
rangeValEncoded: null,
rangeValDecoded: null,
});
pingAmps(whatsOnTheLeft as number, i);
}
} else if (
// is it really healthy? measuring distance is a way to find out
// any present whitespace characters will bloat the length...
i - (whatsOnTheLeft as number) - 1 !==
potentialEntityOnlyNonWhitespaceChars.length ||
str[whatsOnTheLeft as number] !== "&"
) {
console.log(
`964 ${`\u001b[${31}m${`whitespace present!`}\u001b[${39}m`}`
);
const rangeFrom =
str[whatsOnTheLeft as number] === "&"
? whatsOnTheLeft
: whatsEvenMoreToTheLeft;
if (
// if it's a dubious entity
Object.keys(uncertain).includes(
potentialEntityOnlyNonWhitespaceChars
) &&
// and there's a space after ampersand
!str[(rangeFrom as number) + 1].trim().length
) {
console.log(
`981 ${`\u001b[${31}m${`BAIL EARLY`}\u001b[${39}m`} - reset and continue - it's a known uncertain entity!`
);
letterSeqStartAt = null;
continue;
}
console.log(`987 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `bad-html-entity-malformed-${potentialEntityOnlyNonWhitespaceChars}`,
entityName: potentialEntityOnlyNonWhitespaceChars,
rangeFrom: rangeFrom as number,
rangeTo: i + 1,
rangeValEncoded: `&${potentialEntityOnlyNonWhitespaceChars};`,
rangeValDecoded: decode(
`&${potentialEntityOnlyNonWhitespaceChars};`
),
});
pingAmps(rangeFrom as number, i);
} else if (opts.decode) {
console.log(
`1001 ${`\u001b[${31}m${`decode requested!!!`}\u001b[${39}m`}`
);
// last thing, if decode is required, we've got an error still...
console.log(`1005 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `bad-html-entity-encoded-${potentialEntityOnlyNonWhitespaceChars}`,
entityName: potentialEntityOnlyNonWhitespaceChars,
rangeFrom: whatsOnTheLeft as number,
rangeTo: i + 1,
rangeValEncoded: `&${potentialEntityOnlyNonWhitespaceChars};`,
rangeValDecoded: decode(
`&${potentialEntityOnlyNonWhitespaceChars};`
),
});
pingAmps(whatsOnTheLeft as number, i);
} else if (
opts.entityCatcherCb ||
opts.textAmpersandCatcherCb
) {
// it's healthy - so at least ping the entity catcher
if (opts.entityCatcherCb) {
console.log(`1024 call opts.entityCatcherCb()`);
opts.entityCatcherCb(whatsOnTheLeft as number, i + 1);
}
if (opts.textAmpersandCatcherCb) {
console.log(`1029 call pingAmps()`);
pingAmps(whatsOnTheLeft as number, i);
}
}
console.log(`1034 reset and continue`);
letterSeqStartAt = null;
continue;
} else {
console.log(
`1039 ${`\u001b[${31}m${`not recognised "${potentialEntity}" - moving on`}\u001b[${39}m`}`
);
}
// First, match against case-insensitive list
// 1. check, maybe it's a known HTML entity
const firstChar = letterSeqStartAt;
/* istanbul ignore next */
const secondChar = letterSeqStartAt
? right(str, letterSeqStartAt)
: null;
console.log(
`1052 firstChar = str[${firstChar}] = ${
str[firstChar]
}; secondChar = str[${secondChar}] = ${
str[secondChar as number]
}`
);
let tempEnt = "";
let temp: string[];
console.log(
`1063 FIY, situation.charTrimmed.toLowerCase() = "${situation.charTrimmed.toLowerCase()}"`
);
if (
Object.prototype.hasOwnProperty.call(
brokenNamedEntities,
situation.charTrimmed.toLowerCase()
)
) {
//
// case I.
//
console.log(
`1077 ${`\u001b[${32}m${`██`}\u001b[${39}m`} known broken entity ${situation.charTrimmed.toLowerCase()} is indeed on the right`
);
console.log(
`1081 broken entity ${situation.charTrimmed.toLowerCase()} is indeed on the right`
);
tempEnt = situation.charTrimmed;
const decodedEntity = decode(
`&${
brokenNamedEntities[situation.charTrimmed.toLowerCase()]
};`
);
console.log(`1091 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `bad-html-entity-malformed-${
brokenNamedEntities[situation.charTrimmed.toLowerCase()]
}`,
entityName: brokenNamedEntities[
situation.charTrimmed.toLowerCase()
] as string,
rangeFrom: whatsOnTheLeft as number,
rangeTo: i + 1,
rangeValEncoded: `&${
brokenNamedEntities[situation.charTrimmed.toLowerCase()]
};`,
rangeValDecoded: decodedEntity,
});
pingAmps(whatsOnTheLeft as number, i);
} else if (
// idea being, if length of suspected chunk is less or equal to
// the length of the longest entity (add 1 for Levenshtein distance)
// we still consider that whole chunk (from ampersand to semi)
// might be a value of an entity
potentialEntity.length < maxLength + 2 &&
// a) either one character is different:
(((temp = [...allNamedEntitiesSetOnly].filter(
(curr) => leven(curr, potentialEntity) === 1
)) &&
temp.length) ||
//
// OR
//
// b) two are different but entity is at least 4 chars long:
((temp = [...allNamedEntitiesSetOnly].filter(
(curr) =>
/* istanbul ignore next */
leven(curr, potentialEntity) === 2 &&
potentialEntity.length > 3
)) &&
temp.length))
) {
console.log(
`1131 ${`\u001b[${32}m${`LEVENSHTEIN DIFFERENCE CAUGHT malformed "${temp}"`}\u001b[${39}m`}`
);
// now the problem: what if there were multiple entities matched?
/* istanbul ignore else */
if (temp.length === 1) {
[tempEnt] = temp;
console.log(`1139 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `bad-html-entity-malformed-${tempEnt}`,
entityName: tempEnt,
rangeFrom: whatsOnTheLeft as number,
rangeTo: i + 1,
rangeValEncoded: `&${tempEnt};`,
rangeValDecoded: decode(`&${tempEnt};`),
});
pingAmps(whatsOnTheLeft as number, i);
} else if (temp) {
// For example, &rsqo; could be suspected as
// Lenshtein's distance ] and ’
// The last chance, count how many letters are
// absent in this malformed entity.
const missingLettersCount = temp.map((ent) => {
const splitStr = str.split("");
return ent.split("").reduce((acc, curr) => {
if (splitStr.includes(curr)) {
// remove that character from splitStr
// so that we count only once, repetitions need to
// be matched equally
splitStr.splice(splitStr.indexOf(curr), 1);
return acc + 1;
}
return acc;
}, 0);
});
console.log(
`1168 ███████████████████████████████████████ ${`\u001b[${33}m${`missingLettersCount`}\u001b[${39}m`} = ${JSON.stringify(
missingLettersCount,
null,
4
)}`
);
const maxVal = Math.max(...missingLettersCount);
console.log(
`1176 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`maxVal`}\u001b[${39}m`} = ${JSON.stringify(
maxVal,
null,
4
)}`
);
// if there's only one value with more characters matched
// than others, ] vs ’ - latter would win matching
// against messed up &rsqo; - we pick that winning-one
if (
maxVal &&
missingLettersCount.filter((v) => v === maxVal).length === 1
) {
for (
let z = 0, len = missingLettersCount.length;
z < len;
z++
) {
if (missingLettersCount[z] === maxVal) {
tempEnt = temp[z];
console.log(
`1197 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`tempEnt`}\u001b[${39}m`} = ${JSON.stringify(
tempEnt,
null,
4
)}`
);
console.log(
`1204 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`
);
rangesArr2.push({
ruleName: `bad-html-entity-malformed-${tempEnt}`,
entityName: tempEnt,
rangeFrom: whatsOnTheLeft as number,
rangeTo: i + 1,
rangeValEncoded: `&${tempEnt};`,
rangeValDecoded: decode(`&${tempEnt};`),
});
pingAmps(whatsOnTheLeft as number, i);
break;
}
}
}
}
}
// if "tempEnt" was not set by now, it is not a known HTML entity
if (!tempEnt) {
console.log(
`1226 ${`\u001b[${90}m${`so it's not one of known named HTML entities`}\u001b[${39}m`}`
);
console.log(
`1229 ${`\u001b[${90}m${`checking for broken recognised entities`}\u001b[${39}m`}`
);
// it's an unrecognised entity:
console.log(`1233 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `bad-html-entity-unrecognised`,
entityName: null,
rangeFrom: whatsOnTheLeft as number,
rangeTo: i + 1,
rangeValEncoded: null,
rangeValDecoded: null,
});
pingAmps(whatsOnTheLeft as number, i);
}
//
//
//
//
// NAMED ENTITIES CLAUSES ABOVE
//
//
//
//
}
}
} else if (
str[whatsEvenMoreToTheLeft as number] === "&" &&
str[i] === ";" &&
i - (whatsEvenMoreToTheLeft as number) < maxLength
) {
//
//
//
//
// CASE 4 - &*...;
//
//
//
//
console.log(
`1271 ${`\u001b[${32}m${`██`}\u001b[${39}m`} might be a messy entity. We have "${str.slice(
whatsEvenMoreToTheLeft as number,
i + 1
)}"`
);
const situation = resemblesNumericEntity(
str,
(whatsEvenMoreToTheLeft as number) + 1,
i
);
console.log(
`1282 ${`\u001b[${32}m${`██ situation:`}\u001b[${39}m`}\n${JSON.stringify(
situation,
null,
4
)}`
);
console.log(
`1290 FIY, ${`\u001b[${33}m${`potentialEntity`}\u001b[${39}m`} = ${JSON.stringify(
potentialEntity,
null,
4
)}`
);
// push the issue:
console.log(`1298 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: `${
/* istanbul ignore next */
situation.probablyNumeric
? "bad-html-entity-malformed-numeric"
: "bad-html-entity-unrecognised"
}`,
entityName: null,
rangeFrom: whatsEvenMoreToTheLeft as number,
rangeTo: i + 1,
rangeValEncoded: null,
rangeValDecoded: null,
});
pingAmps(whatsEvenMoreToTheLeft as number, i);
}
}
// one-character chunks or chunks ending with ampersand get wiped:
letterSeqStartAt = null;
console.log(
`1319 ${`\u001b[${31}m${`RESET`}\u001b[${39}m`} ${`\u001b[${33}m${`letterSeqStartAt`}\u001b[${39}m`} = null`
);
}
// Catch the start of the sequence of latin letters. It's necessary to
// tackle named HTML entity recognition, missing ampersands and semicolons.
if (
letterSeqStartAt === null &&
isLatinLetterOrNumberOrHash(str[i]) &&
str[i + 1]
) {
letterSeqStartAt = i;
console.log(
`1333 SET ${`\u001b[${33}m${`letterSeqStartAt`}\u001b[${39}m`} = ${letterSeqStartAt}`
);
}
// catch amp;
if (str[i] === "a") {
console.log(`1339 ${`\u001b[${90}m${`within a clauses`}\u001b[${39}m`}`);
// 1. catch recursively-encoded cases. They're easy actually, the task will
// be deleting sequence of repeated "amp;" between ampersand and letter.
// For example, we have this:
// text& amp ; a m p ; nbsp;text
// We start at the opening ampersand at index 4;
const singleAmpOnTheRight = rightSeq(str, i, "m", "p", ";");
if (singleAmpOnTheRight) {
console.log(
`1349 ${`\u001b[${90}m${`confirmed amp; from index ${i} onwards`}\u001b[${39}m`}`
);
// if we had to delete all amp;amp;amp; and leave only ampersand, this
// will be the index to delete up to:
let toDeleteAllAmpEndHere = singleAmpOnTheRight.rightmostChar + 1;
console.log(
`1356 SET ${`\u001b[${33}m${`toDeleteAllAmpEndHere`}\u001b[${39}m`} = ${toDeleteAllAmpEndHere}`
);
// so one & is confirmed.
const nextAmpOnTheRight = rightSeq(
str,
singleAmpOnTheRight.rightmostChar,
"a",
"m",
"p",
";"
);
if (nextAmpOnTheRight) {
console.log(
`1370 ${`\u001b[${90}m${`confirmed another amp; on the right of index ${singleAmpOnTheRight.rightmostChar}`}\u001b[${39}m`}`
);
toDeleteAllAmpEndHere = nextAmpOnTheRight.rightmostChar + 1;
console.log(
`1375 SET ${`\u001b[${33}m${`toDeleteAllAmpEndHere`}\u001b[${39}m`} = ${toDeleteAllAmpEndHere}`
);
let temp;
do {
console.log(
`1381 ${`\u001b[${36}m${`======== loop ========`}\u001b[${39}m`}`
);
temp = rightSeq(str, toDeleteAllAmpEndHere - 1, "a", "m", "p", ";");
console.log(
`1385 ${`\u001b[${36}m${`temp = ${JSON.stringify(
temp,
null,
4
)}`}\u001b[${39}m`}`
);
if (temp) {
toDeleteAllAmpEndHere = temp.rightmostChar + 1;
console.log(
`1395 ${`\u001b[${36}m${`another amp; confirmed! Now`}\u001b[${39}m`} ${`\u001b[${33}m${`toDeleteAllAmpEndHere`}\u001b[${39}m`} = ${JSON.stringify(
toDeleteAllAmpEndHere,
null,
4
)};`
);
}
} while (temp);
console.log(
`1405 FINAL ${`\u001b[${32}m${`toDeleteAllAmpEndHere`}\u001b[${39}m`} = ${JSON.stringify(
toDeleteAllAmpEndHere,
null,
4
)}`
);
}
// What we have is toDeleteAllAmpEndHere which marks where the last amp;
// semicolon ends (were we to delete the whole thing).
// For example, in:
// text& amp ; a m p ; a m p ; nbsp;text
// this would be index 49, the "n" from "nbsp;"
const firstCharThatFollows: number | null = right(
str,
toDeleteAllAmpEndHere - 1
);
const secondCharThatFollows = firstCharThatFollows
? right(str, firstCharThatFollows)
: null;
console.log(
`1427 SET initial ${`\u001b[${33}m${`firstCharThatFollows`}\u001b[${39}m`} = str[${firstCharThatFollows}] = ${
str[firstCharThatFollows as number]
}; ${`\u001b[${33}m${`secondCharThatFollows`}\u001b[${39}m`} = str[${secondCharThatFollows}] = ${
str[secondCharThatFollows as number]
}`
);
// If entity follows, for example,
// text& amp ; a m p ; a m p ; nbsp;text
// we delete from the first ampersand to the beginning of that entity.
// Otherwise, we delete only repetitions of amp; + whitespaces in between.
let matchedTemp = "";
let matchedVal;
if (
secondCharThatFollows &&
Object.prototype.hasOwnProperty.call(
entStartsWith,
str[firstCharThatFollows as number]
) &&
Object.prototype.hasOwnProperty.call(
entStartsWith[str[firstCharThatFollows as number]],
str[secondCharThatFollows]
) &&
(entStartsWith as Obj)[str[firstCharThatFollows as number]][
str[secondCharThatFollows]
].some((entity: string) => {
// if (str.entStartsWith(`${entity};`, firstCharThatFollows)) {
const matchEntityOnTheRight = rightSeq(
str,
toDeleteAllAmpEndHere - 1,
...entity.split("")
);
/* istanbul ignore else */
if (matchEntityOnTheRight) {
matchedTemp = entity;
matchedVal = matchEntityOnTheRight;
return true;
}
})
) {
doNothingUntil =
(firstCharThatFollows as number) + matchedTemp.length + 1;
console.log(
`1470 ${`\u001b[${31}m${`██ ACTIVATE doNothingUntil = ${doNothingUntil}`}\u001b[${39}m`}`
);
console.log(
`1474 ENTITY ${`\u001b[${32}m${matchedTemp}\u001b[${39}m`} FOLLOWS`
);
// is there ampersand on the left of "i", the first amp;?
/* istanbul ignore next */
const whatsOnTheLeft = left(str, i) || 0;
/* istanbul ignore else */
if (str[whatsOnTheLeft as number] === "&") {
console.log(`1482 ampersand on the left`);
console.log(
`1484 ${`\u001b[${33}m${`matchedTemp`}\u001b[${39}m`} = ${JSON.stringify(
matchedTemp,
null,
4
)}; ${`\u001b[${33}m${`matchedVal`}\u001b[${39}m`} = ${JSON.stringify(
matchedVal,
null,
4
)}`
);
console.log(`1494 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: "bad-html-entity-multiple-encoding",
entityName: matchedTemp,
rangeFrom: whatsOnTheLeft,
rangeTo: doNothingUntil,
rangeValEncoded: `&${matchedTemp};`,
rangeValDecoded: decode(`&${matchedTemp};`),
});
pingAmps(whatsOnTheLeft as number, i);
} else if (whatsOnTheLeft) {
// we need to add the ampersand as well. Now, another consideration
// appears: whitespace and where exactly to put it. Algorithmically,
// right here, at this first letter "a" from "amp;&<some-entity>;"
const rangeFrom = i;
console.log(`1509 rangeFrom = ${rangeFrom}`);
const spaceReplacement = "";
if (str[i - 1] === " ") {
console.log(`1513`);
// chomp spaces to the left, but otherwise, don't touch anything
// TODO
}
console.log(`1517 final rangeFrom = ${rangeFrom}`);
/* istanbul ignore else */
if (typeof opts.cb === "function") {
console.log(`1521 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
rangesArr2.push({
ruleName: "bad-html-entity-multiple-encoding",
entityName: matchedTemp,
rangeFrom,
rangeTo: doNothingUntil,
rangeValEncoded: `${spaceReplacement}&${matchedTemp};`,
rangeValDecoded: `${spaceReplacement}${decode(
`&${matchedTemp};`
)}`,
});
pingAmps(rangeFrom, i);
}
}
}
}
}
// catch #x of messed up entities without ampersand (like #x26;)
if (
str[i] === "#" &&
right(str, i) &&
str[right(str, i) as number].toLowerCase() === "x" &&
(!str[i - 1] || !left(str, i) || str[left(str, i) as number] !== "&")
) {
console.log(
`1547 ${`\u001b[${31}m${`██`}\u001b[${39}m`} #x pattern caught`
);
if (isNumeric(str[right(str, right(str, i) as number) as number])) {
brokenNumericEntityStartAt = i;
}
}
// |
// |
// |
// |
// |
// PART 3. RULES AT THE BOTTOM
// |
// |
// |
// |
// |
// ampersand catches are at the bottom to prevent current index
// being tangled into the catch-logic of a previous entity
if (str[i] === "&") {
ampPositions.push(i);
console.log(
`1571 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} to ${`\u001b[${33}m${`ampPositions`}\u001b[${39}m`} now = ${JSON.stringify(
ampPositions,
null,
4
)}`
);
}
if (
!str[i] &&
typeof opts.textAmpersandCatcherCb === "function" &&
ampPositions.length
) {
console.log(
`1585 ${`\u001b[${32}m${`PING last remaining amp indexes`}\u001b[${39}m`}`
);
pingAmps();
}
console.log("---------------");
console.log(
`1592 ${`\u001b[${90}m${`letterSeqStartAt = ${letterSeqStartAt}`}\u001b[${39}m`}`
);
console.log(
`1595 ${`\u001b[${90}m${`ampPositions = ${JSON.stringify(
ampPositions,
null,
4
)}`}\u001b[${39}m`}`
);
counter += 1;
}
// ^
// /|\
// / | \
// / | \
// / | \
// / | \
// |
// |
// T H E L O O P E N D S
// |
// |
// |
// |
// |
// |
if (!rangesArr2.length) {
console.log(`1621 ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`} empty array`);
return [];
}
console.log(
`1626 IN THE END, before merge rangesArr2 = ${JSON.stringify(
rangesArr2,
null,
4
)}`
);
// return rangesArr2.map(opts.cb);
// if any two issue objects have identical "from" indexes, remove the one
// which spans more. For example, [4, 8] and [4, 12] would end up [4, 12]
// winning and [4, 8] removed. Obviously, it's not arrays, it's objects,
// format for example
// {
// "ruleName": "bad-html-entity-malformed-amp",
// "entityName": "amp",
// "rangeFrom": 4,
// "rangeTo": 8,
// "rangeValEncoded": "&",
// "rangeValDecoded": "&"
// },
// so instead of [4, 8] that would be [rangeFrom, rangeTo]...
const res: any = rangesArr2.filter((filteredRangeObj, i) =>
rangesArr2.every(
(oneOfEveryObj, y) =>
i === y ||
!(
filteredRangeObj.rangeFrom >= oneOfEveryObj.rangeFrom &&
filteredRangeObj.rangeTo < oneOfEveryObj.rangeTo
)
)
);
/* istanbul ignore else */
if (typeof opts.cb === "function") {
console.log(`1661 ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`} mapped`);
return res.map(opts.cb);
}
console.log(
`1666 RETURN ${`\u001b[${33}m${`res`}\u001b[${39}m`} = ${JSON.stringify(
res,
null,
4
)}`
);
/* istanbul ignore next */
return res;
}
export { fixEnt, version, allRules }; | the_stack |
import * as dat from "dat.gui";
import gsap from "gsap";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import Stats from "three/examples/jsm/libs/stats.module.js";
import { Line2 } from "three/examples/jsm/lines/Line2.js";
import { LineGeometry } from "three/examples/jsm/lines/LineGeometry.js";
import { LineMaterial } from "three/examples/jsm/lines/LineMaterial.js";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js";
import { SVGLoader } from "three/examples/jsm/loaders/SVGLoader";
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
import { ShaderPass } from "three/examples/jsm/postprocessing/ShaderPass";
import { UnrealBloomPass } from "three/examples/jsm/postprocessing/UnrealBloomPass.js";
import { FXAAShader } from "three/examples/jsm/shaders/FXAAShader.js";
import { GammaCorrectionShader } from "three/examples/jsm/shaders/GammaCorrectionShader.js";
import { WEBGL } from "three/examples/jsm/WebGL.js";
import { toThreeColor } from "utils/color";
import { computeAABB } from "utils/math";
import { loadSVG } from "utils/svg";
import { createTexObject } from "utils/tex";
import TextMeshObject from "./objects/TextMeshObject";
import "./style/player.css";
import { GlitchPass } from "./utils/GlitchPass";
import WebmMediaRecorder from "./utils/WebmMediaRecorder";
const DEFAULT_LINE_WIDTH = 0.02;
const defaultEase = "power2.out";
const DEG2RAD = Math.PI / 180;
declare class CCapture {
constructor(params: any);
}
gsap.ticker.remove(gsap.updateRoot);
let isRunning = false;
let glitchPassEnabled = false;
let renderTargetWidth = 1920;
let renderTargetHeight = 1080;
let motionBlurSamples = 1;
let bloomEnabled = false;
let globalTimeline = gsap.timeline({ onComplete: stopRender });
const mainTimeline = gsap.timeline();
let stats: Stats;
let capturer: CCapture;
let renderer: THREE.WebGLRenderer;
let composer: EffectComposer;
let currentLayer = "default";
let scene = new THREE.Scene();
let camera: THREE.Camera;
let uiScene = new THREE.Scene();
let uiCamera: THREE.Camera;
let renderTarget: THREE.WebGLMultisampleRenderTarget;
let lightGroup: THREE.Group;
let cameraControls: OrbitControls;
let glitchPass: any;
let gridHelper: THREE.GridHelper;
let backgroundAlpha = 1.0;
let fxaaEnabled: boolean = false;
let lastTimestamp: number;
let timeElapsed = 0;
let recorder: WebmMediaRecorder;
globalTimeline.add(mainTimeline, "0");
let options = {
format: "webm",
framerate: 30,
render: function () {
startRender();
},
timeline: 0,
};
const seedrandom = require("seedrandom");
let rng = seedrandom("hello.");
const commandQueue: Function[] = [];
function startRender({ resetTiming = true, name = document.title } = {}) {
if (gridHelper !== undefined) {
gridHelper.visible = false;
}
if (resetTiming) {
// Reset gsap
gsap.ticker.remove(gsap.updateRoot);
lastTimestamp = undefined;
}
if (options.format == "webm-fast") {
if (!recorder) {
recorder = new WebmMediaRecorder({ name, framerate: options.framerate });
}
recorder.start();
} else {
capturer = new CCapture({
verbose: true,
display: false,
framerate: options.framerate,
motionBlurFrames: motionBlurSamples,
quality: 100,
format: options.format,
workersPath: "dist/src/",
timeLimit: 0,
frameLimit: 0,
autoSaveTime: 0,
name,
});
(capturer as any).start();
}
(window as any).movy.isRendering = true;
}
(window as any).movy = {
startRender,
isRendering: false,
};
function stopRender() {
if (options.format == "webm-fast") {
if (recorder) {
recorder.stop();
}
} else {
if (capturer) {
(capturer as any).stop();
(capturer as any).save();
capturer = undefined;
}
}
(window as any).movy.isRendering = false;
}
function createOrthographicCamera() {
const aspect = renderTargetWidth / renderTargetHeight;
const viewportHeight = 10;
const camera = new THREE.OrthographicCamera(
(viewportHeight * aspect) / -2,
(viewportHeight * aspect) / 2,
viewportHeight / 2,
viewportHeight / -2,
-1000,
1000
);
camera.position.set(0, 0, 10);
return camera;
}
function createPerspectiveCamera(): THREE.Camera {
// This will ensure the size of 10 in the vertical direction.
const camera = new THREE.PerspectiveCamera(
60,
renderTargetWidth / renderTargetHeight,
0.1,
5000
);
camera.position.set(0, 0, 8.66);
camera.lookAt(new THREE.Vector3(0, 0, 0));
return camera;
}
function setupScene() {
if (WEBGL.isWebGL2Available() === false) {
document.body.appendChild(WEBGL.getWebGL2ErrorMessage());
return;
}
// Create renderer
renderer = new THREE.WebGLRenderer({
alpha: true,
});
renderer.localClippingEnabled = true;
renderer.setSize(renderTargetWidth, renderTargetHeight);
renderer.setClearColor(0x000000, backgroundAlpha);
document.body.appendChild(renderer.domElement);
{
stats = Stats();
// stats.showPanel(1); // 0: fps, 1: ms, 2: mb, 3+: custom
document.body.appendChild(stats.dom);
}
scene.background = new THREE.Color(0);
if (!camera) {
camera = createOrthographicCamera();
}
uiCamera = createOrthographicCamera();
cameraControls = new OrbitControls(camera, renderer.domElement);
// Create multi-sample render target in order to reduce aliasing (better
// quality than FXAA).
renderTarget = new THREE.WebGLMultisampleRenderTarget(
renderTargetWidth,
renderTargetHeight
);
renderTarget.samples = 8; // TODO: don't hardcode
composer = new EffectComposer(renderer, renderTarget);
composer.setSize(renderTargetWidth, renderTargetHeight);
// Glitch pass
if (glitchPassEnabled) {
glitchPass = new GlitchPass();
composer.addPass(glitchPass);
}
// Always use a render pass for gamma correction. This avoid adding an extra
// copy pass to resolve MSAA samples.
composer.insertPass(new ShaderPass(GammaCorrectionShader), 1);
// Bloom pass
if (bloomEnabled) {
let bloomPass = new UnrealBloomPass(
new THREE.Vector2(renderTargetWidth, renderTargetHeight),
0.5, // Strength
0.4, // radius
0.85 // threshold
);
composer.addPass(bloomPass);
// TODO: find a better way to remove the aliasing introduced in BloomPass.
fxaaEnabled = true;
}
if (fxaaEnabled) {
const fxaaPass = new ShaderPass(FXAAShader);
const ratio = renderer.getPixelRatio();
fxaaPass.uniforms["resolution"].value.x = 1 / (renderTargetWidth * ratio);
fxaaPass.uniforms["resolution"].value.y = 1 / (renderTargetHeight * ratio);
composer.addPass(fxaaPass);
}
}
function animate() {
// time /* `time` parameter is buggy in `ccapture`. Do not use! */
const nowInSecs = Date.now() / 1000;
requestAnimationFrame(animate);
let delta: number;
{
// Compute `timeElapsed`. This works for both animation preview and capture.
if (lastTimestamp === undefined) {
delta = 0.000001;
lastTimestamp = nowInSecs;
globalTimeline.seek(0, false);
} else {
delta = nowInSecs - lastTimestamp;
lastTimestamp = nowInSecs;
}
timeElapsed += delta;
}
gsap.updateRoot(timeElapsed);
scene.traverse((child: any) => {
if (typeof child.update === "function") {
child.update(delta);
}
});
renderer.setRenderTarget(renderTarget);
// Render scene
renderer.render(scene, camera);
// Render UI on top of the scene
renderer.autoClearColor = false;
renderer.render(uiScene, uiCamera);
renderer.autoClearColor = true;
renderer.setRenderTarget(null);
// Post processing
composer.readBuffer = renderTarget;
composer.render();
stats.update();
if (capturer) (capturer as any).capture(renderer.domElement);
}
interface MoveCameraParameters extends Transform, AnimationParameters {
lookAt?: { x?: number; y?: number; z?: number } | [number, number, number?];
fov?: number;
zoom?: number;
}
export function cameraMoveTo(params: MoveCameraParameters = {}) {
commandQueue.push(() => {
const { t, lookAt, duration = 0.5, ease = defaultEase, fov, zoom } = params;
const tl = gsap.timeline({
defaults: {
duration,
ease,
onUpdate: () => {
// Keep looking at the target while camera is moving.
if (lookAt) {
camera.lookAt(toThreeVector3(lookAt));
}
},
},
});
if (camera instanceof THREE.PerspectiveCamera) {
const perspectiveCamera = camera as THREE.PerspectiveCamera;
// Animate FoV
if (fov !== undefined) {
tl.to(
perspectiveCamera,
{
fov,
onUpdate: () => {
perspectiveCamera.updateProjectionMatrix();
},
},
"<"
);
}
}
createTransformAnimation({
...params,
tl,
object3d: camera,
});
if (zoom !== undefined) {
tl.to(
camera,
{
zoom,
onUpdate: () => {
(camera as any).updateProjectionMatrix();
},
},
"<"
);
}
mainTimeline.add(tl, t);
});
}
export function generateRandomString(length: number) {
let result = "";
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
export function randomInt(min: number, max: number) {
return Math.floor(random() * (max - min + 1)) + min;
}
function createLine3d(
material: THREE.Material,
{
points = [],
lineWidth = 0.1,
}: {
color: THREE.Color;
points: THREE.Vector3[];
lineWidth: number;
}
) {
if (points.length === 0) {
points.push(new THREE.Vector3(-1.73, -1, 0));
points.push(new THREE.Vector3(1.73, -1, 0));
points.push(new THREE.Vector3(0, 2, 0));
points.push(points[0]);
}
let lineColor = new THREE.Color(0xffffff);
let style = SVGLoader.getStrokeStyle(
lineWidth,
lineColor.getStyle(),
"miter",
"butt",
4
);
// style.strokeLineJoin = "round";
let geometry = SVGLoader.pointsToStroke(points, style, 12, 0.001);
let mesh = new THREE.Mesh(geometry, material);
return mesh;
}
function getAllMaterials(object3d: THREE.Object3D): THREE.Material[] {
const materials = new Set<THREE.Material>();
const getMaterialsRecursive = (object3d: THREE.Object3D) => {
const mesh = object3d as THREE.Mesh;
if (mesh && mesh.material) {
materials.add(mesh.material as THREE.Material);
}
if (object3d.children) {
object3d.children.forEach((child) => {
getMaterialsRecursive(child);
});
}
};
getMaterialsRecursive(object3d);
return Array.from(materials);
}
function createFadeInAnimation(
object3d: THREE.Object3D,
{ duration = 0.25, ease = "linear" }: AnimationParameters = {}
) {
const tl = gsap.timeline();
// Set initial visibility to false.
object3d.visible = false;
tl.set(object3d, { visible: true }, "<");
const materials = getAllMaterials(object3d);
for (const material of materials) {
tl.set(material, { transparent: true }, "<");
tl.from(
material,
{
opacity: 0,
duration,
ease,
},
"<"
);
}
return tl;
}
function createFadeOutAnimation(
obj: THREE.Object3D,
{ duration = 0.25, ease = "linear" }: AnimationParameters = {}
): gsap.core.Timeline {
const tl = gsap.timeline({ defaults: { duration, ease } });
const materials = getAllMaterials(obj);
materials.forEach((material) => {
tl.set(material, { transparent: true }, "<");
tl.to(
material,
{
opacity: 0,
},
"<"
);
});
return tl;
}
function addDefaultLights() {
if (lightGroup === undefined) {
lightGroup = new THREE.Group();
scene.add(lightGroup);
if (0) {
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.9);
directionalLight.position.set(0.3, 1, 0.5);
lightGroup.add(directionalLight);
const ambientLight = new THREE.AmbientLight(0xffffff, 0.1); // soft white light
lightGroup.add(ambientLight);
} else {
// Experiment with HemisphereLight
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.7);
directionalLight.position.set(0.3, 1, 0.5);
lightGroup.add(directionalLight);
const hemiLight = new THREE.HemisphereLight(0xffffff, 0x3f3f3f, 0.3);
lightGroup.add(hemiLight);
}
}
}
function createExplosionAnimation(
objectGroup: THREE.Object3D,
{
ease = "expo.out",
duration = 2,
minRotation = -4 * Math.PI,
maxRotation = 4 * Math.PI,
minRadius = 1,
maxRadius = 4,
minScale = 1,
maxScale = 1,
stagger = 0.03,
} = {}
) {
const tl = gsap.timeline({
defaults: {
duration,
ease: ease,
},
});
let delay = 0;
objectGroup.children.forEach((child, i) => {
const r = minRadius + (maxRadius - minRadius) * rng();
const theta = rng() * 2 * Math.PI;
const x = r * Math.cos(theta);
const y = r * Math.sin(theta);
child.position.z += 0.01 * i; // z-fighting
tl.fromTo(child.position, { x: 0, y: 0 }, { x, y }, delay);
const rotation = minRotation + rng() * (maxRotation - minRotation);
tl.fromTo(child.rotation, { z: 0 }, { z: rotation }, delay);
const targetScale = child.scale.setScalar(
minScale + (maxScale - minScale) * rng()
);
tl.fromTo(
child.scale,
{ x: 0.001, y: 0.001, z: 0.001 },
{ x: targetScale.x, y: targetScale.y, z: targetScale.z },
delay
);
delay += stagger;
});
return tl;
}
function createGroupFlyInAnimation(
objectGroup: THREE.Object3D,
{ ease = "expo.out", duration = 1, stagger = 0 } = {}
) {
const tl = gsap.timeline({
defaults: {
duration,
ease: ease,
},
});
let delay = 0;
objectGroup.children.forEach((child) => {
const targetScale = child.scale.clone().multiplyScalar(0.01);
tl.from(
child.scale,
{ x: targetScale.x, y: targetScale.y, z: targetScale.z },
delay
);
delay += stagger;
});
return tl;
}
// Deprecated
function getCompoundBoundingBox(object3D: THREE.Object3D) {
let box: THREE.Box3;
object3D.traverse(function (obj3D: any) {
const geometry = obj3D.geometry;
if (geometry === undefined) {
return;
}
geometry.computeBoundingBox();
if (box === undefined) {
box = geometry.boundingBox;
} else {
box.union(geometry.boundingBox);
}
});
return box;
}
export function addGlitch({ duration = 0.2, t }: AnimationParameters = {}) {
glitchPassEnabled = true;
commandQueue.push(() => {
const tl = gsap.timeline();
tl.set(glitchPass, { factor: 1 });
tl.set(glitchPass, { factor: 0 }, `<${duration}`);
mainTimeline.add(tl, t);
});
}
export function run() {
if (isRunning) return;
isRunning = true;
(async () => {
setupScene();
for (const cmd of commandQueue) {
if (typeof cmd === "function") {
const ret = cmd();
if (ret instanceof Promise) {
await ret;
}
} else {
throw `invalid command`;
}
}
// Always Add 0.5s to the end of animation to avoid zero-length video.
if (mainTimeline.duration() < Number.EPSILON) {
mainTimeline.set({}, {}, "+=0.5");
}
{
// Create UI controls
const gui = new dat.GUI();
gui.add(options, "format", ["webm", "webm-fast", "png"]);
gui.add(options, "framerate", [10, 25, 30, 60, 120]);
gui.add(options, "render");
options.timeline = 0;
gui
.add(options, "timeline", 0, globalTimeline.totalDuration())
.onChange((val) => {
globalTimeline.seek(val, false);
});
Object.keys(globalTimeline.labels).forEach((key) => {
console.log(`${key} ${globalTimeline.labels[key]}`);
});
const folder = gui.addFolder("Timeline Labels");
const labels: any = {};
Object.keys(globalTimeline.labels).forEach((key) => {
const label = key;
const time = globalTimeline.labels[key];
console.log(this);
labels[label] = () => {
globalTimeline.seek(time, false);
};
folder.add(labels, label);
});
}
if (0) {
// Grid helper
const size = 20;
const divisions = 20;
const colorCenterLine = "#008800";
const colorGrid = "#888888";
gridHelper = new THREE.GridHelper(
size,
divisions,
new THREE.Color(colorCenterLine),
new THREE.Color(colorGrid)
);
gridHelper.rotation.x = Math.PI / 2;
scene.add(gridHelper);
}
// Start animation
requestAnimationFrame(animate);
})();
}
function createArrow2DGeometry(arrowLength: number) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
// prettier-ignore
new THREE.BufferAttribute(new Float32Array([
-0.5 * arrowLength, -0.5 * arrowLength, 0,
0.5 * arrowLength, -0.5 * arrowLength, 0,
0, 0.5 * arrowLength, 0
]), 3)
);
geometry.computeVertexNormals();
return geometry;
}
interface CreateArrowLineParameters extends BasicMaterial {
lineWidth?: number;
arrowEnd?: boolean;
arrowStart?: boolean;
threeDimensional?: boolean;
}
function createArrowLine(
from: THREE.Vector3,
to: THREE.Vector3,
params: CreateArrowLineParameters = {}
) {
const {
lineWidth = DEFAULT_LINE_WIDTH,
arrowEnd = true,
arrowStart = false,
threeDimensional = false,
} = params;
const material = createMaterial(params);
const direction = new THREE.Vector3();
direction.subVectors(to, from);
const halfLength = direction.length() * 0.5;
direction.subVectors(to, from).normalize();
const center = new THREE.Vector3();
center.addVectors(from, to).multiplyScalar(0.5);
const quaternion = new THREE.Quaternion(); // create one and reuse it
quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);
const group = new THREE.Group();
let length = halfLength * 2;
const arrowLength = lineWidth * 10;
let offset = 0;
{
// Create line
if (arrowEnd) {
length -= arrowLength;
offset -= 0.5 * arrowLength;
}
if (arrowStart) {
length -= arrowLength;
offset += 0.5 * arrowLength;
}
const geometry = !threeDimensional
? new THREE.PlaneGeometry(lineWidth, length)
: new THREE.CylinderGeometry(lineWidth / 2, lineWidth / 2, length, 16);
const line = new THREE.Mesh(geometry, material);
line.position.copy(direction.clone().multiplyScalar(offset).add(center));
line.setRotationFromQuaternion(quaternion);
group.add(line);
}
// Create arrows
for (let i = 0; i < 2; i++) {
if (i === 0 && !arrowStart) continue;
if (i === 1 && !arrowEnd) continue;
const geometry = !threeDimensional
? createArrow2DGeometry(arrowLength)
: new THREE.ConeGeometry(arrowLength * 0.5, arrowLength, 32);
geometry.translate(0, -arrowLength / 2, 0);
const arrow = new THREE.Mesh(geometry, material);
arrow.setRotationFromQuaternion(quaternion);
arrow.position.copy(i === 0 ? from : to);
group.add(arrow);
if (i === 0) arrow.rotateZ(Math.PI);
}
return group;
}
async function loadTexture(url: string): Promise<THREE.Texture> {
return new Promise((resolve, reject) => {
new THREE.TextureLoader().load(url, (texture) => {
resolve(texture);
});
});
}
export function getPolygonVertices({ sides = 3, radius = 0.5 } = {}) {
const verts: [number, number][] = [];
for (let i = 0; i < sides; i++) {
verts.push([
radius * Math.sin((2 * i * Math.PI) / sides),
radius * Math.cos((2 * i * Math.PI) / sides),
]);
}
return verts;
}
export function getTriangleVertices({
radius = 0.5,
}: { radius?: number } = {}) {
return getPolygonVertices({ sides: 3, radius });
}
interface AnimationParameters {
t?: number | string;
duration?: number;
ease?: string;
}
interface MoveObjectParameters extends Transform, AnimationParameters {}
interface Shake2DParameters extends AnimationParameters {
interval?: number;
strength?: number;
}
interface FadeObjectParameters extends AnimationParameters {
opacity?: number;
}
interface WipeInParameters extends AnimationParameters {
direction?: "up" | "down" | "left" | "right";
}
interface RevealParameters extends AnimationParameters {
direction?: "up" | "down" | "left" | "right";
}
interface RotateParameters extends AnimationParameters {
x?: number;
y?: number;
repeat?: number;
}
function createTransformAnimation({
position,
x,
y,
z,
rx,
ry,
rz,
sx,
sy,
sz,
scale,
tl,
object3d,
}: {
x?: number | ((t: number) => number);
y?: number | ((t: number) => number);
z?: number | ((t: number) => number);
rx?: number;
ry?: number;
rz?: number;
sx?: number;
sy?: number;
sz?: number;
position?: [number, number] | [number, number, number];
scale?: number;
tl: gsap.core.Timeline;
object3d: THREE.Object3D;
}) {
if (position) {
const p = toThreeVector3(position);
tl.to(object3d.position, { x: p.x, y: p.y, z: p.z }, "<");
} else {
if (x !== undefined) tl.to(object3d.position, { x }, "<");
if (y !== undefined) tl.to(object3d.position, { y }, "<");
if (z !== undefined) tl.to(object3d.position, { z }, "<");
}
if (rx !== undefined) tl.to(object3d.rotation, { x: rx }, "<");
if (ry !== undefined) tl.to(object3d.rotation, { y: ry }, "<");
if (rz !== undefined) tl.to(object3d.rotation, { z: rz }, "<");
if (scale !== undefined) {
tl.to(
object3d.scale,
{
x: scale,
y: scale,
z: scale,
},
"<"
);
} else {
if (sx !== undefined) tl.to(object3d.scale, { x: sx }, "<");
if (sy !== undefined) tl.to(object3d.scale, { y: sy }, "<");
if (sz !== undefined) tl.to(object3d.scale, { z: sz }, "<");
}
}
function createLine(
positions: number[],
{
lineWidth,
color,
}: { lineWidth?: number; color?: string | number; opacity?: number } = {}
) {
const geometry = new LineGeometry();
geometry.setPositions(positions);
const material = new LineMaterial({
color: toThreeColor(color).getHex(),
linewidth: lineWidth || DEFAULT_LINE_WIDTH,
worldUnits: true,
});
const line = new Line2(geometry, material);
return { line, geometry, material };
}
class SceneObject {
object3D: THREE.Object3D;
children: SceneObject[] = [];
protected addObjectToScene(obj: SceneObject, transform: Transform) {
if (transform.parent) {
transform.parent.object3D.add(obj.object3D);
} else {
console.assert(obj.object3D);
this.object3D.add(obj.object3D);
}
}
private add3DGeometry(
params: AddObjectParameters = {},
geometry: THREE.BufferGeometry
) {
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
if (params.lighting === undefined) params.lighting = true;
const material = createMaterial(params);
obj.object3D = new THREE.Group();
obj.object3D.add(new THREE.Mesh(geometry, material));
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
_addMesh(mesh: THREE.Mesh, params: AddObjectParameters = {}): SceneObject {
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
addDefaultLights();
obj.object3D = mesh;
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
clone() {
const obj = new SceneObject();
commandQueue.push(async () => {
obj.object3D = this.object3D.clone();
obj.object3D.traverse((node) => {
const mesh = node as THREE.Mesh;
if (mesh.isMesh) {
mesh.material = Array.isArray(mesh.material)
? mesh.material.map((material) => material.clone())
: mesh.material.clone();
}
});
this.object3D.parent.add(obj.object3D);
});
return obj;
}
addGroup(params: AddGroupParameters = {}) {
const obj = new GroupObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(() => {
obj.object3D = new THREE.Group();
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
add3DModel(url: string, params: AddObjectParameters = {}): SceneObject {
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
addDefaultLights();
const object = await loadObj(url);
const aabb = computeAABB(object);
const size = new THREE.Vector3();
aabb.getSize(size);
const length = Math.max(size.x, size.y, size.z);
object.scale.divideScalar(length);
const center = new THREE.Vector3();
aabb.getCenter(center);
center.divideScalar(length);
object.position.sub(center);
const group = new THREE.Group();
group.add(object);
if (params.wireframe || params.color || params.opacity !== undefined) {
const material = createMaterial({ ...params, lighting: true });
object.traverse((o: any) => {
if (o.isMesh) o.material = material;
});
}
obj.object3D = group;
updateTransform(group, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addCircle(params: AddCircleParameters = {}): SceneObject {
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
if (params.lighting === undefined) params.lighting = false;
const material = createMaterial(params);
const geometry = new THREE.CircleGeometry(params.radius || 0.5, 128);
obj.object3D = new THREE.Group();
obj.object3D.add(new THREE.Mesh(geometry, material));
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addArrow(
p1: [number, number, number?],
p2: [number, number, number?],
params: AddArrowParameters = {}
): SceneObject {
// For back compat
if (!Array.isArray(p1)) {
params = p1;
p1 = (params as any).from;
p2 = (params as any).to;
}
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
const {
lineWidth = DEFAULT_LINE_WIDTH,
arrowStart = false,
arrowEnd = true,
} = params;
commandQueue.push(async () => {
addDefaultLights();
if (params.lighting === undefined) params.lighting = false;
obj.object3D = createArrowLine(toThreeVector3(p1), toThreeVector3(p2), {
arrowStart,
arrowEnd,
lineWidth,
color: params.color,
});
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addDoubleArrow(
p1: [number, number, number?],
p2: [number, number, number?],
params: AddLineParameters = {}
): SceneObject {
return this.addArrow(p1, p2, {
...params,
arrowStart: true,
arrowEnd: true,
});
}
addAxes2D(params: AddAxes2DParameters = {}): SceneObject {
const {
xRange = [-4, 4],
yRange = [-4, 4],
tickIntervalX = 1,
tickIntervalY = 1,
showTicks = true,
showTickLabels = true,
} = params;
const textScale = 0.25;
const stickLabelSpacing = 0.2;
const stickLength = 0.2;
const obj = this.addGroup(params);
if (showTicks) {
// X ticks
const numTicksX = Math.floor((xRange[1] - xRange[0]) / tickIntervalX);
for (let i = 0; i <= numTicksX; i++) {
const x = xRange[0] + i * tickIntervalX;
if (x !== 0) {
obj.addLine([x, -stickLength * 0.5], [x, stickLength * 0.5], {
lineWidth: DEFAULT_LINE_WIDTH,
});
if (showTickLabels) {
obj.addText(`${x}`, {
x,
y: -stickLabelSpacing,
anchor: "top",
scale: textScale,
font: "math",
});
}
}
}
// Y ticks
const numTicksY = Math.floor((yRange[1] - yRange[0]) / tickIntervalY);
for (let i = 0; i <= numTicksY; i++) {
const y = yRange[0] + i * tickIntervalY;
if (y !== 0) {
obj.addLine([-stickLength * 0.5, y], [stickLength * 0.5, y], {
lineWidth: DEFAULT_LINE_WIDTH,
});
if (showTickLabels) {
obj.addText(`${y}`, {
x: -stickLabelSpacing,
y,
anchor: "right",
scale: textScale,
font: "math",
});
}
}
}
}
obj.addArrow(
[xRange[0] - tickIntervalX * 0.5, 0, 0],
[xRange[1] + tickIntervalX * 0.5, 0, 0],
{
lineWidth: DEFAULT_LINE_WIDTH,
}
);
obj.addArrow(
[0, yRange[0] - tickIntervalY * 0.5, 0],
[0, yRange[1] + tickIntervalY * 0.5, 0],
{
lineWidth: DEFAULT_LINE_WIDTH,
}
);
return obj;
}
addAxes3D(params: AddAxes3DParameters = {}): SceneObject {
const { xRange = [-4, 4], yRange = [-4, 4], zRange = [-4, 4] } = params;
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
obj.object3D = new THREE.Group();
const arrowParams = {
arrowStart: false,
arrowEnd: true,
threeDimensional: true,
lighting: true,
lineWidth: 0.05,
};
obj.object3D.add(
createArrowLine(
new THREE.Vector3(xRange[0], 0, 0),
new THREE.Vector3(xRange[1], 0, 0),
{ ...arrowParams, color: "red" }
)
);
obj.object3D.add(
createArrowLine(
new THREE.Vector3(0, yRange[0], 0),
new THREE.Vector3(0, yRange[1], 0),
{ ...arrowParams, color: "green" }
)
);
obj.object3D.add(
createArrowLine(
new THREE.Vector3(0, 0, zRange[0]),
new THREE.Vector3(0, 0, zRange[1]),
{ ...arrowParams, color: "blue" }
)
);
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addArc(
startAngle: number,
endAngle: number,
radius = 1,
params: AddLineParameters = {}
): SceneObject {
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
addDefaultLights();
if (params.lighting === undefined) params.lighting = false;
const curve = new THREE.EllipseCurve(
0,
0,
radius,
radius,
startAngle * DEG2RAD,
endAngle * DEG2RAD,
false,
0
);
const points = curve.getSpacedPoints(64);
const points2 = [];
for (const pt of points) {
points2.push(pt.x, pt.y, 0);
}
const { line } = createLine(points2, params);
obj.object3D = line;
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addGrid(params: AddGridParameters = {}): SceneObject {
const { gridSize = 10, color } = params;
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
obj.object3D = new THREE.GridHelper(
gridSize,
gridSize,
color !== undefined ? toThreeColor(color) : 0x00ff00,
color !== undefined ? toThreeColor(color) : 0xc0c0c0
);
obj.object3D.rotation.x = Math.PI / 2;
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addImage(file: string, params: AddTextParameters = {}): SceneObject {
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
const { color, ccw } = params;
commandQueue.push(async () => {
if (file.endsWith(".svg")) {
obj.object3D = await loadSVG(file, {
ccw,
color,
opacity: params.opacity || 1.0,
});
} else {
const texture = await loadTexture(file);
texture.encoding = THREE.sRGBEncoding;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
const material = new THREE.MeshBasicMaterial({
map: texture,
side: THREE.DoubleSide,
transparent: true,
opacity: params.opacity || 1.0,
color: toThreeColor(color),
});
const aspect = texture.image.width / texture.image.height;
const geometry = new THREE.PlaneBufferGeometry(
aspect > 1 ? aspect : 1,
aspect > 1 ? 1 : 1 / aspect
);
const mesh = new THREE.Mesh(geometry, material);
obj.object3D = mesh;
}
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addLine(
p1: [number, number, number?],
p2: [number, number, number?],
params: AddLineParameters = {}
): SceneObject {
// For back compat
if (!Array.isArray(p1)) {
params = p1;
const from:
| [number, number, number?]
| { x: number; y: number; z: number } = (params as any).from;
const to:
| [number, number, number?]
| { x: number; y: number; z: number } = (params as any).to;
p1 = Array.isArray(from) ? from : [from.x, from.y, from.z];
p2 = Array.isArray(to) ? to : [to.x, to.y, to.z];
}
return this.addPolyline([p1, p2], params);
}
// TODO: extract this into a separate class: LineObject
verts: number[] = [];
addPolyline(
points: [number, number, number?][],
params: AddLineParameters = {}
): SceneObject {
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
let positions: number[];
positions = [];
for (const pt of points) {
positions.push(pt[0], pt[1], pt.length <= 2 ? 0 : pt[2]);
}
obj.verts = positions;
const { geometry, line } = createLine(positions, params);
obj.object3D = line;
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addPyramid(params: AddObjectParameters = {}): SceneObject {
const geometry = new THREE.ConeGeometry(0.5, 1.0, 4, defaultSeg(params));
return this.add3DGeometry(params, geometry);
}
addCube(params: AddObjectParameters = {}): SceneObject {
const geometry = new THREE.BoxGeometry(1, 1, 1);
return this.add3DGeometry(params, geometry);
}
addSphere(params: AddObjectParameters = {}): SceneObject {
const geometry = new THREE.SphereGeometry(
0.5,
defaultSeg(params),
defaultSeg(params)
);
return this.add3DGeometry(params, geometry);
}
addCone(params: AddObjectParameters = {}): SceneObject {
const geometry = new THREE.ConeGeometry(
0.5,
1.0,
defaultSeg(params),
defaultSeg(params)
);
return this.add3DGeometry(params, geometry);
}
addCylinder(params: AddObjectParameters = {}): SceneObject {
const geometry = new THREE.CylinderGeometry(
0.5,
0.5,
1,
defaultSeg(params)
);
return this.add3DGeometry(params, geometry);
}
addTorus(params: AddObjectParameters = {}): SceneObject {
const geometry = new THREE.TorusGeometry(
0.375,
0.125,
defaultSeg(params),
defaultSeg(params)
);
return this.add3DGeometry(params, geometry);
}
addCircleOutline(params: AddCircleOutlineParameters = {}) {
const { lineWidth = DEFAULT_LINE_WIDTH, color } = params;
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
if (params.lighting === undefined) params.lighting = false;
const material = createMaterial(params);
const verts = getPolygonVertices({
sides: 128,
radius: params.radius || 0.5,
});
const v3d = verts.map((v) => new THREE.Vector3(v[0], v[1], 0));
obj.object3D = createLine3d(material, {
points: v3d.concat(v3d[0]),
lineWidth,
color: toThreeColor(color),
});
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addRectOutline(params: AddOutlineParameters = {}) {
const {
width = 1,
height = 1,
lineWidth = DEFAULT_LINE_WIDTH,
color,
} = params;
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
if (params.lighting === undefined) params.lighting = false;
const material = createMaterial(params);
const halfWidth = width * 0.5;
const halfHeight = height * 0.5;
obj.object3D = createLine3d(material, {
points: [
new THREE.Vector3(-halfWidth, -halfHeight, 0),
new THREE.Vector3(-halfWidth, halfHeight, 0),
new THREE.Vector3(halfWidth, halfHeight, 0),
new THREE.Vector3(halfWidth, -halfHeight, 0),
new THREE.Vector3(-halfWidth, -halfHeight, 0),
],
lineWidth,
color: toThreeColor(color),
});
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addRect(params: AddRectParameters = {}): SceneObject {
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
if (params.lighting === undefined) params.lighting = false;
const material = createMaterial(params);
const { width = 1, height = 1 } = params;
const geometry = new THREE.PlaneGeometry(width, height);
obj.object3D = new THREE.Group();
obj.object3D.add(new THREE.Mesh(geometry, material));
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addPolygon(
vertices: [number, number][],
params: AddPolygonParameters = {}
): SceneObject {
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
if (params.lighting === undefined) params.lighting = false;
const material = createMaterial(params);
// Vertex positions
const positions: number[] = [];
for (const v of vertices) {
positions.push(v[0], v[1], 0);
}
// Indices
const indices: number[] = [];
for (let i = 0; i < vertices.length - 2; i++) {
indices.push(0, i + 1, i + 2);
}
const geometry = new THREE.BufferGeometry();
geometry.setIndex(indices);
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
obj.object3D = new THREE.Group();
obj.object3D.add(new THREE.Mesh(geometry, material));
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addTriangle(params: AddPolygonParameters = {}): SceneObject {
return this.addPolygon(getTriangleVertices(), params);
}
addTriangleOutline(params: AddOutlineParameters = {}) {
const { lineWidth = DEFAULT_LINE_WIDTH, color } = params;
const obj = new SceneObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
if (params.lighting === undefined) params.lighting = false;
const material = createMaterial(params);
const verts = getPolygonVertices();
const v3d = verts.map((v) => new THREE.Vector3(v[0], v[1], 0));
obj.object3D = createLine3d(material, {
points: v3d.concat(v3d[0]),
lineWidth,
color: toThreeColor(color),
});
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addText(text: string, params: AddTextParameters = {}): TextObject {
const obj = new TextObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
const material = createMaterial({ ...params });
const textObject = new TextMeshObject({
...params,
color: toThreeColor(params.color),
material,
});
await textObject.init();
textObject.setText(text, true);
obj.object3D = textObject;
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addText3D(text: string, params: AddText3DParameters = {}): TextObject {
const obj = new TextObject();
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
const material = createMaterial({
...params,
lighting: params.lighting !== undefined ? params.lighting : true,
});
const textObject = new TextMeshObject({
...params,
color: toThreeColor(params.color),
material,
text3D: true,
});
await textObject.init();
textObject.setText(text, true);
obj.object3D = textObject;
updateTransform(obj.object3D, params);
this.addObjectToScene(obj, params);
});
return obj;
}
addTex(tex: string, params: AddTextParameters = {}): TexObject {
const obj = new TexObject();
obj._initParams = params;
if (params.parent) {
params.parent.children.push(obj);
} else {
this.children.push(obj);
}
commandQueue.push(async () => {
const texObject = await createTexObject(tex, {
color: "#" + toThreeColor(params.color).getHexString(),
});
updateTransform(texObject, params);
obj.object3D = texObject;
this.addObjectToScene(obj, params);
});
return obj;
}
moveTo(params: MoveObjectParameters = {}) {
const { t, duration = 0.5, ease = defaultEase } = params;
commandQueue.push(() => {
let tl = gsap.timeline({
defaults: {
duration,
ease,
},
});
createTransformAnimation({
...params,
tl,
object3d: this.object3D,
});
mainTimeline.add(tl, t);
});
return this;
}
scaleTo(scale: number, params: AnimationParameters = {}) {
const { t, duration = 0.5, ease = defaultEase } = params;
commandQueue.push(() => {
let tl = gsap.timeline({
defaults: {
duration,
ease,
},
});
tl.to(
this.object3D.scale,
{
x: scale,
y: scale,
z: scale,
},
"<"
);
mainTimeline.add(tl, t);
});
return this;
}
scaleXTo(sx: number, params: AnimationParameters = {}) {
const { t, duration = 0.5, ease = defaultEase } = params;
commandQueue.push(() => {
let tl = gsap.timeline({
defaults: {
duration,
ease,
},
});
tl.to(this.object3D.scale, { x: sx }, "<");
mainTimeline.add(tl, t);
});
return this;
}
scaleYTo(sy: number, params: AnimationParameters = {}) {
const { t, duration = 0.5, ease = defaultEase } = params;
commandQueue.push(() => {
let tl = gsap.timeline({
defaults: {
duration,
ease,
},
});
tl.to(this.object3D.scale, { y: sy }, "<");
mainTimeline.add(tl, t);
});
return this;
}
scaleZTo(sz: number, params: AnimationParameters = {}) {
const { t, duration = 0.5, ease = defaultEase } = params;
commandQueue.push(() => {
let tl = gsap.timeline({
defaults: {
duration,
ease,
},
});
tl.to(this.object3D.scale, { z: sz }, "<");
mainTimeline.add(tl, t);
});
return this;
}
fadeIn({ duration = 0.25, ease = "linear", t }: AnimationParameters = {}) {
commandQueue.push(() => {
const tl = createFadeInAnimation(this.object3D, { duration, ease });
mainTimeline.add(tl, t);
});
return this;
}
fadeOut(params: FadeObjectParameters = {}) {
this.changeOpacity(params.opacity === undefined ? 0 : params.opacity, {
...params,
});
return this;
}
changeOpacity(
opacity: number,
{ duration = 0.25, ease = "linear", t }: FadeObjectParameters = {}
) {
commandQueue.push(() => {
const tl = gsap.timeline({ defaults: { duration, ease } });
const materials = getAllMaterials(this.object3D);
for (const material of materials) {
tl.set(material, { transparent: true }, "<");
tl.to(
material,
{
opacity,
},
"<"
);
}
if (opacity == 0) {
tl.set(this.object3D, { visible: false }, ">");
}
mainTimeline.add(tl, t);
});
return this;
}
changeColor(
color: string | number,
{ duration = 0.25, ease = "power1.inOut", t }: AnimationParameters = {}
) {
commandQueue.push(() => {
const tl = gsap.timeline({ defaults: { duration, ease } });
const materials = getAllMaterials(this.object3D);
for (const material of materials) {
if ((material as any).color) {
const destColor = toThreeColor(color);
tl.to(
(material as any).color,
{
r: destColor.r,
g: destColor.g,
b: destColor.b,
},
"<"
);
}
}
mainTimeline.add(tl, t);
});
return this;
}
rotateTo(
rx?: number,
ry?: number,
rz?: number,
{ t, duration = 0.5, ease = defaultEase }: AnimationParameters = {}
) {
commandQueue.push(() => {
const tl = gsap.timeline({ defaults: { duration, ease } });
if (rx !== undefined) {
tl.to(this.object3D.rotation, { x: rx * DEG2RAD }, "<");
}
if (ry !== undefined) {
tl.to(this.object3D.rotation, { y: ry * DEG2RAD }, "<");
}
if (rz !== undefined) {
tl.to(this.object3D.rotation, { z: rz * DEG2RAD }, "<");
}
mainTimeline.add(tl, t);
});
return this;
}
rotateXTo(degrees: number, params: AnimationParameters = {}) {
this.rotateTo(degrees, undefined, undefined, params);
return this;
}
rotateZTo(degrees: number, params: AnimationParameters = {}) {
this.rotateTo(undefined, undefined, degrees, params);
return this;
}
rotateYTo(degrees: number, params: AnimationParameters = {}) {
this.rotateTo(undefined, degrees, undefined, params);
return this;
}
spinning({
t,
duration = 5,
repeat,
ease = "none",
x = Math.PI * 2,
y = -Math.PI * 2,
}: RotateParameters = {}) {
commandQueue.push(() => {
const tl = gsap.timeline({
defaults: { duration, ease, repeat },
});
tl.to(this.object3D.rotation, { x, y }, "<");
mainTimeline.add(tl, t);
});
return this;
}
rotateIn({
t,
duration = 0.5,
ease = defaultEase,
}: AnimationParameters = {}) {
commandQueue.push(() => {
const tl = gsap.timeline({ defaults: { duration, ease } });
tl.from(this.object3D.rotation, { z: Math.PI * 4, duration }, "<");
tl.from(
this.object3D.scale,
{
x: Number.EPSILON,
y: Number.EPSILON,
z: Number.EPSILON,
duration,
},
"<"
);
mainTimeline.add(tl, t);
});
return this;
}
grow({ t, ease = defaultEase, duration = 0.5 }: AnimationParameters = {}) {
commandQueue.push(() => {
this.object3D.visible = false;
const tl = gsap.timeline();
tl.set(this.object3D, { visible: true });
tl.from(
this.object3D.scale,
{ x: 0.01, y: 0.01, z: 0.01, ease, duration },
"<"
);
mainTimeline.add(tl, t);
});
return this;
}
grow2({ t }: AnimationParameters = {}) {
commandQueue.push(() => {
const tl = gsap.timeline();
tl.fromTo(
this.object3D,
{ visible: false },
{ visible: true, ease: "none", duration: 0.001 }
);
tl.from(
this.object3D.scale,
{
x: 0.01,
y: 0.01,
z: 0.01,
ease: "elastic.out(1, 0.75)",
onStart: () => {
this.object3D.visible = true;
},
},
"<"
);
mainTimeline.add(tl, t);
});
return this;
}
grow3({ t }: AnimationParameters = {}) {
commandQueue.push(() => {
mainTimeline.from(
this.object3D.scale,
{
x: 0.01,
y: 0.01,
z: 0.01,
ease: "elastic.out(1, 0.2)",
duration: 1.0,
},
t
);
});
return this;
}
flying({ t, duration = 5 }: AnimationParameters = {}) {
const WIDTH = 30;
const HEIGHT = 15;
commandQueue.push(() => {
const tl = gsap.timeline();
this.object3D.children.forEach((x) => {
tl.fromTo(
x.position,
{
x: rng() * WIDTH - WIDTH / 2,
y: rng() * HEIGHT - HEIGHT / 2,
},
{
x: rng() * WIDTH - WIDTH / 2,
y: rng() * HEIGHT - HEIGHT / 2,
duration,
ease: "none",
},
0
);
});
mainTimeline.add(tl, t);
});
return this;
}
reveal({
direction = "up",
t,
duration = 0.5,
ease = defaultEase,
}: RevealParameters = {}) {
commandQueue.push(() => {
const object3d = this.object3D;
const clippingPlanes: THREE.Plane[] = [];
const box = computeAABB(object3d);
const materials = getAllMaterials(object3d);
const tl = gsap.timeline({
defaults: {
duration,
ease,
},
});
// Attach clipping planes to each material.
tl.set(
{},
{
onComplete: () => {
for (const material of materials) {
material.clippingPlanes = clippingPlanes;
}
},
}
);
tl.fromTo(
object3d,
{ visible: false },
{
visible: true,
duration: 0.001,
},
"<"
);
if (direction === "right") {
clippingPlanes.push(
new THREE.Plane(new THREE.Vector3(1, 0, 0), -box.min.x)
);
tl.from(object3d.position, {
x: object3d.position.x - (box.max.x - box.min.x),
});
} else if (direction === "left") {
clippingPlanes.push(
new THREE.Plane(new THREE.Vector3(-1, 0, 0), box.max.x)
);
tl.from(object3d.position, {
x: object3d.position.x + (box.max.x - box.min.x),
});
} else if (direction === "up") {
clippingPlanes.push(
new THREE.Plane(new THREE.Vector3(0, 1, 0), -box.min.y)
);
tl.from(object3d.position, {
y: object3d.position.y - (box.max.y - box.min.y),
});
} else if (direction === "down") {
clippingPlanes.push(
new THREE.Plane(new THREE.Vector3(0, -1, 0), box.max.y)
);
tl.from(object3d.position, {
y: object3d.position.y + (box.max.y - box.min.y),
});
}
// Detach clipping planes to each material.
tl.set(
{},
{
onComplete: () => {
for (const material of materials) {
material.clippingPlanes = null;
}
},
}
);
mainTimeline.add(tl, t);
});
return this;
}
vertexToAnimate = new Map<number, THREE.Vector3>();
updateVert(
i: number,
position: [number, number, number?],
params: AnimationParameters = {}
) {
commandQueue.push(() => {
if (this.verts.length > 0) {
const mesh = this.object3D as THREE.Mesh;
// TODO: add support for all object types instead of just LineGeometry.
const geometry = mesh.geometry as LineGeometry;
const tl = gsap.timeline({
defaults: { duration: 0.5, ease: defaultEase },
});
const x = this.verts[3 * i];
const y = this.verts[3 * i + 1];
const z = this.verts[3 * i + 2];
const data = { x, y, z };
tl.to(data, {
x: position[0],
y: position[1],
z: position[2] || 0,
onUpdate: () => {
this.verts[3 * i] = data.x;
this.verts[3 * i + 1] = data.y;
this.verts[3 * i + 2] = data.z;
// TODO: perf optimization: multiple vertice update.
geometry.setPositions(this.verts);
},
});
this.verts[3 * i] = position[0];
this.verts[3 * i + 1] = position[1];
this.verts[3 * i + 2] = position[2] || 0;
mainTimeline.add(tl, params.t);
} else {
const mesh = this.object3D as THREE.Mesh;
const geometry = mesh.geometry as THREE.BufferGeometry;
const positions = geometry.attributes.position;
const tl = gsap.timeline({
defaults: { duration: 0.5, ease: defaultEase },
});
let vertex: THREE.Vector3;
if (!this.vertexToAnimate.has(i)) {
vertex = new THREE.Vector3(
positions.getX(i),
positions.getY(i),
positions.getZ(i)
);
this.vertexToAnimate.set(i, vertex);
} else {
vertex = this.vertexToAnimate.get(i);
}
tl.to(vertex, {
x: position[0],
y: position[1],
z: position[2] || 0,
onUpdate: () => {
positions.setXYZ(i, vertex.x, vertex.y, vertex.z);
geometry.attributes.position.needsUpdate = true;
},
});
mainTimeline.add(tl, params.t);
}
});
return this;
}
wipeIn({
direction = "right",
t,
duration = 0.5,
ease = "power.out",
}: WipeInParameters = {}) {
commandQueue.push(() => {
this.object3D.visible = false;
const boundingBox = computeAABB(this.object3D);
const materials = getAllMaterials(this.object3D);
const tl = gsap.timeline({
defaults: { duration, ease },
});
let clipPlane: THREE.Plane;
if (direction === "right") {
clipPlane = new THREE.Plane(new THREE.Vector3(-1, 0, 0));
} else if (direction === "left") {
clipPlane = new THREE.Plane(new THREE.Vector3(1, 0, 0));
} else if (direction === "up") {
clipPlane = new THREE.Plane(new THREE.Vector3(0, -1, 0));
} else if (direction === "down") {
clipPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0));
}
tl.set(this.object3D, {
visible: true,
onComplete: () => {
for (const material of materials) {
material.clippingPlanes = [clipPlane];
}
},
});
if (direction === "right") {
tl.fromTo(
clipPlane,
{ constant: boundingBox.min.x },
{ constant: boundingBox.max.x }
);
} else if (direction === "left") {
tl.fromTo(
clipPlane,
{ constant: boundingBox.min.x },
{ constant: boundingBox.max.x }
);
} else if (direction === "up") {
tl.fromTo(
clipPlane,
{ constant: boundingBox.min.y },
{ constant: boundingBox.max.y }
);
} else if (direction === "down") {
tl.fromTo(
clipPlane,
{ constant: boundingBox.min.y },
{ constant: boundingBox.max.y }
);
}
tl.set(
{},
{
onComplete: () => {
for (const material of materials) {
material.clippingPlanes = null;
}
},
}
);
mainTimeline.add(tl, t);
});
return this;
}
shake2D({
interval = 0.01,
duration = 0.2,
strength = 0.2,
t,
}: Shake2DParameters = {}) {
function R(max: number, min: number) {
return rng() * (max - min) + min;
}
commandQueue.push(() => {
const object3d = this.object3D;
const tl = gsap.timeline({ defaults: { ease: "none" } });
tl.set(object3d, { x: "+=0" }); // this creates a full _gsTransform on object3d
//store the transform values that exist before the shake so we can return to them later
const initProps = {
x: object3d.position.x,
y: object3d.position.y,
rotation: object3d.position.z,
};
//shake a bunch of times
for (var i = 0; i < duration / interval; i++) {
const offset = R(-strength, strength);
tl.to(object3d.position, {
x: initProps.x + offset,
y: initProps.y - offset,
// rotation: initProps.rotation + R(-5, 5)
duration: interval,
});
}
//return to pre-shake values
tl.to(object3d.position, interval, {
x: initProps.x,
y: initProps.y,
// scale: initProps.scale,
// rotation: initProps.rotation
});
mainTimeline.add(tl, t);
});
return this;
}
show({ duration = 0.001, t }: Shake2DParameters = {}) {
commandQueue.push(() => {
const tl = gsap.timeline({ defaults: { ease: "none", duration } });
tl.fromTo(this.object3D, { visible: false }, { visible: true });
mainTimeline.add(tl, t);
});
return this;
}
}
interface ExplodeParameters extends AnimationParameters {
speed?: string;
minRotation?: number;
maxRotation?: number;
minRadius?: number;
maxRadius?: number;
minScale?: number;
maxScale?: number;
stagger?: number;
}
class GroupObject extends SceneObject {
explode2D({
t,
ease = "expo.out",
duration = 2,
minRotation = -2 * Math.PI,
maxRotation = 2 * Math.PI,
minRadius = 0,
maxRadius = 4,
minScale = 1,
maxScale = 1,
stagger = 0,
speed,
}: ExplodeParameters = {}) {
commandQueue.push(() => {
let tl: gsap.core.Timeline;
tl = createExplosionAnimation(this.object3D, {
ease,
duration,
minRotation,
maxRotation,
minRadius,
maxRadius,
minScale,
maxScale,
stagger,
});
mainTimeline.add(tl, t);
});
return this;
}
implode2D({ t = undefined, duration = 0.5 }: AnimationParameters = {}) {
commandQueue.push(() => {
const tl = gsap.timeline({
defaults: {
duration,
ease: "expo.inOut",
},
});
tl.to(
this.object3D.children.map((x) => x.position),
{
x: 0,
y: 0,
},
0
);
tl.to(
this.object3D.children.map((x) => x.scale),
{
x: 0.001,
y: 0.001,
},
0
);
tl.to(
this.object3D.children.map((x) => x.rotation),
{
x: 0,
y: 0,
z: 0,
},
0
);
mainTimeline.add(tl, t);
});
return this;
}
flyIn({ t, duration = 0.5, ease = "power.in" }: AnimationParameters = {}) {
commandQueue.push(() => {
const tl = gsap.timeline({
defaults: {
duration,
ease,
},
});
this.object3D.children.forEach((child) => {
tl.from(child.rotation, { x: -Math.PI / 2 }, "<0.03");
tl.from(
child.position,
{
y: -child.scale.length(),
z: -child.scale.length() * 2,
},
"<"
);
tl.add(createFadeInAnimation(child, { duration }), "<");
});
mainTimeline.add(tl, t);
return tl;
});
return this;
}
}
function addCustomAnimation(
tl: gsap.core.Timeline,
callback: (t: number) => void
) {
const data = { val: 0 };
tl.fromTo(
data,
{ val: 0 },
{
val: 1,
ease: "linear",
onUpdate: () => {
callback(data.val);
},
},
"<"
);
}
interface ChangeTextParameters extends AnimationParameters {
from?: number;
to?: number;
}
interface TypeTextParameters extends AnimationParameters {
interval?: number;
}
class TextObject extends GroupObject {
changeText(
func: (val: number) => any,
{
from = 0,
to = 1,
duration = 5,
ease = "expo.out",
t,
}: ChangeTextParameters = {}
) {
commandQueue.push(() => {
const textObject = this.object3D as any;
const tl = gsap.timeline({ defaults: { duration, ease } });
const data = { val: from };
tl.to(data, {
val: to,
onUpdate: () => {
const text = func(data.val).toString();
textObject.setText(text);
},
});
mainTimeline.add(tl, t);
});
return this;
}
typeText({ t, duration, interval = 0.1 }: TypeTextParameters = {}) {
commandQueue.push(() => {
const textObject = this.object3D as any;
if (duration !== undefined) {
interval = duration / textObject.children.length;
}
const tl = gsap.timeline({
defaults: { duration: interval, ease: "steps(1)" },
});
textObject.children.forEach((letter: any) => {
tl.fromTo(letter, { visible: false }, { visible: true });
});
mainTimeline.add(tl, t);
});
return this;
}
updateText(text: string, params: AnimationParameters = {}) {
commandQueue.push(async () => {
mainTimeline.set(
{},
{
onComplete: () => {
const textMesh = this.object3D as TextMeshObject;
textMesh.setText(text);
},
},
params.t
);
});
}
}
class TexObject extends GroupObject {
_initParams: AddTextParameters;
static transformTexFromTo(
from: TexObject[],
to: TexObject[],
params: AnimationParameters = {}
) {
const { duration = 1, t, ease = defaultEase } = params;
const _rightToLeft = (params as any)._rightToLeft;
commandQueue.push(() => {
const tl = gsap.timeline({ defaults: { ease, duration } });
// From tex objects
const fromTexObjects = [];
for (const o of from) {
tl.set(o.object3D, { visible: true }, "<");
tl.set(o.object3D.children, { visible: true }, "<");
o.object3D.updateWorldMatrix(true, true);
console.assert(o.object3D instanceof THREE.Group);
for (const c of o.object3D.children) {
fromTexObjects.push(c);
}
}
// Dest tex objects
const toTexObjects = [];
for (const o of to) {
o.object3D.updateWorldMatrix(true, true);
console.assert(o.object3D instanceof THREE.Group);
for (const c of o.object3D.children) {
toTexObjects.push(c);
}
}
const matchedDstSymbols = Array(toTexObjects.length).fill(false);
const ii = [...Array(fromTexObjects.length).keys()];
for (let i of _rightToLeft ? ii.reverse() : ii) {
const c1 = fromTexObjects[i];
// find match
let found = false;
const jj = [...Array(toTexObjects.length).keys()];
for (let j of _rightToLeft ? jj.reverse() : jj) {
if (!matchedDstSymbols[j]) {
const c2 = toTexObjects[j];
if (c1.name === c2.name) {
let posInSrcTexObject = c2.getWorldPosition(new THREE.Vector3());
posInSrcTexObject = c1.parent.worldToLocal(posInSrcTexObject);
let scaleInSrcTexObject = c2.getWorldScale(new THREE.Vector3());
scaleInSrcTexObject.divide(
c1.parent.getWorldScale(new THREE.Vector3())
);
createTransformAnimation({
object3d: c1,
x: posInSrcTexObject.x,
y: posInSrcTexObject.y,
z: posInSrcTexObject.z,
sx: scaleInSrcTexObject.x,
sy: scaleInSrcTexObject.y,
sz: scaleInSrcTexObject.z,
tl,
});
found = true;
matchedDstSymbols[j] = true;
break;
}
}
}
if (!found) {
tl.add(
createFadeOutAnimation(c1, { duration, ease: "power4.out" }),
0
);
}
}
for (const i in matchedDstSymbols) {
const c = toTexObjects[i];
if (!matchedDstSymbols[i]) {
// Fade in unmatched symbols in toTextObject
tl.add(createFadeInAnimation(c, { duration, ease: "power4.in" }), 0);
} else {
// Hide matched symbols in toTextObject
c.visible = false;
}
}
// Hide all symbols in srcTexObject
tl.set(fromTexObjects, { visible: false }, "+=0");
// Show all symbols in dstTexObject
tl.set(toTexObjects, { visible: true }, "+=0");
mainTimeline.add(tl, t);
});
}
transformTexTo(
to: TexObject | TexObject[],
params: AnimationParameters = {}
) {
if (to instanceof TexObject) {
to = [to];
}
TexObject.transformTexFromTo([this], to, params);
return this;
}
transformTexFrom(
from: TexObject | TexObject[],
params: AnimationParameters = {}
) {
if (from instanceof TexObject) {
from = [from];
}
TexObject.transformTexFromTo(from, [this], params);
return this;
}
clone() {
const superClone = super.clone();
const copy = Object.assign(new TexObject(), superClone);
commandQueue.push(async () => {
for (var attr in superClone) {
if (superClone.hasOwnProperty(attr)) {
copy[attr] = superClone[attr];
}
}
});
return copy;
}
updateTex(tex: string, params: AnimationParameters = {}) {
commandQueue.push(async () => {
const newTexObject = await createTexObject(tex, {
color: "#" + toThreeColor(this._initParams.color).getHexString(),
});
newTexObject.visible = false;
this.object3D.add(newTexObject);
const tl = gsap.timeline();
tl.set(this.object3D.children, { visible: false }, "<");
tl.set(newTexObject, { visible: true }, "<");
mainTimeline.add(tl, params.t);
});
}
}
interface AddTextParameters extends Transform, BasicMaterial {
font?: "zh" | "en" | "math" | "code" | "gdh";
fontSize?: number;
letterSpacing?: number;
centerTextVertically?: boolean;
ccw?: boolean;
}
interface AddText3DParameters extends AddTextParameters {}
interface AddRectParameters extends Transform, BasicMaterial {
width?: number;
height?: number;
}
interface AddCircleParameters extends Transform, BasicMaterial {
radius?: number;
}
interface AddPolygonParameters extends Transform, BasicMaterial {}
interface AddOutlineParameters extends Transform, BasicMaterial {
lineWidth?: number;
width?: number;
height?: number;
}
interface AddCircleOutlineParameters extends Transform, BasicMaterial {
lineWidth?: number;
radius?: number;
}
function defaultSeg({ wireframe }: AddObjectParameters) {
return wireframe ? 16 : 64;
}
export function _addPanoramicSkybox(file: string) {
const obj = new SceneObject();
commandQueue.push(async () => {
const geometry = new THREE.SphereGeometry(500, 60, 40);
// invert the geometry on the x-axis so that all of the faces point inward
geometry.scale(-1, 1, 1);
const texture = new THREE.TextureLoader().load(file);
texture.encoding = THREE.sRGBEncoding;
const material = new THREE.MeshBasicMaterial({ map: texture });
const skySphere = new THREE.Mesh(geometry, material);
scene.add(skySphere);
obj.object3D = skySphere;
});
return obj;
}
interface AddLineParameters extends Transform, BasicMaterial {
lineWidth?: number;
}
interface AddArrowParameters extends AddLineParameters {
arrowStart?: boolean;
arrowEnd?: boolean;
}
interface AddAxes2DParameters extends Transform, BasicMaterial {
xRange?: [number, number, number?];
yRange?: [number, number, number?];
showTicks?: boolean;
showTickLabels?: boolean;
tickIntervalX?: number;
tickIntervalY?: number;
}
interface AddAxes3DParameters extends Transform, BasicMaterial {
xRange?: [number, number, number?];
yRange?: [number, number, number?];
zRange?: [number, number, number?];
}
interface AddGridParameters extends Transform, BasicMaterial {
gridSize?: number;
}
function toThreeVector3(
v?: { x?: number; y?: number; z?: number } | [number, number, number?]
) {
if (v === undefined) {
return new THREE.Vector3(0, 0, 0);
} else if (Array.isArray(v)) {
if (v.length == 2) {
return new THREE.Vector3(v[0], v[1]);
} else if (v.length == 3) {
return new THREE.Vector3(v[0], v[1], v[2]);
}
} else {
return new THREE.Vector3(
v.x === undefined ? 0 : v.x,
v.y === undefined ? 0 : v.y,
v.z === undefined ? 0 : v.z
);
}
}
interface Transform {
x?: number;
y?: number;
z?: number;
rx?: number;
ry?: number;
rz?: number;
sx?: number;
sy?: number;
sz?: number;
position?: [number, number] | [number, number, number];
scale?: number;
parent?: SceneObject;
anchor?:
| "left"
| "right"
| "top"
| "bottom"
| "topLeft"
| "topRight"
| "bottomLeft"
| "bottomRight";
}
interface AddObjectParameters extends Transform, BasicMaterial {
vertices?: any;
outline?: any;
outlineWidth?: any;
width?: any;
height?: any;
t?: number | string;
parent?: SceneObject;
lighting?: any;
ccw?: any;
font?: any;
fontSize?: any;
start?: any;
end?: any;
lineWidth?: any;
gridSize?: any;
centralAngle?: any;
letterSpacing?: any;
duration?: any;
type?: any;
}
interface BasicMaterial {
color?: string | number;
opacity?: number;
wireframe?: boolean;
lighting?: boolean;
}
function createMaterial(params: BasicMaterial = {}) {
if (params.wireframe) {
return new THREE.MeshBasicMaterial({
color: toThreeColor(params.color),
wireframe: true,
});
} else if (params.lighting) {
addDefaultLights();
return new THREE.MeshStandardMaterial({
color: toThreeColor(params.color),
roughness: 0.5,
transparent: params.opacity !== undefined && params.opacity < 1.0,
opacity: params.opacity || 1.0,
});
} else {
return new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
color: toThreeColor(params.color),
transparent: params.opacity !== undefined && params.opacity < 1.0,
opacity: params.opacity || 1.0,
});
}
}
function updateTransform(obj: THREE.Object3D, transform: Transform) {
// Position
if (transform.position !== undefined) {
obj.position.copy(toThreeVector3(transform.position));
} else {
for (const prop of ["x", "y", "z"]) {
const T = transform as any;
const V = obj.position as any;
if (T[prop] !== undefined) {
V[prop] = T[prop];
}
}
}
if (transform.anchor !== undefined) {
console.assert(obj.children.length > 0);
const aabb = computeAABB(obj);
const size = aabb.getSize(new THREE.Vector3());
if (transform.anchor === "left") {
for (const child of obj.children) {
child.translateX(size.x / 2);
}
} else if (transform.anchor === "right") {
for (const child of obj.children) {
child.translateX(-size.x / 2);
}
} else if (transform.anchor === "top") {
for (const child of obj.children) {
child.translateY(-size.y / 2);
}
} else if (transform.anchor === "bottom") {
for (const child of obj.children) {
child.translateY(size.y / 2);
}
} else if (transform.anchor === "topLeft") {
for (const child of obj.children) {
child.translateX(size.x / 2);
child.translateY(-size.y / 2);
}
} else if (transform.anchor === "topRight") {
for (const child of obj.children) {
child.translateX(-size.x / 2);
child.translateY(-size.y / 2);
}
} else if (transform.anchor === "bottomLeft") {
for (const child of obj.children) {
child.translateX(size.x / 2);
child.translateY(size.y / 2);
}
} else if (transform.anchor === "bottomRight") {
for (const child of obj.children) {
child.translateX(-size.x / 2);
child.translateY(size.y / 2);
}
}
}
// Scale
if (transform.scale !== undefined) {
obj.scale.multiplyScalar(transform.scale);
} else {
if (transform.sx !== undefined) {
obj.scale.x = transform.sx;
}
if (transform.sy !== undefined) {
obj.scale.y = transform.sy;
}
if (transform.sz !== undefined) {
obj.scale.z = transform.sz;
}
}
// Rotation
if (transform.rx !== undefined) {
// XXX: when rx is greater than 10, use it as a degrees instead of radians.
obj.rotation.x =
Math.abs(transform.rx) > 10 ? transform.rx * DEG2RAD : transform.rx;
}
if (transform.ry !== undefined) {
obj.rotation.y =
Math.abs(transform.ry) > 10 ? transform.ry * DEG2RAD : transform.ry;
}
if (transform.rz !== undefined) {
obj.rotation.z =
Math.abs(transform.rz) > 10 ? transform.rz * DEG2RAD : transform.rz;
}
}
export function _setUILayer() {
currentLayer = "ui";
}
interface AddGroupParameters extends Transform {}
export function getQueryString(url: string = undefined) {
// get query string from url (optional) or window
var queryString = url ? url.split("?")[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj: any = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split("#")[0];
// split our query string into its component parts
var arr = queryString.split("&");
for (var i = 0; i < arr.length; i++) {
// separate the keys and the values
var a = arr[i].split("=");
// set parameter name and value (use 'true' if empty)
var paramName = a[0];
var paramValue = typeof a[1] === "undefined" ? true : a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
if (typeof paramValue === "string") {
// paramValue = paramValue.toLowerCase();
paramValue = decodeURIComponent(paramValue);
}
// if the paramName ends with square brackets, e.g. colors[] or colors[2]
if (paramName.match(/\[(\d+)?\]$/)) {
// create key if it doesn't exist
var key = paramName.replace(/\[(\d+)?\]/, "");
if (!obj[key]) obj[key] = [];
// if it's an indexed array e.g. colors[2]
if (paramName.match(/\[\d+\]$/)) {
// get the index value and add the entry at the appropriate position
var index = /\[(\d+)\]/.exec(paramName)[1];
obj[key][index] = paramValue;
} else {
// otherwise add the value to the end of the array
obj[key].push(paramValue);
}
} else {
// we're dealing with a string
if (!obj[paramName]) {
// if it doesn't exist, create property
obj[paramName] = paramValue;
} else if (obj[paramName] && typeof obj[paramName] === "string") {
// if property does exist and it's a string, convert it to an array
obj[paramName] = [obj[paramName]];
obj[paramName].push(paramValue);
} else {
// otherwise add the property
obj[paramName].push(paramValue);
}
}
}
}
return obj;
}
export function setSeed(val: any) {
rng = seedrandom(val);
}
export function random(min = 0, max = 1) {
return min + rng() * (max - min);
}
function getGridPosition({ rows = 1, cols = 1, width = 25, height = 14 } = {}) {
const gapX = width / cols;
const gapY = height / rows;
const startX = (width / cols - width) * 0.5;
const startY = (height / rows - height) * 0.5;
const results = [];
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
results.push(
new THREE.Vector3(j * gapX + startX, -(i * gapY + startY), 0)
);
}
}
return results;
}
export function enableMotionBlur({ samples = 16 } = {}) {
motionBlurSamples = samples;
}
export function setResolution(w: number, h: number) {
renderTargetWidth = w;
renderTargetHeight = h;
}
export function setBackgroundColor(color: number | string) {
commandQueue.push(() => {
scene.background = toThreeColor(color);
});
}
export function fadeOutAll(params: AnimationParameters = {}) {
const root = getRoot();
commandQueue.push(() => {
const tl = gsap.timeline();
for (const object3d of root.object3D.children) {
tl.add(
createFadeOutAnimation(object3d, { duration: params.duration }),
"<"
);
}
mainTimeline.add(tl, params.t);
});
}
export function hideAll(params: AnimationParameters = {}) {
const root = getRoot();
commandQueue.push(() => {
const tl = gsap.timeline();
for (const object3d of root.object3D.children) {
tl.set(object3d, { visible: false }, "<");
}
mainTimeline.add(tl, params.t);
});
}
export function pause(duration: number | string) {
commandQueue.push(() => {
mainTimeline.set(
{},
{},
typeof duration === "number" ? "+=" + duration.toString() : duration
);
});
}
export function enableBloom() {
bloomEnabled = true;
}
export function _setCamera(cam: THREE.Camera) {
camera = cam;
}
export function _enableFXAA() {
fxaaEnabled = true;
}
async function loadObj(url: string): Promise<THREE.Group> {
return new Promise((resolve, reject) => {
const loader = new OBJLoader();
loader.load(
url,
function (object) {
resolve(object);
},
function (xhr) {
console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
},
function (error) {
reject(error);
}
);
});
}
export function _animateTo(
targets: gsap.TweenTarget,
vars: gsap.TweenVars,
t?: gsap.Position
) {
commandQueue.push(() => {
mainTimeline.to(targets, vars, t);
});
}
const root = new GroupObject();
root.object3D = new THREE.Group();
scene.add(root.object3D);
const uiRoot = new GroupObject();
uiRoot.object3D = new THREE.Group();
uiScene.add(uiRoot.object3D);
function getRoot(): GroupObject {
if (currentLayer === "ui") {
return uiRoot;
} else {
return root;
}
}
export function addCircle(params: AddCircleParameters = {}): SceneObject {
return getRoot().addCircle(params);
}
export function addCircleOutline(
params: AddCircleOutlineParameters = {}
): SceneObject {
return getRoot().addCircleOutline(params);
}
export function addCone(params: AddObjectParameters = {}): SceneObject {
return getRoot().addCone(params);
}
export function addCube(params: AddObjectParameters = {}): SceneObject {
return getRoot().addCube(params);
}
export function addCylinder(params: AddObjectParameters = {}): SceneObject {
return getRoot().addCylinder(params);
}
export function addGrid(params: AddGridParameters = {}): SceneObject {
return getRoot().addGrid(params);
}
export function addGroup(params: AddGroupParameters = {}): GroupObject {
return getRoot().addGroup(params);
}
export function addImage(
file: string,
params: AddTextParameters = {}
): SceneObject {
return getRoot().addImage(file, params);
}
export function addLine(
p1: [number, number, number?],
p2: [number, number, number?],
params: AddLineParameters = {}
): SceneObject {
return getRoot().addLine(p1, p2, params);
}
export function addPolyline(
points: [number, number, number][],
params: AddObjectParameters = {}
): SceneObject {
return getRoot().addPolyline(points, params);
}
export function addPyramid(params: AddObjectParameters = {}): SceneObject {
return getRoot().addPyramid(params);
}
export function addRect(params: AddRectParameters = {}): SceneObject {
return getRoot().addRect(params);
}
export function addRectOutline(params: AddOutlineParameters = {}): SceneObject {
return getRoot().addRectOutline(params);
}
export function addSphere(params: AddObjectParameters = {}): SceneObject {
return getRoot().addSphere(params);
}
export function addText(
text: string,
params: AddTextParameters = {}
): TextObject {
return getRoot().addText(text, params);
}
export function addText3D(
text: string,
params: AddText3DParameters = {}
): TextObject {
return getRoot().addText3D(text, params);
}
export function addTex(tex: string, params: AddTextParameters = {}): TexObject {
return getRoot().addTex(tex, params);
}
export function addTorus(params: AddObjectParameters = {}): SceneObject {
return getRoot().addTorus(params);
}
export function addTriangle(params: AddPolygonParameters = {}): SceneObject {
return getRoot().addTriangle(params);
}
export function addPolygon(
vertices: [number, number][],
params: AddPolygonParameters = {}
): SceneObject {
return getRoot().addPolygon(vertices, params);
}
export function addTriangleOutline(
params: AddOutlineParameters = {}
): SceneObject {
return getRoot().addTriangleOutline(params);
}
export function _addMesh(
mesh: THREE.Mesh,
params: AddObjectParameters = {}
): SceneObject {
return getRoot()._addMesh(mesh, params);
}
export function add3DModel(
url: string,
params: AddObjectParameters = {}
): SceneObject {
return getRoot().add3DModel(url, params);
}
export function addArrow(
p1: [number, number, number?],
p2: [number, number, number?],
params: AddArrowParameters = {}
): SceneObject {
return getRoot().addArrow(p1, p2, params);
}
export function addDoubleArrow(
p1: [number, number, number?],
p2: [number, number, number?],
params: AddLineParameters = {}
): SceneObject {
return getRoot().addDoubleArrow(p1, p2, params);
}
export function addAxes2D(params: AddAxes2DParameters = {}): SceneObject {
return getRoot().addAxes2D(params);
}
export function addAxes3D(params: AddAxes3DParameters = {}): SceneObject {
return getRoot().addAxes3D(params);
}
export function addArc(
startAngle: number,
endAngle: number,
radius = 1,
params: AddLineParameters = {}
): SceneObject {
return getRoot().addArc(startAngle, endAngle, radius, params);
}
export function moveTo(params: MoveObjectParameters = {}) {
return getRoot().moveTo(params);
}
export function usePerspectiveCamera() {
camera = createPerspectiveCamera();
}
export function useOrthographicCamera() {
camera = createOrthographicCamera();
}
export function addFog() {
commandQueue.push(() => {
scene.fog = new THREE.FogExp2(0x0, 0.03);
});
}
document.body.onload = function () {
run();
};
////////////////////////////////////////////////////////////////////////////////
// Raycast z plane at mouse click, then copy the intersection to clipboard.
////////////////////////////////////////////////////////////////////////////////
const raycaster = new THREE.Raycaster();
const planeZ = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
function onMouseMove(event: MouseEvent) {
if (renderer === undefined) return;
let bounds = renderer.domElement.getBoundingClientRect();
const mouse = new THREE.Vector2(
((event.clientX - bounds.left) / (bounds.right - bounds.left)) * 2 - 1,
-((event.clientY - bounds.top) / (bounds.bottom - bounds.top)) * 2 + 1
);
raycaster.setFromCamera(mouse, camera);
const target = new THREE.Vector3();
raycaster.ray.intersectPlane(planeZ, target);
// Copy to clipboard
navigator.clipboard.writeText(
`[${target.x.toFixed(3)}, ${target.y.toFixed(3)}, ${target.z.toFixed(3)}]`
);
}
window.addEventListener("click", onMouseMove, false); | the_stack |
import '../../../test/common-test-setup-karma';
import './gr-account-list';
import {
AccountInfoInput,
GrAccountList,
RawAccountInput,
} from './gr-account-list';
import {
AccountId,
AccountInfo,
EmailAddress,
GroupId,
GroupInfo,
SuggestedReviewerAccountInfo,
Suggestion,
} from '../../../types/common';
import {queryAll} from '../../../test/test-utils';
import {ReviewerSuggestionsProvider} from '../../../scripts/gr-reviewer-suggestions-provider/gr-reviewer-suggestions-provider';
import * as MockInteractions from '@polymer/iron-test-helpers/mock-interactions';
const basicFixture = fixtureFromElement('gr-account-list');
class MockSuggestionsProvider implements ReviewerSuggestionsProvider {
init() {}
getSuggestions(_: string): Promise<Suggestion[]> {
return Promise.resolve([]);
}
makeSuggestionItem(_: Suggestion) {
return {
name: 'test',
value: {
account: {
_account_id: 1 as AccountId,
} as AccountInfo,
count: 1,
} as SuggestedReviewerAccountInfo,
};
}
}
suite('gr-account-list tests', () => {
let _nextAccountId = 0;
const makeAccount: () => AccountInfo = function () {
const accountId = ++_nextAccountId;
return {
_account_id: accountId as AccountId,
};
};
const makeGroup: () => GroupInfo = function () {
const groupId = `group${++_nextAccountId}`;
return {
id: groupId as GroupId,
_group: true,
};
};
let existingAccount1: AccountInfo;
let existingAccount2: AccountInfo;
let element: GrAccountList;
let suggestionsProvider: MockSuggestionsProvider;
function getChips() {
return queryAll(element, 'gr-account-chip');
}
function handleAdd(value: RawAccountInput) {
element._handleAdd(
new CustomEvent<{value: RawAccountInput}>('add', {detail: {value}})
);
}
setup(() => {
existingAccount1 = makeAccount();
existingAccount2 = makeAccount();
element = basicFixture.instantiate();
element.accounts = [existingAccount1, existingAccount2];
suggestionsProvider = new MockSuggestionsProvider();
element.suggestionsProvider = suggestionsProvider;
});
test('account entry only appears when editable', () => {
element.readonly = false;
assert.isFalse(element.$.entry.hasAttribute('hidden'));
element.readonly = true;
assert.isTrue(element.$.entry.hasAttribute('hidden'));
});
test('addition and removal of account/group chips', () => {
flush();
sinon.stub(element, '_computeRemovable').returns(true);
// Existing accounts are listed.
let chips = getChips();
assert.equal(chips.length, 2);
assert.isFalse(chips[0].classList.contains('pendingAdd'));
assert.isFalse(chips[1].classList.contains('pendingAdd'));
// New accounts are added to end with pendingAdd class.
const newAccount = makeAccount();
handleAdd({account: newAccount});
flush();
chips = getChips();
assert.equal(chips.length, 3);
assert.isFalse(chips[0].classList.contains('pendingAdd'));
assert.isFalse(chips[1].classList.contains('pendingAdd'));
assert.isTrue(chips[2].classList.contains('pendingAdd'));
// Removed accounts are taken out of the list.
element.dispatchEvent(
new CustomEvent('remove', {
detail: {account: existingAccount1},
composed: true,
bubbles: true,
})
);
flush();
chips = getChips();
assert.equal(chips.length, 2);
assert.isFalse(chips[0].classList.contains('pendingAdd'));
assert.isTrue(chips[1].classList.contains('pendingAdd'));
// Invalid remove is ignored.
element.dispatchEvent(
new CustomEvent('remove', {
detail: {account: existingAccount1},
composed: true,
bubbles: true,
})
);
element.dispatchEvent(
new CustomEvent('remove', {
detail: {account: newAccount},
composed: true,
bubbles: true,
})
);
flush();
chips = getChips();
assert.equal(chips.length, 1);
assert.isFalse(chips[0].classList.contains('pendingAdd'));
// New groups are added to end with pendingAdd and group classes.
const newGroup = makeGroup();
handleAdd({group: newGroup, confirm: false});
flush();
chips = getChips();
assert.equal(chips.length, 2);
assert.isTrue(chips[1].classList.contains('group'));
assert.isTrue(chips[1].classList.contains('pendingAdd'));
// Removed groups are taken out of the list.
element.dispatchEvent(
new CustomEvent('remove', {
detail: {account: newGroup},
composed: true,
bubbles: true,
})
);
flush();
chips = getChips();
assert.equal(chips.length, 1);
assert.isFalse(chips[0].classList.contains('pendingAdd'));
});
test('_getSuggestions uses filter correctly', () => {
const originalSuggestions: Suggestion[] = [
{
email: 'abc@example.com' as EmailAddress,
text: 'abcd',
_account_id: 3 as AccountId,
} as AccountInfo,
{
email: 'qwe@example.com' as EmailAddress,
text: 'qwer',
_account_id: 1 as AccountId,
} as AccountInfo,
{
email: 'xyz@example.com' as EmailAddress,
text: 'aaaaa',
_account_id: 25 as AccountId,
} as AccountInfo,
];
sinon
.stub(suggestionsProvider, 'getSuggestions')
.returns(Promise.resolve(originalSuggestions));
sinon
.stub(suggestionsProvider, 'makeSuggestionItem')
.callsFake(suggestion => {
return {
name: ((suggestion as AccountInfo).email as string) ?? '',
value: {
account: suggestion as AccountInfo,
count: 1,
},
};
});
return element
._getSuggestions('')
.then(suggestions => {
// Default is no filtering.
assert.equal(suggestions.length, 3);
// Set up filter that only accepts suggestion1.
const accountId = (originalSuggestions[0] as AccountInfo)._account_id;
element.filter = function (suggestion) {
return (suggestion as AccountInfo)._account_id === accountId;
};
return element._getSuggestions('');
})
.then(suggestions => {
assert.deepEqual(suggestions, [
{
name: (originalSuggestions[0] as AccountInfo).email as string,
value: {
account: originalSuggestions[0] as AccountInfo,
count: 1,
},
},
]);
});
});
test('_computeChipClass', () => {
const account = makeAccount() as AccountInfoInput;
assert.equal(element._computeChipClass(account), '');
account._pendingAdd = true;
assert.equal(element._computeChipClass(account), 'pendingAdd');
account._group = true;
assert.equal(element._computeChipClass(account), 'group pendingAdd');
account._pendingAdd = false;
assert.equal(element._computeChipClass(account), 'group');
});
test('_computeRemovable', () => {
const newAccount = makeAccount() as AccountInfoInput;
newAccount._pendingAdd = true;
element.readonly = false;
element.removableValues = [];
assert.isFalse(element._computeRemovable(existingAccount1, false));
assert.isTrue(element._computeRemovable(newAccount, false));
element.removableValues = [existingAccount1];
assert.isTrue(element._computeRemovable(existingAccount1, false));
assert.isTrue(element._computeRemovable(newAccount, false));
assert.isFalse(element._computeRemovable(existingAccount2, false));
element.readonly = true;
assert.isFalse(element._computeRemovable(existingAccount1, true));
assert.isFalse(element._computeRemovable(newAccount, true));
});
test('submitEntryText', () => {
element.allowAnyInput = true;
flush();
const getTextStub = sinon.stub(element.$.entry, 'getText');
getTextStub.onFirstCall().returns('');
getTextStub.onSecondCall().returns('test');
getTextStub.onThirdCall().returns('test@test');
// When entry is empty, return true.
const clearStub = sinon.stub(element.$.entry, 'clear');
assert.isTrue(element.submitEntryText());
assert.isFalse(clearStub.called);
// When entry is invalid, return false.
assert.isFalse(element.submitEntryText());
assert.isFalse(clearStub.called);
// When entry is valid, return true and clear text.
assert.isTrue(element.submitEntryText());
assert.isTrue(clearStub.called);
assert.equal(
element.additions()[0].account?.email,
'test@test' as EmailAddress
);
});
test('additions returns sanitized new accounts and groups', () => {
assert.equal(element.additions().length, 0);
const newAccount = makeAccount();
handleAdd({account: newAccount});
const newGroup = makeGroup();
handleAdd({group: newGroup, confirm: false});
assert.deepEqual(element.additions(), [
{
account: {
_account_id: newAccount._account_id,
_pendingAdd: true,
},
},
{
group: {
id: newGroup.id,
_group: true,
_pendingAdd: true,
},
},
]);
});
test('large group confirmations', () => {
assert.isNull(element.pendingConfirmation);
assert.deepEqual(element.additions(), []);
const group = makeGroup();
const reviewer = {
group,
count: 10,
confirm: true,
};
handleAdd(reviewer);
assert.deepEqual(element.pendingConfirmation, reviewer);
assert.deepEqual(element.additions(), []);
element.confirmGroup(group);
assert.isNull(element.pendingConfirmation);
assert.deepEqual(element.additions(), [
{
group: {
id: group.id,
_group: true,
_pendingAdd: true,
confirmed: true,
},
},
]);
});
test('removeAccount fails if account is not removable', () => {
element.readonly = true;
const acct = makeAccount();
element.accounts = [acct];
element.removeAccount(acct);
assert.equal(element.accounts.length, 1);
});
test('max-count', () => {
element.maxCount = 1;
const acct = makeAccount();
handleAdd({account: acct});
flush();
assert.isTrue(element.$.entry.hasAttribute('hidden'));
});
test('enter text calls suggestions provider', async () => {
const suggestions: Suggestion[] = [
{
email: 'abc@example.com' as EmailAddress,
text: 'abcd',
} as AccountInfo,
{
email: 'qwe@example.com' as EmailAddress,
text: 'qwer',
} as AccountInfo,
];
const getSuggestionsStub = sinon
.stub(suggestionsProvider, 'getSuggestions')
.returns(Promise.resolve(suggestions));
const makeSuggestionItemSpy = sinon.spy(
suggestionsProvider,
'makeSuggestionItem'
);
const input = element.$.entry.$.input;
input.text = 'newTest';
MockInteractions.focus(input.$.input);
input.noDebounce = true;
await flush();
assert.isTrue(getSuggestionsStub.calledOnce);
assert.equal(getSuggestionsStub.lastCall.args[0], 'newTest');
assert.equal(makeSuggestionItemSpy.getCalls().length, 2);
});
suite('allowAnyInput', () => {
setup(() => {
element.allowAnyInput = true;
});
test('adds emails', () => {
const accountLen = element.accounts.length;
handleAdd('test@test');
assert.equal(element.accounts.length, accountLen + 1);
assert.equal(
(element.accounts[accountLen] as AccountInfoInput).email,
'test@test' as EmailAddress
);
});
test('toasts on invalid email', () => {
const toastHandler = sinon.stub();
element.addEventListener('show-alert', toastHandler);
handleAdd('test');
assert.isTrue(toastHandler.called);
});
});
suite('keyboard interactions', () => {
test('backspace at text input start removes last account', async () => {
const input = element.$.entry.$.input;
sinon.stub(input, '_updateSuggestions');
sinon.stub(element, '_computeRemovable').returns(true);
await flush();
// Next line is a workaround for Firefox not moving cursor
// on input field update
assert.equal(element._getNativeInput(input.$.input).selectionStart, 0);
input.text = 'test';
MockInteractions.focus(input.$.input);
flush();
assert.equal(element.accounts.length, 2);
MockInteractions.pressAndReleaseKeyOn(
element._getNativeInput(input.$.input),
8
); // Backspace
assert.equal(element.accounts.length, 2);
input.text = '';
MockInteractions.pressAndReleaseKeyOn(
element._getNativeInput(input.$.input),
8
); // Backspace
flush();
assert.equal(element.accounts.length, 1);
});
test('arrow key navigation', async () => {
const input = element.$.entry.$.input;
input.text = '';
element.accounts = [makeAccount(), makeAccount()];
flush();
MockInteractions.focus(input.$.input);
await flush();
const chips = element.accountChips;
const chipsOneSpy = sinon.spy(chips[1], 'focus');
MockInteractions.pressAndReleaseKeyOn(input.$.input, 37); // Left
assert.isTrue(chipsOneSpy.called);
const chipsZeroSpy = sinon.spy(chips[0], 'focus');
MockInteractions.pressAndReleaseKeyOn(chips[1], 37); // Left
assert.isTrue(chipsZeroSpy.called);
MockInteractions.pressAndReleaseKeyOn(chips[0], 37); // Left
assert.isTrue(chipsZeroSpy.calledOnce);
MockInteractions.pressAndReleaseKeyOn(chips[0], 39); // Right
assert.isTrue(chipsOneSpy.calledTwice);
});
test('delete', () => {
element.accounts = [makeAccount(), makeAccount()];
flush();
const focusSpy = sinon.spy(element.accountChips[1], 'focus');
const removeSpy = sinon.spy(element, 'removeAccount');
MockInteractions.pressAndReleaseKeyOn(element.accountChips[0], 8); // Backspace
assert.isTrue(focusSpy.called);
assert.isTrue(removeSpy.calledOnce);
MockInteractions.pressAndReleaseKeyOn(element.accountChips[1], 46); // Delete
assert.isTrue(removeSpy.calledTwice);
});
});
}); | the_stack |
import { fromBase64, toBase64 } from "@cosmjs/encoding";
import {
coins,
DirectSecp256k1HdWallet,
encodePubkey,
makeAuthInfoBytes,
makeSignDoc,
Registry,
TxBodyEncodeObject,
} from "@cosmjs/proto-signing";
import { assert, sleep } from "@cosmjs/utils";
import { TxRaw } from "cosmjs-types/cosmos/tx/v1beta1/tx";
import { ReadonlyDate } from "readonly-date";
import {
assertIsBroadcastTxSuccess,
PrivateStargateClient,
StargateClient,
TimeoutError,
} from "./stargateclient";
import {
faucet,
makeRandomAddress,
nonExistentAddress,
pendingWithoutSimapp,
pendingWithoutSlowSimapp,
simapp,
slowSimapp,
tendermintIdMatcher,
unused,
validator,
} from "./testutils.spec";
describe("StargateClient", () => {
describe("connect", () => {
it("works", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
expect(client).toBeTruthy();
client.disconnect();
});
});
describe("getChainId", () => {
it("works", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
expect(await client.getChainId()).toEqual(simapp.chainId);
client.disconnect();
});
it("caches chain ID", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const openedClient = client as unknown as PrivateStargateClient;
const getCodeSpy = spyOn(openedClient.tmClient!, "status").and.callThrough();
expect(await client.getChainId()).toEqual(simapp.chainId); // from network
expect(await client.getChainId()).toEqual(simapp.chainId); // from cache
expect(getCodeSpy).toHaveBeenCalledTimes(1);
client.disconnect();
});
});
describe("getHeight", () => {
it("works", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const height1 = await client.getHeight();
expect(height1).toBeGreaterThan(0);
await sleep(simapp.blockTime * 1.4); // tolerate chain being 40% slower than expected
const height2 = await client.getHeight();
expect(height2).toBeGreaterThanOrEqual(height1 + 1);
expect(height2).toBeLessThanOrEqual(height1 + 2);
client.disconnect();
});
});
describe("getAccount", () => {
it("works for unused account", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const account = await client.getAccount(unused.address);
assert(account);
expect(account).toEqual({
address: unused.address,
pubkey: null,
accountNumber: unused.accountNumber,
sequence: unused.sequence,
});
client.disconnect();
});
it("works for account with pubkey and non-zero sequence", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const account = await client.getAccount(validator.delegatorAddress);
assert(account);
expect(account).toEqual({
address: validator.delegatorAddress,
pubkey: validator.pubkey,
accountNumber: validator.accountNumber,
sequence: validator.sequence,
});
client.disconnect();
});
it("returns null for non-existent address", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const account = await client.getAccount(nonExistentAddress);
expect(account).toBeNull();
client.disconnect();
});
});
describe("getSequence", () => {
it("works for unused account", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const account = await client.getSequence(unused.address);
assert(account);
expect(account).toEqual({
accountNumber: unused.accountNumber,
sequence: unused.sequence,
});
client.disconnect();
});
it("rejects for non-existent address", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
await expectAsync(client.getSequence(nonExistentAddress)).toBeRejectedWithError(
/account does not exist on chain/i,
);
client.disconnect();
});
});
describe("getBlock", () => {
it("works for latest block", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const response = await client.getBlock();
expect(response).toEqual(
jasmine.objectContaining({
id: jasmine.stringMatching(tendermintIdMatcher),
header: jasmine.objectContaining({
chainId: await client.getChainId(),
}),
txs: jasmine.arrayContaining([]),
}),
);
expect(response.header.height).toBeGreaterThanOrEqual(1);
expect(new ReadonlyDate(response.header.time).getTime()).toBeLessThan(ReadonlyDate.now());
expect(new ReadonlyDate(response.header.time).getTime()).toBeGreaterThanOrEqual(
ReadonlyDate.now() - 5_000,
);
client.disconnect();
});
it("works for block by height", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const height = (await client.getBlock()).header.height;
const response = await client.getBlock(height - 1);
expect(response).toEqual(
jasmine.objectContaining({
id: jasmine.stringMatching(tendermintIdMatcher),
header: jasmine.objectContaining({
height: height - 1,
chainId: await client.getChainId(),
}),
txs: jasmine.arrayContaining([]),
}),
);
expect(new ReadonlyDate(response.header.time).getTime()).toBeLessThan(ReadonlyDate.now());
expect(new ReadonlyDate(response.header.time).getTime()).toBeGreaterThanOrEqual(
ReadonlyDate.now() - 5_000,
);
client.disconnect();
});
});
describe("getBalance", () => {
it("works for different existing balances", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const response1 = await client.getBalance(unused.address, simapp.denomFee);
expect(response1).toEqual({
amount: unused.balanceFee,
denom: simapp.denomFee,
});
const response2 = await client.getBalance(unused.address, simapp.denomStaking);
expect(response2).toEqual({
amount: unused.balanceStaking,
denom: simapp.denomStaking,
});
client.disconnect();
});
it("returns 0 for non-existent balance", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const response = await client.getBalance(unused.address, "gintonic");
expect(response).toEqual({
denom: "gintonic",
amount: "0",
});
client.disconnect();
});
it("returns 0 for non-existent address", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const response = await client.getBalance(nonExistentAddress, simapp.denomFee);
expect(response).toEqual({
denom: simapp.denomFee,
amount: "0",
});
client.disconnect();
});
});
describe("getAllBalances", () => {
it("returns all balances for unused account", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const balances = await client.getAllBalances(unused.address);
expect(balances).toEqual([
{
amount: unused.balanceFee,
denom: simapp.denomFee,
},
{
amount: unused.balanceStaking,
denom: simapp.denomStaking,
},
]);
client.disconnect();
});
it("returns an empty list for non-existent account", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const balances = await client.getAllBalances(nonExistentAddress);
expect(balances).toEqual([]);
client.disconnect();
});
});
describe("broadcastTx", () => {
it("broadcasts a transaction", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(faucet.mnemonic);
const [{ address, pubkey: pubkeyBytes }] = await wallet.getAccounts();
const pubkey = encodePubkey({
type: "tendermint/PubKeySecp256k1",
value: toBase64(pubkeyBytes),
});
const registry = new Registry();
const txBodyFields: TxBodyEncodeObject = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: {
messages: [
{
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: {
fromAddress: address,
toAddress: makeRandomAddress(),
amount: [
{
denom: "ucosm",
amount: "1234567",
},
],
},
},
],
},
};
const txBodyBytes = registry.encode(txBodyFields);
const { accountNumber, sequence } = (await client.getSequence(address))!;
const feeAmount = coins(2000, "ucosm");
const gasLimit = 200000;
const authInfoBytes = makeAuthInfoBytes([{ pubkey, sequence }], feeAmount, gasLimit);
const chainId = await client.getChainId();
const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber);
const { signature } = await wallet.signDirect(address, signDoc);
const txRaw = TxRaw.fromPartial({
bodyBytes: txBodyBytes,
authInfoBytes: authInfoBytes,
signatures: [fromBase64(signature.signature)],
});
const txRawBytes = Uint8Array.from(TxRaw.encode(txRaw).finish());
const txResult = await client.broadcastTx(txRawBytes);
assertIsBroadcastTxSuccess(txResult);
const { gasUsed, rawLog, transactionHash } = txResult;
expect(gasUsed).toBeGreaterThan(0);
expect(rawLog).toMatch(/{"key":"amount","value":"1234567ucosm"}/);
expect(transactionHash).toMatch(/^[0-9A-F]{64}$/);
client.disconnect();
});
it("errors immediately for a CheckTx failure", async () => {
pendingWithoutSimapp();
const client = await StargateClient.connect(simapp.tendermintUrl);
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(faucet.mnemonic);
const [{ address, pubkey: pubkeyBytes }] = await wallet.getAccounts();
const pubkey = encodePubkey({
type: "tendermint/PubKeySecp256k1",
value: toBase64(pubkeyBytes),
});
const registry = new Registry();
const invalidRecipientAddress = "tgrade1z363ulwcrxged4z5jswyt5dn5v3lzsemwz9ewj"; // wrong bech32 prefix
const txBodyFields: TxBodyEncodeObject = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: {
messages: [
{
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: {
fromAddress: address,
toAddress: invalidRecipientAddress,
amount: [
{
denom: "ucosm",
amount: "1234567",
},
],
},
},
],
},
};
const txBodyBytes = registry.encode(txBodyFields);
const { accountNumber, sequence } = (await client.getSequence(address))!;
const feeAmount = coins(2000, "ucosm");
const gasLimit = 200000;
const authInfoBytes = makeAuthInfoBytes([{ pubkey, sequence }], feeAmount, gasLimit, sequence);
const chainId = await client.getChainId();
const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber);
const { signature } = await wallet.signDirect(address, signDoc);
const txRaw = TxRaw.fromPartial({
bodyBytes: txBodyBytes,
authInfoBytes: authInfoBytes,
signatures: [fromBase64(signature.signature)],
});
const txRawBytes = Uint8Array.from(TxRaw.encode(txRaw).finish());
await expectAsync(client.broadcastTx(txRawBytes)).toBeRejectedWithError(/invalid recipient address/i);
client.disconnect();
});
it("respects user timeouts rather than RPC timeouts", async () => {
pendingWithoutSlowSimapp();
const client = await StargateClient.connect(slowSimapp.tendermintUrl);
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(faucet.mnemonic);
const [{ address, pubkey: pubkeyBytes }] = await wallet.getAccounts();
const pubkey = encodePubkey({
type: "tendermint/PubKeySecp256k1",
value: toBase64(pubkeyBytes),
});
const registry = new Registry();
const txBodyFields: TxBodyEncodeObject = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: {
messages: [
{
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: {
fromAddress: address,
toAddress: makeRandomAddress(),
amount: [
{
denom: "ucosm",
amount: "1234567",
},
],
},
},
],
},
};
const txBodyBytes = registry.encode(txBodyFields);
const chainId = await client.getChainId();
const feeAmount = coins(2000, "ucosm");
const gasLimit = 200000;
const { accountNumber: accountNumber1, sequence: sequence1 } = (await client.getSequence(address))!;
const authInfoBytes1 = makeAuthInfoBytes([{ pubkey, sequence: sequence1 }], feeAmount, gasLimit);
const signDoc1 = makeSignDoc(txBodyBytes, authInfoBytes1, chainId, accountNumber1);
const { signature: signature1 } = await wallet.signDirect(address, signDoc1);
const txRaw1 = TxRaw.fromPartial({
bodyBytes: txBodyBytes,
authInfoBytes: authInfoBytes1,
signatures: [fromBase64(signature1.signature)],
});
const txRawBytes1 = Uint8Array.from(TxRaw.encode(txRaw1).finish());
const largeTimeoutMs = 30_000;
const txResult = await client.broadcastTx(txRawBytes1, largeTimeoutMs);
assertIsBroadcastTxSuccess(txResult);
const { accountNumber: accountNumber2, sequence: sequence2 } = (await client.getSequence(address))!;
const authInfoBytes2 = makeAuthInfoBytes([{ pubkey, sequence: sequence2 }], feeAmount, gasLimit);
const signDoc2 = makeSignDoc(txBodyBytes, authInfoBytes2, chainId, accountNumber2);
const { signature: signature2 } = await wallet.signDirect(address, signDoc2);
const txRaw2 = TxRaw.fromPartial({
bodyBytes: txBodyBytes,
authInfoBytes: authInfoBytes2,
signatures: [fromBase64(signature2.signature)],
});
const txRawBytes2 = Uint8Array.from(TxRaw.encode(txRaw2).finish());
const smallTimeoutMs = 1_000;
await expectAsync(client.broadcastTx(txRawBytes2, smallTimeoutMs)).toBeRejectedWithError(
TimeoutError,
/transaction with id .+ was submitted but was not yet found on the chain/i,
);
client.disconnect();
}, 30_000);
});
}); | the_stack |
import { _, DocumentManager, FileUtils, Mustache } from "./brackets-modules";
import * as md5 from "blueimp-md5";
import * as moment from "moment";
import * as Strings from "strings";
import * as ErrorHandler from "./ErrorHandler";
import * as Events from "./Events";
import EventEmitter from "./EventEmitter";
import * as Git from "./git/GitCli";
import * as Git2 from "./git/Git";
import * as HistoryViewer from "./HistoryViewer";
import * as Preferences from "./Preferences";
const generateMd5 = _.memoize((str) => (md5 as any)(str));
const gitPanelHistoryTemplate = require("text!templates/git-panel-history.html");
const gitPanelHistoryCommitsTemplate = require("text!templates/git-panel-history-commits.html");
let $gitPanel = $(null);
let $tableContainer = $(null);
let $historyList = $(null);
let commitCache = [];
const avatarType = Preferences.get("avatarType");
let lastDocumentSeen = null;
function initVariables() {
$gitPanel = $("#git-panel");
$tableContainer = $gitPanel.find(".table-container");
attachHandlers();
}
function attachHandlers() {
$tableContainer
.off(".history")
.on("scroll.history", () => loadMoreHistory())
.on("click.history", ".history-commit", function () {
const hash = $(this).attr("x-hash");
const commit = _.find(commitCache, (c) => c.hash === hash);
HistoryViewer.show(commit, getCurrentDocument(), {
isInitial: $(this).attr("x-initial-commit") === "true"
});
});
}
const generateCssAvatar = _.memoize((author, email) => {
// Original source: http://indiegamr.com/generate-repeatable-random-numbers-in-js/
const seededRandom = function (max = 1, min = 0, _seed) {
const seed = (_seed * 9301 + 49297) % 233280;
const rnd = seed / 233280.0;
return min + rnd * (max - min);
};
// Use `seededRandom()` to generate a pseudo-random number [0-16] to pick a color from the list
const seedBase = parseInt(author.charCodeAt(3).toString(), email.length);
const seed = parseInt(email.charCodeAt(seedBase.toString().substring(1, 2)).toString(), 16);
const colors = [
"#ffb13b", "#dd5f7a", "#8dd43a", "#2f7e2f", "#4141b9", "#3dafea", "#7e3e3e", "#f2f26b",
"#864ba3", "#ac8aef", "#f2f2ce", "#379d9d", "#ff6750", "#8691a2", "#d2fd8d", "#88eadf"
];
const texts = [
"#FEFEFE", "#FEFEFE", "#FEFEFE", "#FEFEFE", "#FEFEFE", "#FEFEFE", "#FEFEFE", "#333333",
"#FEFEFE", "#FEFEFE", "#333333", "#FEFEFE", "#FEFEFE", "#FEFEFE", "#333333", "#333333"
];
const picked = Math.floor(seededRandom(0, 16, seed));
return "background-color: " + colors[picked] + "; color: " + texts[picked];
}, (author, email) => {
// calculate hash for memoize - both are strings so we don't need to convert
return author + email;
});
// Render history list the first time
function renderHistory(file) {
// clear cache
commitCache = [];
return Git.getCurrentBranchName().then((branchName) => {
// Get the history commits of the current branch
const p = file ? Git2.getFileHistory(file.relative, branchName) : Git.getHistory(branchName);
return p.then((_commits) => {
// calculate some missing stuff like avatars
const commits = addAdditionalCommitInfo(_commits);
commitCache = commitCache.concat(commits);
const templateData = {
commits,
usePicture: avatarType === "PICTURE",
useIdenticon: avatarType === "IDENTICON",
useBwAvatar: avatarType === "AVATAR_BW",
useColoredAvatar: avatarType === "AVATAR_COLOR",
Strings
};
$tableContainer.append(Mustache.render(gitPanelHistoryTemplate, templateData, {
commits: gitPanelHistoryCommitsTemplate
}));
$historyList = $tableContainer.find("#git-history-list")
.data("file", file ? file.absolute : null)
.data("file-relative", file ? file.relative : null);
$historyList
.find("tr.history-commit:last-child")
.attr("x-initial-commit", "true");
});
}).catch((err) => ErrorHandler.showError(err, "Failed to get history"));
}
// Load more rows in the history list on scroll
function loadMoreHistory() {
if ($historyList.is(":visible")) {
if (($tableContainer.prop("scrollHeight") - $tableContainer.scrollTop()) === $tableContainer.height()) {
if ($historyList.attr("x-finished") === "true") {
return null;
}
return Git.getCurrentBranchName().then((branchName) => {
let p;
const file = $historyList.data("file-relative");
const skipCount = $tableContainer.find("tr.history-commit").length;
if (file) {
p = Git2.getFileHistory(file, branchName, skipCount);
} else {
p = Git.getHistory(branchName, skipCount);
}
return p.then((_commits) => {
if (_commits.length === 0) {
$historyList.attr("x-finished", "true");
// marks initial commit as first
$historyList
.find("tr.history-commit:last-child")
.attr("x-initial-commit", "true");
return;
}
const commits = addAdditionalCommitInfo(_commits);
commitCache = commitCache.concat(commits);
const templateData = {
commits,
usePicture: avatarType === "PICTURE",
useIdenticon: avatarType === "IDENTICON",
useBwAvatar: avatarType === "AVATAR_BW",
useColoredAvatar: avatarType === "AVATAR_COLOR",
Strings
};
const commitsHtml = Mustache.render(gitPanelHistoryCommitsTemplate, templateData);
$historyList.children("tbody").append(commitsHtml);
})
.catch((err) => ErrorHandler.showError(err, "Failed to load more history rows"));
})
.catch((err) => ErrorHandler.showError(err, "Failed to get current branch name"));
}
}
return null;
}
function addAdditionalCommitInfo(commits) {
const mode = Preferences.get("dateMode");
let format = Strings.DATE_FORMAT;
const ownFormat = Preferences.get("dateFormat") || Strings.DATE_FORMAT;
if (mode === 2 && format.indexOf(" ")) {
// only date part
format = format.substring(0, format.indexOf(" "));
}
_.forEach(commits, (commit) => {
// Get color for AVATAR_BW and AVATAR_COLOR
if (avatarType === "AVATAR_COLOR" || avatarType === "AVATAR_BW") {
commit.cssAvatar = generateCssAvatar(commit.author, commit.email);
commit.avatarLetter = commit.author.substring(0, 1);
}
if (avatarType === "PICTURE" || avatarType === "IDENTICON") {
commit.emailHash = generateMd5(commit.email);
}
// FUTURE: convert date modes to sensible constant strings
if (mode === 4) {
// mode 4: Original Git date
commit.date = {
shown: commit.date
};
return;
}
const date = moment(commit.date);
commit.date = {
title: ""
};
switch (mode) {
// mode 0 (default): formatted with Strings.DATE_FORMAT
default:
case 0:
commit.date.shown = date.format(format);
break;
// mode 1: always relative
case 1:
commit.date.shown = date.fromNow();
commit.date.title = date.format(format);
break;
// mode 2: intelligent relative/formatted
case 2:
const relative = date.fromNow();
const formatted = date.format(format);
commit.date.shown = relative + " (" + formatted + ")";
commit.date.title = date.format(Strings.DATE_FORMAT);
break;
// mode 3: formatted with own format (as pref)
case 3:
commit.date.shown = date.format(ownFormat);
commit.date.title = date.format(format);
break;
/* mode 4 (Original Git date) is handled above */
}
commit.hasTag = (commit.tags) ? true : false;
});
return commits;
}
function getCurrentDocument() {
if (HistoryViewer.isVisible()) {
return lastDocumentSeen;
}
const doc = DocumentManager.getCurrentDocument();
if (doc) {
lastDocumentSeen = doc;
}
return doc || lastDocumentSeen;
}
function handleFileChange() {
const currentDocument = getCurrentDocument();
if ($historyList.is(":visible") && $historyList.data("file")) {
handleToggleHistory("FILE", currentDocument);
}
$gitPanel.find(".git-file-history").prop("disabled", !currentDocument);
}
// Show or hide the history list on click of .history button
// newHistoryMode can be "FILE" or "GLOBAL"
function handleToggleHistory(newHistoryMode: "FILE" | "GLOBAL", newDocument?) {
// this is here to check that $historyList is still attached to the DOM
$historyList = $tableContainer.find("#git-history-list");
let historyEnabled = $historyList.is(":visible");
const currentFile = $historyList.data("file") || null;
let currentHistoryMode;
if (historyEnabled) {
currentHistoryMode = currentFile ? "FILE" : "GLOBAL";
} else {
currentHistoryMode = "DISABLED";
}
const doc = newDocument ? newDocument : getCurrentDocument();
let file;
if (currentHistoryMode !== newHistoryMode) {
// we are switching the modes so enable
historyEnabled = true;
} else if (!newDocument) {
// we are not changing the mode and we are not switching to a new document
historyEnabled = !historyEnabled;
}
if (historyEnabled && newHistoryMode === "FILE") {
if (doc) {
file = {};
file.absolute = doc.file.fullPath;
file.relative = FileUtils.getRelativeFilename(Preferences.get("currentGitRoot"), file.absolute);
} else {
// we want a file history but no file was found
historyEnabled = false;
}
}
// Render #git-history-list if is not already generated or if the viewed file for file history has changed
const isEmpty = $historyList.find("tr").length === 0;
const fileChanged = currentFile !== (file ? file.absolute : null);
if (historyEnabled && (isEmpty || fileChanged)) {
if ($historyList.length > 0) {
$historyList.remove();
}
const $spinner = $("<div class='spinner spin large'></div>").appendTo($gitPanel);
renderHistory(file).finally(() => {
$spinner.remove();
});
}
// disable commit button when viewing history
// refresh status when history is closed and commit button will correct its disabled state if required
if (historyEnabled) {
$gitPanel.find(".git-commit, .check-all").prop("disabled", true);
} else {
Git.status();
}
// Toggle visibility of .git-edited-list and #git-history-list
$tableContainer.find(".git-edited-list").toggle(!historyEnabled);
$historyList.toggle(historyEnabled);
if (!historyEnabled) { HistoryViewer.hide(); }
// Toggle history button
const globalButtonActive = historyEnabled && newHistoryMode === "GLOBAL";
const fileButtonActive = historyEnabled && newHistoryMode === "FILE";
$gitPanel.find(".git-history-toggle").toggleClass("active", globalButtonActive)
.attr("title", globalButtonActive ? Strings.TOOLTIP_HIDE_HISTORY : Strings.TOOLTIP_SHOW_HISTORY);
$gitPanel.find(".git-file-history").toggleClass("active", fileButtonActive)
.attr("title", fileButtonActive ? Strings.TOOLTIP_HIDE_FILE_HISTORY : Strings.TOOLTIP_SHOW_FILE_HISTORY);
}
// Event listeners
EventEmitter.on(Events.GIT_ENABLED, () => {
initVariables();
});
EventEmitter.on(Events.GIT_DISABLED, () => {
lastDocumentSeen = null;
$historyList.remove();
$historyList = $();
});
EventEmitter.on(Events.HISTORY_SHOW, (mode) => {
handleToggleHistory(mode === "FILE" ? "FILE" : "GLOBAL");
});
EventEmitter.on(Events.BRACKETS_CURRENT_DOCUMENT_CHANGE, () => {
handleFileChange();
}); | the_stack |
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import cls from 'classnames';
import PropTypes from 'prop-types';
import { cssClasses, strings } from '@douyinfe/semi-foundation/typography/constants';
import Typography from './typography';
import Copyable from './copyable';
import { IconSize as Size } from '../icons/index';
import { isUndefined, omit, merge, isString } from 'lodash';
import Tooltip from '../tooltip/index';
import Popover from '../popover/index';
import getRenderText from './util';
import warning from '@douyinfe/semi-foundation/utils/warning';
import isEnterPress from '@douyinfe/semi-foundation/utils/isEnterPress';
import LocaleConsumer from '../locale/localeConsumer';
import { Locale } from '../locale/interface';
import { Ellipsis, EllipsisPos, ShowTooltip, TypographyBaseSize, TypographyBaseType } from './interface';
import { CopyableConfig, LinkType } from './title';
import { BaseProps } from '../_base/baseComponent';
import { isSemiIcon } from '../_utils';
export interface BaseTypographyProps extends BaseProps {
copyable?: CopyableConfig | boolean;
delete?: boolean;
disabled?: boolean;
icon?: React.ReactNode;
ellipsis?: Ellipsis | boolean;
mark?: boolean;
underline?: boolean;
link?: LinkType;
strong?: boolean;
type?: TypographyBaseType;
size?: TypographyBaseSize;
style?: React.CSSProperties;
className?: string;
code?: boolean;
children?: React.ReactNode;
component?: React.ElementType;
spacing?: string;
heading?: string;
}
interface BaseTypographyState {
editable: boolean;
copied: boolean;
isOverflowed: boolean;
ellipsisContent: string;
expanded: boolean;
isTruncated: boolean;
first: boolean;
prevChildren: React.ReactNode;
}
const prefixCls = cssClasses.PREFIX;
const ELLIPSIS_STR = '...';
const wrapperDecorations = (props: BaseTypographyProps, content: React.ReactNode) => {
const { mark, code, underline, strong, link, disabled } = props;
let wrapped = content;
const wrap = (isNeeded: boolean | LinkType, tag: string) => {
let wrapProps = {};
if (!isNeeded) {
return;
}
if (typeof isNeeded === 'object') {
wrapProps = { ...isNeeded };
}
wrapped = React.createElement(tag, wrapProps, wrapped);
};
wrap(mark, 'mark');
wrap(code, 'code');
wrap(underline && !link, 'u');
wrap(strong, 'strong');
wrap(props.delete, 'del');
wrap(link, disabled ? 'span' : 'a');
return wrapped;
};
export default class Base extends Component<BaseTypographyProps, BaseTypographyState> {
static propTypes = {
children: PropTypes.node,
copyable: PropTypes.oneOfType([
PropTypes.shape({
text: PropTypes.string,
onCopy: PropTypes.func,
successTip: PropTypes.node,
copyTip: PropTypes.node,
}),
PropTypes.bool,
]),
delete: PropTypes.bool,
disabled: PropTypes.bool,
// editable: PropTypes.bool,
ellipsis: PropTypes.oneOfType([
PropTypes.shape({
rows: PropTypes.number,
expandable: PropTypes.bool,
expandText: PropTypes.string,
onExpand: PropTypes.func,
suffix: PropTypes.string,
showTooltip: PropTypes.oneOfType([
PropTypes.shape({
type: PropTypes.string,
opts: PropTypes.object,
}),
PropTypes.bool,
]),
collapsible: PropTypes.bool,
collapseText: PropTypes.string,
pos: PropTypes.oneOf(['end', 'middle']),
}),
PropTypes.bool,
]),
mark: PropTypes.bool,
underline: PropTypes.bool,
link: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
spacing: PropTypes.oneOf(strings.SPACING),
strong: PropTypes.bool,
size: PropTypes.oneOf(strings.SIZE),
type: PropTypes.oneOf(strings.TYPE),
style: PropTypes.object,
className: PropTypes.string,
icon: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
heading: PropTypes.string,
component: PropTypes.string,
};
static defaultProps = {
children: null as React.ReactNode,
copyable: false,
delete: false,
disabled: false,
// editable: false,
ellipsis: false,
icon: '',
mark: false,
underline: false,
strong: false,
link: false,
type: 'primary',
spacing: 'normal',
size: 'normal',
style: {},
className: '',
};
wrapperRef: React.RefObject<any>;
expandRef: React.RefObject<any>;
copyRef: React.RefObject<any>;
rafId: ReturnType<typeof requestAnimationFrame>;
expandStr: string;
collapseStr: string;
constructor(props: BaseTypographyProps) {
super(props);
this.state = {
editable: false,
copied: false,
// ellipsis
// if text is overflow in container
isOverflowed: true,
ellipsisContent: null,
expanded: false,
// if text is truncated with js
isTruncated: false,
// record if has click expanded
first: true,
prevChildren: null,
};
this.wrapperRef = React.createRef();
this.expandRef = React.createRef();
this.copyRef = React.createRef();
}
componentDidMount() {
if (this.props.ellipsis) {
this.getEllipsisState();
window.addEventListener('resize', this.onResize);
}
}
static getDerivedStateFromProps(props: BaseTypographyProps, prevState: BaseTypographyState) {
const { prevChildren } = prevState;
const newState: Partial<BaseTypographyState> = {};
newState.prevChildren = props.children;
if (props.ellipsis && prevChildren !== props.children) {
// reset ellipsis state if children update
newState.isOverflowed = true;
newState.ellipsisContent = null;
newState.expanded = false;
newState.isTruncated = false;
newState.first = true;
}
return newState;
}
componentDidUpdate(prevProps: BaseTypographyProps) {
// Render was based on outdated refs and needs to be rerun
if (this.props.children !== prevProps.children) {
this.forceUpdate();
if (this.props.ellipsis) {
this.getEllipsisState();
}
}
}
componentWillUnmount() {
if (this.props.ellipsis) {
window.removeEventListener('resize', this.onResize);
}
if (this.rafId) {
window.cancelAnimationFrame(this.rafId);
}
}
onResize = () => {
if (this.rafId) {
window.cancelAnimationFrame(this.rafId);
}
this.rafId = window.requestAnimationFrame(this.getEllipsisState.bind(this));
};
// if need to use js overflowed:
// 1. text is expandable 2. expandText need to be shown 3. has extra operation 4. text need to ellipse from mid
canUseCSSEllipsis = () => {
const { copyable } = this.props;
const { expandable, expandText, pos, suffix } = this.getEllipsisOpt();
return !expandable && isUndefined(expandText) && !copyable && pos === 'end' && !suffix.length;
};
/**
* whether truncated
* rows < = 1 if there is overflow content, return true
* rows > 1 if there is overflow height, return true
* @param {Number} rows
* @returns {Boolean}
*/
shouldTruncated = (rows: number) => {
if (!rows || rows < 1) {
return false;
}
const updateOverflow =
rows <= 1 ?
this.wrapperRef.current.scrollWidth > this.wrapperRef.current.clientWidth :
this.wrapperRef.current.scrollHeight > this.wrapperRef.current.offsetHeight;
return updateOverflow;
};
showTooltip = () => {
const { isOverflowed, isTruncated, expanded } = this.state;
const { showTooltip, expandable, expandText } = this.getEllipsisOpt();
const overflowed = !expanded && (isOverflowed || isTruncated);
const noExpandText = !expandable && isUndefined(expandText);
const show = noExpandText && overflowed && showTooltip;
if (!show) {
return show;
}
const defaultOpts = {
type: 'tooltip',
opts: {},
};
if (typeof showTooltip === 'object') {
if (showTooltip.type && showTooltip.type.toLowerCase() === 'popover') {
return merge(
{
opts: {
style: { width: '240px' },
showArrow: true,
},
},
showTooltip
);
}
return { ...defaultOpts, ...showTooltip };
}
return defaultOpts;
};
getEllipsisState() {
const { rows, suffix, pos } = this.getEllipsisOpt();
const { children } = this.props;
// wait until element mounted
if (!this.wrapperRef || !this.wrapperRef.current) {
this.onResize();
return false;
}
const { ellipsisContent, isOverflowed, isTruncated, expanded } = this.state;
const updateOverflow = this.shouldTruncated(rows);
const canUseCSSEllipsis = this.canUseCSSEllipsis();
const needUpdate = updateOverflow !== isOverflowed;
if (!rows || rows < 0 || expanded) {
return undefined;
}
if (canUseCSSEllipsis) {
if (needUpdate) {
this.setState({ expanded: !updateOverflow });
}
return undefined;
}
const extraNode = [this.expandRef.current, this.copyRef && this.copyRef.current];
warning(
'children' in this.props && typeof children !== 'string',
"[Semi Typography] 'Only children with pure text could be used with ellipsis at this moment."
);
const content = getRenderText(
ReactDOM.findDOMNode(this.wrapperRef.current) as HTMLElement,
rows,
children as string,
extraNode,
ELLIPSIS_STR,
suffix,
pos
);
if (children === content) {
this.setState({ expanded: true });
} else if (ellipsisContent !== content || isOverflowed !== updateOverflow) {
this.setState({
ellipsisContent: content,
isOverflowed: updateOverflow,
isTruncated: children !== content,
});
}
return undefined;
}
/**
* Triggered when the fold button is clicked to save the latest expanded state
* @param {Event} e
*/
toggleOverflow = (e: React.MouseEvent<HTMLAnchorElement>) => {
const { onExpand, expandable, collapsible } = this.getEllipsisOpt();
const { expanded } = this.state;
onExpand && onExpand(!expanded, e);
if ((expandable && !expanded) || (collapsible && expanded)) {
this.setState({ expanded: !expanded, first: false });
}
};
getEllipsisOpt = (): Ellipsis => {
const { ellipsis } = this.props;
if (!ellipsis) {
return {};
}
const opt = {
rows: 1,
expandable: false,
pos: 'end' as EllipsisPos,
suffix: '',
showTooltip: false,
collapsible: false,
expandText: (ellipsis as Ellipsis).expandable ? this.expandStr : undefined,
collapseText: (ellipsis as Ellipsis).collapsible ? this.collapseStr : undefined,
...(typeof ellipsis === 'object' ? ellipsis : null),
};
return opt;
};
renderExpandable = () => {
const { expandText, expandable, collapseText, collapsible } = this.getEllipsisOpt();
const { expanded, first } = this.state;
const noExpandText = !expandable && isUndefined(expandText);
const noCollapseText = !collapsible && isUndefined(collapseText);
let text;
if (!expanded && !noExpandText) {
text = expandText;
} else if (expanded && !first && !noCollapseText) {
// if expanded is true but the text is initally mounted, we dont show collapseText
text = collapseText;
}
if (!noExpandText || !noCollapseText) {
return (
// TODO: replace `a` tag with `span` in next major version
// NOTE: may have effect on style
// eslint-disable-next-line jsx-a11y/anchor-is-valid
<a
role="button"
tabIndex={0}
className={`${prefixCls}-ellipsis-expand`}
key="expand"
ref={this.expandRef}
aria-label={text}
onClick={this.toggleOverflow}
onKeyPress={e => isEnterPress(e) && this.toggleOverflow(e as any)}
>
{text}
</a>
);
}
return null;
};
/**
* 获取文本的缩略class和style
*
* 截断类型:
* - CSS 截断,仅在 rows=1 且没有 expandable、pos、suffix 时生效
* - JS 截断,应对 CSS 无法阶段的场景
* 相关变量
* props:
* - ellipsis:
* - rows
* - expandable
* - pos
* - suffix
* state:
* - isOverflowed,文本是否处于overflow状态
* - expanded,文本是否处于折叠状态
* - isTruncated,文本是否被js截断
*
* Get the abbreviated class and style of the text
*
* Truncation type:
* -CSS truncation, which only takes effect when rows = 1 and there is no expandable, pos, suffix
* -JS truncation, dealing with scenarios where CSS cannot stage
* related variables
* props:
* -ellipsis:
* -rows
* -expandable
* -pos
* -suffix
* state:
* -isOverflowed, whether the text is in an overflow state
* -expanded, whether the text is in a collapsed state
* -isTruncated, whether the text is truncated by js
* @returns {Object}
*/
getEllipsisStyle = () => {
const { ellipsis } = this.props;
const { expandable } = this.getEllipsisOpt();
if (!ellipsis) {
return {
ellipsisCls: '',
ellipsisStyle: {},
// ellipsisAttr: {}
};
}
const { rows } = this.getEllipsisOpt();
const { isOverflowed, expanded, isTruncated } = this.state;
const useCSS = !expanded && this.canUseCSSEllipsis();
const ellipsisCls = cls({
[`${prefixCls}-ellipsis`]: true,
[`${prefixCls}-ellipsis-single-line`]: rows === 1,
[`${prefixCls}-ellipsis-multiple-line`]: rows > 1,
[`${prefixCls}-ellipsis-overflow-ellipsis`]: rows === 1 && useCSS,
});
const ellipsisStyle = useCSS && rows > 1 ? { WebkitLineClamp: rows } : {};
return {
ellipsisCls,
ellipsisStyle: isOverflowed ? ellipsisStyle : {},
};
};
renderEllipsisText = (opt: Ellipsis) => {
const { suffix } = opt;
const { children } = this.props;
const { isTruncated, expanded, isOverflowed, ellipsisContent } = this.state;
if (expanded || !isTruncated) {
return (
<>
{children}
{suffix && suffix.length ? suffix : null}
</>
);
}
return (
<span>
{ellipsisContent}
{/* {ELLIPSIS_STR} */}
{suffix}
</span>
);
};
renderOperations() {
return (
<>
{this.renderExpandable()}
{this.renderCopy()}
</>
);
}
renderCopy() {
const { copyable, children } = this.props;
if (!copyable) {
return null;
}
let copyContent: string;
let hasObject = false;
if (Array.isArray(children)) {
copyContent = '';
children.forEach(value => {
if (typeof value === 'object') {
hasObject = true;
}
copyContent += String(value);
});
} else if (typeof children !== 'object') {
copyContent = String(children);
} else {
hasObject = true;
copyContent = String(children);
}
warning(
hasObject,
'Children in Typography is a object, it will case a [object Object] mistake when copy to clipboard.'
);
const copyConfig = {
content: copyContent,
duration: 3,
...(typeof copyable === 'object' ? copyable : null),
};
return <Copyable {...copyConfig} forwardRef={this.copyRef} />;
}
renderIcon() {
const { icon, size } = this.props;
if (!icon) {
return null;
}
const iconSize: Size = size === 'small' ? 'small' : 'default';
return (
<span className={`${prefixCls}-icon`}>
{isSemiIcon(icon) ? React.cloneElement((icon as React.ReactElement), { size: iconSize }) : icon}
</span>
);
}
renderContent() {
const {
component,
children,
className,
type,
spacing,
disabled,
style,
ellipsis,
icon,
size,
link,
heading,
...rest
} = this.props;
const textProps = omit(rest, [
'strong',
'editable',
'mark',
'copyable',
'underline',
'code',
// 'link',
'delete',
]);
const iconNode = this.renderIcon();
const ellipsisOpt = this.getEllipsisOpt();
const { ellipsisCls, ellipsisStyle } = this.getEllipsisStyle();
let textNode = ellipsis ? this.renderEllipsisText(ellipsisOpt) : children;
const linkCls = cls({
[`${prefixCls}-link-text`]: link,
[`${prefixCls}-link-underline`]: this.props.underline && link,
});
textNode = wrapperDecorations(
this.props,
<>
{iconNode}
{this.props.link ? <span className={linkCls}>{textNode}</span> : textNode}
</>
);
const hTagReg = /^h[1-6]$/;
const wrapperCls = cls(className, ellipsisCls, {
// [`${prefixCls}-primary`]: !type || type === 'primary',
[`${prefixCls}-${type}`]: type && !link,
[`${prefixCls}-${size}`]: size,
[`${prefixCls}-link`]: link,
[`${prefixCls}-disabled`]: disabled,
[`${prefixCls}-${spacing}`]: spacing,
[`${prefixCls}-${heading}`]: isString(heading) && hTagReg.test(heading),
});
return (
<Typography
className={wrapperCls}
style={{ ...style, ...ellipsisStyle }}
component={component}
forwardRef={this.wrapperRef}
{...textProps}
>
{textNode}
{this.renderOperations()}
</Typography>
);
}
renderTipWrapper() {
const { children } = this.props;
const showTooltip = this.showTooltip();
const content = this.renderContent();
if (showTooltip) {
const { type, opts } = showTooltip as ShowTooltip;
if (type.toLowerCase() === 'popover') {
return (
<Popover content={children} position="top" {...opts}>
{content}
</Popover>
);
}
return (
<Tooltip content={children} position="top" {...opts}>
{content}
</Tooltip>
);
} else {
return content;
}
}
render() {
return (
<LocaleConsumer componentName="Typography">
{(locale: Locale['Typography']) => {
this.expandStr = locale.expand;
this.collapseStr = locale.collapse;
return this.renderTipWrapper();
}}
</LocaleConsumer>
);
}
} | the_stack |
import * as bluebird from "bluebird";
import * as i18next from "i18next";
import * as _ from "lodash";
import { Context as AWSLambdaContext } from "aws-lambda";
import { LambdaLogOptions } from "lambda-log";
import {
Ask,
IDirective,
IDirectiveClass,
Reprompt,
Say,
SayP,
Tell,
Text,
TextP,
} from "./directives";
import { errorHandler, UnknownRequestType } from "./errors";
import { isLambdaContext, timeout } from "./lambda";
import { IModel, Model } from "./Model";
import { IRenderer, IRendererConfig, Renderer } from "./renderers/Renderer";
import {
IStateHandler,
ITransition,
IUnhandledStateCb,
State,
StateMachine,
SystemTransition,
} from "./StateMachine";
import { IBag, IVoxaEvent, IVoxaIntentEvent } from "./VoxaEvent";
import { IVoxaReply } from "./VoxaReply";
const i18n: i18next.i18n = require("i18next");
export interface IVoxaAppConfig extends IRendererConfig {
Model: IModel;
RenderClass: IRenderer;
views: i18next.Resource;
variables?: any;
logOptions?: LambdaLogOptions;
onUnhandledState?: IUnhandledStateCb;
}
export type IEventHandler = (
event: IVoxaEvent,
response: IVoxaReply,
transition?: ITransition,
) => IVoxaReply | void;
export type IErrorHandler = (
event: IVoxaEvent,
error: Error,
ReplyClass: IVoxaReply,
) => IVoxaReply;
export class VoxaApp {
[key: string]: any;
/*
* This way we can simply override the method if we want different request types
*/
get requestTypes(): string[] {
// eslint-disable-line class-methods-use-this
return ["IntentRequest", "SessionEndedRequest"];
}
public eventHandlers: any = {};
public requestHandlers: any;
public config: IVoxaAppConfig;
public renderer: Renderer;
public i18nextPromise: PromiseLike<i18next.TFunction>;
// WARNING: the i18n variable should remain as a local instance of the VoxaApp.ts
// class, so that its internal configuration is initialized with every Voxa's request.
// This ensures its configuration is tied to the locale the request is coming with.
// For instance, if a skill has en-US and de-DE locales. There could be an issue
// with the global instance of i18n to return english values to the German locale.
public i18n: i18next.i18n;
public states: State[] = [];
public directiveHandlers: IDirectiveClass[] = [];
constructor(config: any) {
this.i18n = i18n.createInstance();
this.config = config;
this.requestHandlers = {
SessionEndedRequest: this.handleOnSessionEnded.bind(this),
};
_.forEach(this.requestTypes, (requestType) =>
this.registerRequestHandler(requestType),
);
this.registerEvents();
this.onError(errorHandler, true);
this.config = _.assign(
{
Model,
RenderClass: Renderer,
},
this.config,
);
this.validateConfig();
this.i18nextPromise = initializeI118n(this.i18n, this.config.views);
this.renderer = new this.config.RenderClass(this.config);
// this can be used to plug new information in the request
// default is to just initialize the model
this.onRequestStarted(this.transformRequest);
// run the state machine for intentRequests
this.onIntentRequest(this.runStateMachine, true);
this.onAfterStateChanged(this.renderDirectives);
this.onBeforeReplySent(this.saveSession, true);
this.directiveHandlers = [Say, SayP, Ask, Reprompt, Tell, Text, TextP];
}
public validateConfig() {
if (!this.config.Model.deserialize) {
throw new Error("Model should have a deserialize method");
}
if (
!this.config.Model.serialize &&
!(this.config.Model.prototype && this.config.Model.prototype.serialize)
) {
throw new Error("Model should have a serialize method");
}
}
public async handleOnSessionEnded(
event: IVoxaIntentEvent,
response: IVoxaReply,
): Promise<IVoxaReply> {
const sessionEndedHandlers = this.getOnSessionEndedHandlers(
event.platform.name,
);
const replies = await bluebird.mapSeries(
sessionEndedHandlers,
(fn: IEventHandler) => fn(event, response),
);
const lastReply = _.last(replies);
if (lastReply) {
return lastReply;
}
return response;
}
/*
* iterate on all error handlers and simply return the first one that
* generates a reply
*/
public async handleErrors(
event: IVoxaEvent,
error: Error,
reply: IVoxaReply,
): Promise<IVoxaReply> {
const errorHandlers = this.getOnErrorHandlers(event.platform.name);
const replies: IVoxaReply[] = await bluebird.map(
errorHandlers,
async (handler: IErrorHandler) => {
return await handler(event, error, reply);
},
);
let response: IVoxaReply | undefined = _.find(replies);
if (!response) {
reply.clear();
response = reply;
}
return response;
}
// Call the specific request handlers for each request type
public async execute(
voxaEvent: IVoxaEvent,
reply: IVoxaReply,
): Promise<IVoxaReply> {
voxaEvent.log.debug("Received new event", { event: voxaEvent.rawEvent });
try {
if (!this.requestHandlers[voxaEvent.request.type]) {
throw new UnknownRequestType(voxaEvent.request.type);
}
const requestHandler = this.requestHandlers[voxaEvent.request.type];
const executeHandlers = async () => {
switch (voxaEvent.request.type) {
case "IntentRequest":
case "SessionEndedRequest": {
// call all onRequestStarted callbacks serially.
await bluebird.mapSeries(
this.getOnRequestStartedHandlers(voxaEvent.platform.name),
(fn: IEventHandler) => {
return fn(voxaEvent, reply);
},
);
if (voxaEvent.session.new) {
// call all onSessionStarted callbacks serially.
await bluebird.mapSeries(
this.getOnSessionStartedHandlers(voxaEvent.platform.name),
(fn: IEventHandler) => fn(voxaEvent, reply),
);
}
// Route the request to the proper handler which may have been overriden.
return await requestHandler(voxaEvent, reply);
}
default: {
return await requestHandler(voxaEvent, reply);
}
}
};
let response: IVoxaReply;
const context = voxaEvent.executionContext;
if (isLambdaContext(context)) {
const promises = [];
const { timer, timerPromise } = timeout(context);
promises.push(timerPromise);
promises.push(executeHandlers());
response = await bluebird.race(promises);
if (timer) {
clearTimeout(timer);
}
} else {
response = await executeHandlers();
}
return response;
} catch (error) {
return this.handleErrors(voxaEvent, error, reply);
}
}
/*
* Request handlers are in charge of responding to the different request types alexa sends,
* in general they will defer to the proper event handler
*/
public registerRequestHandler(requestType: string): void {
// .filter(requestType => !this.requestHandlers[requestType])
if (this.requestHandlers[requestType]) {
return;
}
const eventName = `on${_.upperFirst(requestType)}`;
this.registerEvent(eventName);
this.requestHandlers[requestType] = async (
voxaEvent: IVoxaEvent,
response: IVoxaReply,
): Promise<IVoxaReply> => {
const capitalizedEventName = _.upperFirst(_.camelCase(eventName));
const runCallback = (fn: IEventHandler): IVoxaReply | void =>
fn.call(this, voxaEvent, response);
const result = await bluebird.mapSeries(
this[`get${capitalizedEventName}Handlers`](),
runCallback,
);
// if the handlers produced a reply we return the last one
const lastReply = _(result)
.filter()
.last();
if (lastReply) {
return lastReply;
}
// else we return the one we started with
return response;
};
}
/*
* Event handlers are array of callbacks that get executed when an event is triggered
* they can return a promise if async execution is needed,
* most are registered with the voxaEvent handlers
* however there are some that don't map exactly to a voxaEvent and we register them in here,
* override the method to add new events.
*/
public registerEvents(): void {
// Called when the request starts.
this.registerEvent("onRequestStarted");
// Called when the session starts.
this.registerEvent("onSessionStarted");
// Called when the user ends the session.
this.registerEvent("onSessionEnded");
// Sent whenever there's an unhandled error in the onIntent code
this.registerEvent("onError");
//
// this are all StateMachine events
this.registerEvent("onBeforeStateChanged");
this.registerEvent("onAfterStateChanged");
this.registerEvent("onBeforeReplySent");
}
public onUnhandledState(fn: IUnhandledStateCb) {
this.config.onUnhandledState = fn;
}
/*
* Create an event handler register for the provided eventName
* This will keep 2 separate lists of event callbacks
*/
public registerEvent(eventName: string): void {
this.eventHandlers[eventName] = {
core: [],
coreLast: [], // we keep a separate list of event callbacks to alway execute them last
};
if (!this[eventName]) {
const capitalizedEventName = _.upperFirst(_.camelCase(eventName));
this[eventName] = (
callback: IEventHandler,
atLast: boolean = false,
platform: string = "core",
) => {
if (atLast) {
this.eventHandlers[eventName][`${platform}Last`] =
this.eventHandlers[eventName][`${platform}Last`] || [];
this.eventHandlers[eventName][`${platform}Last`].push(
callback.bind(this),
);
} else {
this.eventHandlers[eventName][platform] =
this.eventHandlers[eventName][platform] || [];
this.eventHandlers[eventName][platform].push(callback.bind(this));
}
};
this[`get${capitalizedEventName}Handlers`] = (
platform?: string,
): IEventHandler[] => {
let handlers: IEventHandler[];
if (platform) {
this.eventHandlers[eventName][platform] =
this.eventHandlers[eventName][platform] || [];
this.eventHandlers[eventName][`${platform}Last`] =
this.eventHandlers[eventName][`${platform}Last`] || [];
handlers = _.concat(
this.eventHandlers[eventName].core,
this.eventHandlers[eventName][platform],
this.eventHandlers[eventName].coreLast,
this.eventHandlers[eventName][`${platform}Last`],
);
} else {
handlers = _.concat(
this.eventHandlers[eventName].core,
this.eventHandlers[eventName].coreLast,
);
}
return handlers;
};
}
}
public onState(
stateName: string,
handler: IStateHandler | ITransition,
intents: string[] | string = [],
platform: string = "core",
): void {
const state = new State(stateName, handler, intents, platform);
this.states.push(state);
}
public onIntent(
intentName: string,
handler: IStateHandler | ITransition,
platform: string = "core",
): void {
this.onState(intentName, handler, intentName, platform);
}
public async runStateMachine(
voxaEvent: IVoxaIntentEvent,
response: IVoxaReply,
): Promise<IVoxaReply> {
let fromState = voxaEvent.session.new
? "entry"
: _.get(voxaEvent, "session.attributes.state", "entry");
if (fromState === "die") {
fromState = "entry";
}
const stateMachine = new StateMachine({
onAfterStateChanged: this.getOnAfterStateChangedHandlers(
voxaEvent.platform.name,
),
onBeforeStateChanged: this.getOnBeforeStateChangedHandlers(
voxaEvent.platform.name,
),
onUnhandledState: this.config.onUnhandledState,
states: this.states,
});
voxaEvent.log.debug("Starting the state machine", { fromState });
const transition = await stateMachine.runTransition(
fromState,
voxaEvent,
response,
);
if (transition.shouldTerminate) {
await this.handleOnSessionEnded(voxaEvent, response);
}
const onBeforeReplyHandlers = this.getOnBeforeReplySentHandlers(
voxaEvent.platform.name,
);
voxaEvent.log.debug("Running onBeforeReplySent");
await bluebird.mapSeries(onBeforeReplyHandlers, (fn: IEventHandler) =>
fn(voxaEvent, response, transition),
);
return response;
}
public async renderDirectives(
voxaEvent: IVoxaEvent,
response: IVoxaReply,
transition: SystemTransition,
): Promise<ITransition> {
const directiveClasses: IDirectiveClass[] = _.concat(
_.filter(this.directiveHandlers, { platform: "core" }),
_.filter(this.directiveHandlers, { platform: voxaEvent.platform.name }),
);
const directivesKeyOrder = _.map(directiveClasses, "key");
if (transition.reply) {
const replyTransition = await this.getReplyTransitions(
voxaEvent,
transition,
);
transition = _.merge(transition, replyTransition);
}
const directives: IDirective[] = _(transition)
.toPairs()
.sortBy((pair: any[]) => {
const [key, value] = pair;
return _.indexOf(directivesKeyOrder, key);
})
.map(_.spread(instantiateDirectives))
.flatten()
.concat(transition.directives || [])
.filter()
.filter((directive: IDirective): boolean => {
const constructor: any = directive.constructor;
return _.includes(
["core", voxaEvent.platform.name],
constructor.platform,
);
})
.value();
for (const handler of directives) {
await handler.writeToReply(response, voxaEvent, transition);
}
return transition;
function instantiateDirectives(key: string, value: any): IDirective[] {
let handlers: IDirectiveClass[] = _.filter(
directiveClasses,
(classObject: IDirectiveClass) => classObject.key === key,
);
if (handlers.length > 1) {
handlers = _.filter(
handlers,
(handler: IDirectiveClass) =>
handler.platform === voxaEvent.platform.name,
);
}
return _.map(
handlers,
(Directive: IDirectiveClass) => new Directive(value),
) as IDirective[];
}
}
public async saveSession(
voxaEvent: IVoxaEvent,
response: IVoxaReply,
transition: ITransition,
): Promise<void> {
const serialize = _.get(voxaEvent, "model.serialize");
// we do require models to have a serialize method and check that when Voxa is initialized,
// however, developers could do stuff like `voxaEvent.model = null`,
// which seems natural if they want to
// clear the model
if (!serialize) {
voxaEvent.model = new this.config.Model();
}
const stateName = transition.to;
// We save off the state so that we know where to resume from when the conversation resumes
const modelData = await voxaEvent.model.serialize();
const attributes = {
...voxaEvent.session.outputAttributes,
model: modelData,
state: stateName,
};
await response.saveSession(attributes, voxaEvent);
}
public async transformRequest(voxaEvent: IVoxaEvent): Promise<void> {
await this.i18nextPromise;
const data = voxaEvent.session.attributes.model as IBag;
const model = await this.config.Model.deserialize(data, voxaEvent);
voxaEvent.model = model;
voxaEvent.log.debug("Initialized model ", { model: voxaEvent.model });
voxaEvent.t = this.i18n.getFixedT(voxaEvent.request.locale);
voxaEvent.renderer = this.renderer;
}
private async getReplyTransitions(
voxaEvent: IVoxaEvent,
transition: ITransition,
): Promise<ITransition> {
if (!transition.reply) {
return {};
}
let finalReply = {};
let replies = [];
if (_.isArray(transition.reply)) {
replies = transition.reply;
} else {
replies = [transition.reply];
}
for (const replyItem of replies) {
const reply = await voxaEvent.renderer.renderPath(replyItem, voxaEvent);
const replyKeys = _.keys(reply);
const replyData = _(replyKeys)
.map((key) => {
return [key, replyItem + "." + key];
})
.fromPairs()
.value();
finalReply = _.mergeWith(finalReply, replyData, function customizer(
objValue,
srcValue,
) {
if (!objValue) {
return; // use default merge behavior
}
if (_.isArray(objValue)) {
return objValue.concat(srcValue);
}
return [objValue, srcValue];
});
}
return finalReply;
}
}
export function initializeI118n(
i18nInstance: i18next.i18n,
views: i18next.Resource,
): bluebird<i18next.TFunction> {
type IInitializer = (
options: i18next.InitOptions,
) => bluebird<i18next.TFunction>;
const initialize = bluebird.promisify(i18nInstance.init, {
context: i18nInstance,
}) as IInitializer;
return initialize({
fallbackLng: "en",
load: "all",
nonExplicitWhitelist: true,
resources: views,
});
} | the_stack |
import { should } from 'chai';
import { tokenize, Input, Token, NamespaceStyle } from './utils/tokenize';
describe("Record", () => {
before(() => { should(); });
describe("Record", () => {
for (const namespaceStyle of [NamespaceStyle.BlockScoped, NamespaceStyle.FileScoped]) {
const styleName = namespaceStyle == NamespaceStyle.BlockScoped
? "Block-Scoped"
: "File-Scoped";
it(`record keyword and storage modifiers (${styleName} Namespace)`, async () => {
const input = Input.InNamespace(`
public record PublicRecord { }
record DefaultRecord { }
internal record InternalRecord { }
static record DefaultStaticRecord { }
public static record PublicStaticRecord { }
sealed record DefaultSealedRecord { }
public sealed record PublicSealedRecord { }
public abstract record PublicAbstractRecord { }
abstract record DefaultAbstractRecord { }`, namespaceStyle);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Public,
Token.Keywords.Record,
Token.Identifiers.RecordName("PublicRecord"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Record,
Token.Identifiers.RecordName("DefaultRecord"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Modifiers.Internal,
Token.Keywords.Record,
Token.Identifiers.RecordName("InternalRecord"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Modifiers.Static,
Token.Keywords.Record,
Token.Identifiers.RecordName("DefaultStaticRecord"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Modifiers.Public,
Token.Keywords.Modifiers.Static,
Token.Keywords.Record,
Token.Identifiers.RecordName("PublicStaticRecord"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Modifiers.Sealed,
Token.Keywords.Record,
Token.Identifiers.RecordName("DefaultSealedRecord"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Modifiers.Public,
Token.Keywords.Modifiers.Sealed,
Token.Keywords.Record,
Token.Identifiers.RecordName("PublicSealedRecord"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Modifiers.Public,
Token.Keywords.Modifiers.Abstract,
Token.Keywords.Record,
Token.Identifiers.RecordName("PublicAbstractRecord"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Modifiers.Abstract,
Token.Keywords.Record,
Token.Identifiers.RecordName("DefaultAbstractRecord"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
it(`generics in identifier (${styleName} Namespace)`, async () => {
const input = Input.InNamespace(`record Dictionary<TKey, TValue> { }`, namespaceStyle);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Record,
Token.Identifiers.RecordName("Dictionary"),
Token.Punctuation.TypeParameters.Begin,
Token.Identifiers.TypeParameterName("TKey"),
Token.Punctuation.Comma,
Token.Identifiers.TypeParameterName("TValue"),
Token.Punctuation.TypeParameters.End,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
it(`inheritance (${styleName} Namespace)`, async () => {
const input = Input.InNamespace(`
record PublicRecord : IInterface, IInterfaceTwo { }
record PublicRecord<T> : Root.IInterface<Something.Nested>, Something.IInterfaceTwo { }
record PublicRecord<T> : Dictionary<T, Dictionary<string, string>>, IMap<T, Dictionary<string, string>> { }`, namespaceStyle);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Record,
Token.Identifiers.RecordName("PublicRecord"),
Token.Punctuation.Colon,
Token.Type("IInterface"),
Token.Punctuation.Comma,
Token.Type("IInterfaceTwo"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Record,
Token.Identifiers.RecordName("PublicRecord"),
Token.Punctuation.TypeParameters.Begin,
Token.Identifiers.TypeParameterName("T"),
Token.Punctuation.TypeParameters.End,
Token.Punctuation.Colon,
Token.Type("Root"),
Token.Punctuation.Accessor,
Token.Type("IInterface"),
Token.Punctuation.TypeParameters.Begin,
Token.Type("Something"),
Token.Punctuation.Accessor,
Token.Type("Nested"),
Token.Punctuation.TypeParameters.End,
Token.Punctuation.Comma,
Token.Type("Something"),
Token.Punctuation.Accessor,
Token.Type("IInterfaceTwo"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Record,
Token.Identifiers.RecordName("PublicRecord"),
Token.Punctuation.TypeParameters.Begin,
Token.Identifiers.TypeParameterName("T"),
Token.Punctuation.TypeParameters.End,
Token.Punctuation.Colon,
Token.Type("Dictionary"),
Token.Punctuation.TypeParameters.Begin,
Token.Type("T"),
Token.Punctuation.Comma,
Token.Type("Dictionary"),
Token.Punctuation.TypeParameters.Begin,
Token.PrimitiveType.String,
Token.Punctuation.Comma,
Token.PrimitiveType.String,
Token.Punctuation.TypeParameters.End,
Token.Punctuation.TypeParameters.End,
Token.Punctuation.Comma,
Token.Type("IMap"),
Token.Punctuation.TypeParameters.Begin,
Token.Type("T"),
Token.Punctuation.Comma,
Token.Type("Dictionary"),
Token.Punctuation.TypeParameters.Begin,
Token.PrimitiveType.String,
Token.Punctuation.Comma,
Token.PrimitiveType.String,
Token.Punctuation.TypeParameters.End,
Token.Punctuation.TypeParameters.End,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
it(`generic constraints (${styleName} Namespace)`, async () => {
const input = Input.InNamespace(`
record PublicRecord<T> where T : ISomething { }
record PublicRecord<T, X> : Dictionary<T, List<string>[]>, ISomething
where T : ICar, new()
where X : struct
{
}`, namespaceStyle);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Record,
Token.Identifiers.RecordName("PublicRecord"),
Token.Punctuation.TypeParameters.Begin,
Token.Identifiers.TypeParameterName("T"),
Token.Punctuation.TypeParameters.End,
Token.Keywords.Where,
Token.Type("T"),
Token.Punctuation.Colon,
Token.Type("ISomething"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Record,
Token.Identifiers.RecordName("PublicRecord"),
Token.Punctuation.TypeParameters.Begin,
Token.Identifiers.TypeParameterName("T"),
Token.Punctuation.Comma,
Token.Identifiers.TypeParameterName("X"),
Token.Punctuation.TypeParameters.End,
Token.Punctuation.Colon,
Token.Type("Dictionary"),
Token.Punctuation.TypeParameters.Begin,
Token.Type("T"),
Token.Punctuation.Comma,
Token.Type("List"),
Token.Punctuation.TypeParameters.Begin,
Token.PrimitiveType.String,
Token.Punctuation.TypeParameters.End,
Token.Punctuation.OpenBracket,
Token.Punctuation.CloseBracket,
Token.Punctuation.TypeParameters.End,
Token.Punctuation.Comma,
Token.Type("ISomething"),
Token.Keywords.Where,
Token.Type("T"),
Token.Punctuation.Colon,
Token.Type("ICar"),
Token.Punctuation.Comma,
Token.Keywords.New,
Token.Punctuation.OpenParen,
Token.Punctuation.CloseParen,
Token.Keywords.Where,
Token.Type("X"),
Token.Punctuation.Colon,
Token.Keywords.Struct,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
it(`nested record (${styleName} Namespace)`, async () => {
const input = Input.InNamespace(`
record Klass
{
record Nested
{
}
}`, namespaceStyle);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Record,
Token.Identifiers.RecordName("Klass"),
Token.Punctuation.OpenBrace,
Token.Keywords.Record,
Token.Identifiers.RecordName("Nested"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Punctuation.CloseBrace]);
});
it(`nested record with modifier (${styleName} Namespace)`, async () => {
const input = Input.InNamespace(`
record Klass
{
public record Nested
{
}
}`, namespaceStyle);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Record,
Token.Identifiers.RecordName("Klass"),
Token.Punctuation.OpenBrace,
Token.Keywords.Modifiers.Public,
Token.Keywords.Record,
Token.Identifiers.RecordName("Nested"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Punctuation.CloseBrace]);
});
it(`unsafe record (${styleName} Namespace)`, async () => {
const input = Input.InNamespace(`
unsafe record C
{
}`, namespaceStyle);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Unsafe,
Token.Keywords.Record,
Token.Identifiers.RecordName("C"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
}
});
}); | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormDuplicateRule_Information {
interface tab_administration_Sections {
section_1_2: DevKit.Controls.Section;
}
interface tab_notes_Sections {
notes: DevKit.Controls.Section;
}
interface tab_rule_Sections {
criteria: DevKit.Controls.Section;
description: DevKit.Controls.Section;
Rule_Conditions: DevKit.Controls.Section;
section_1: DevKit.Controls.Section;
}
interface tab_administration extends DevKit.Controls.ITab {
Section: tab_administration_Sections;
}
interface tab_notes extends DevKit.Controls.ITab {
Section: tab_notes_Sections;
}
interface tab_rule extends DevKit.Controls.ITab {
Section: tab_rule_Sections;
}
interface Tabs {
administration: tab_administration;
notes: tab_notes;
rule: tab_rule;
}
interface Body {
Tab: Tabs;
/** Record type of the record being evaluated for potential duplicates. */
BaseEntityTypeCode: DevKit.Controls.OptionSet;
/** Unique identifier of the user who created the duplicate detection rule. */
CreatedBy: DevKit.Controls.Lookup;
/** Date and time when the duplicate detection rule was created. */
CreatedOn: DevKit.Controls.DateTime;
/** Description of the duplicate detection rule. */
Description: DevKit.Controls.String;
/** Determines whether to flag inactive records as duplicates */
ExcludeInactiveRecords: DevKit.Controls.Boolean;
/** Indicates if the operator is case-sensitive. */
IsCaseSensitive: DevKit.Controls.Boolean;
/** Record type of the records being evaluated as potential duplicates. */
MatchingEntityTypeCode: DevKit.Controls.OptionSet;
/** Unique identifier of the user who last modified the duplicate detection rule. */
ModifiedBy: DevKit.Controls.Lookup;
/** Date and time when the duplicate detection rule was last modified. */
ModifiedOn: DevKit.Controls.DateTime;
/** Name of the duplicate detection rule. */
Name: DevKit.Controls.String;
notescontrol: DevKit.Controls.Note;
/** Unique identifier of the user or team who owns the duplicate detection rule. */
OwnerId: DevKit.Controls.Lookup;
ruleconditioncontrol: DevKit.Controls.IFrame;
/** Reason for the status of the duplicate detection rule. */
StatusCode: DevKit.Controls.OptionSet;
}
}
class FormDuplicateRule_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form DuplicateRule_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form DuplicateRule_Information */
Body: DevKit.FormDuplicateRule_Information.Body;
}
class DuplicateRuleApi {
/**
* DynamicsCrm.DevKit DuplicateRuleApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Database table that stores match codes for the record type being evaluated for potential duplicates. */
BaseEntityMatchCodeTable: DevKit.WebApi.StringValueReadonly;
/** Record type of the record being evaluated for potential duplicates. */
BaseEntityName: DevKit.WebApi.StringValue;
/** Record type of the record being evaluated for potential duplicates. */
BaseEntityTypeCode: DevKit.WebApi.OptionSetValueReadonly;
/** Unique identifier of the user who created the duplicate detection rule. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the duplicate detection rule was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the duplicaterule. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Description of the duplicate detection rule. */
Description: DevKit.WebApi.StringValue;
/** Unique identifier of the duplicate detection rule. */
DuplicateRuleId: DevKit.WebApi.GuidValue;
/** Determines whether to flag inactive records as duplicates */
ExcludeInactiveRecords: DevKit.WebApi.BooleanValue;
/** Indicates if the operator is case-sensitive. */
IsCaseSensitive: DevKit.WebApi.BooleanValue;
/** Database table that stores match codes for potential duplicate records. */
MatchingEntityMatchCodeTable: DevKit.WebApi.StringValueReadonly;
/** Record type of the records being evaluated as potential duplicates. */
MatchingEntityName: DevKit.WebApi.StringValue;
/** Record type of the records being evaluated as potential duplicates. */
MatchingEntityTypeCode: DevKit.WebApi.OptionSetValueReadonly;
/** Unique identifier of the user who last modified the duplicate detection rule. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the duplicate detection rule was last modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who last modified the duplicaterule. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Name of the duplicate detection rule. */
Name: DevKit.WebApi.StringValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier of the business unit that owns duplicate detection rule. */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the team who owns the duplicate detection rule. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the user who owns the duplicate detection rule. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the duplicate detection rule. */
StateCode: DevKit.WebApi.OptionSetValueReadonly;
/** Reason for the status of the duplicate detection rule. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
}
}
declare namespace OptionSet {
namespace DuplicateRule {
enum BaseEntityTypeCode {
/** 1 */
Account,
/** 8040 */
ACIViewMapper,
/** 9962 */
Action_Card,
/** 9983 */
Action_Card_Type,
/** 9973 */
Action_Card_User_Settings,
/** 9968 */
ActionCardUserState,
/** 4200 */
Activity,
/** 10049 */
Activity_File_Attachment,
/** 135 */
Activity_Party,
/** 1071 */
Address,
/** 9949 */
Advanced_Similarity_Rule,
/** 10079 */
AI_Builder_Dataset,
/** 10080 */
AI_Builder_Dataset_File,
/** 10081 */
AI_Builder_Dataset_Record,
/** 10082 */
AI_Builder_Datasets_Container,
/** 10083 */
AI_Builder_File,
/** 10084 */
AI_Builder_File_Attached_Data,
/** 402 */
AI_Configuration,
/** 10085 */
AI_Form_Processing_Document,
/** 401 */
AI_Model,
/** 10088 */
AI_Object_Detection_Bounding_Box,
/** 10086 */
AI_Object_Detection_Image,
/** 10089 */
AI_Object_Detection_Image_Mapping,
/** 10087 */
AI_Object_Detection_Label,
/** 400 */
AI_Template,
/** 132 */
Announcement,
/** 2000 */
Annual_Fiscal_Calendar,
/** 9011 */
App_Config_Master,
/** 9012 */
App_Configuration,
/** 9013 */
App_Configuration_Instance,
/** 9007 */
App_Module_Component,
/** 9009 */
App_Module_Roles,
/** 4707 */
Application_File,
/** 1120 */
Application_Ribbons,
/** 10021 */
ApplicationUser,
/** 8700 */
AppModule_Metadata,
/** 8702 */
AppModule_Metadata_Async_Operation,
/** 8701 */
AppModule_Metadata_Dependency,
/** 4201 */
Appointment,
/** 127 */
Article,
/** 1082 */
Article_Comment,
/** 1016 */
Article_Template,
/** 1001 */
Attachment_1001,
/** 1002 */
Attachment_1002,
/** 9808 */
Attribute,
/** 4601 */
Attribute_Map,
/** 4567 */
Auditing,
/** 1094 */
Authorization_Server,
/** 9936 */
Azure_Service_Connection,
/** 10039 */
BotContent,
/** 10115 */
BPF_Account,
/** 4425 */
Bulk_Delete_Failure,
/** 4424 */
Bulk_Delete_Operation,
/** 4232 */
Business_Data_Localized_Label,
/** 4725 */
Business_Process_Flow_Instance,
/** 10 */
Business_Unit,
/** 6 */
Business_Unit_Map,
/** 4003 */
Calendar,
/** 4004 */
Calendar_Rule,
/** 301 */
Callback_Registration,
/** 300 */
Canvas_App,
/** 10031 */
CanvasApp_Extended_Metadata,
/** 10018 */
CascadeGrantRevokeAccessRecordsTracker,
/** 10019 */
CascadeGrantRevokeAccessVersionTracker,
/** 10065 */
Catalog,
/** 10066 */
Catalog_Assignment,
/** 9959 */
Category,
/** 3005 */
Channel_Access_Profile,
/** 9400 */
Channel_Access_Profile_Rule,
/** 9401 */
Channel_Access_Profile_Rule_Item,
/** 1236 */
Channel_Property,
/** 1234 */
Channel_Property_Group,
/** 10041 */
Chatbot,
/** 10042 */
Chatbot_subcomponent,
/** 36 */
Client_update,
/** 4417 */
Column_Mapping,
/** 8005 */
Comment,
/** 10005 */
Component_Layer,
/** 10006 */
Component_Layer_Data_Source,
/** 3234 */
Connection,
/** 10037 */
Connection_Reference,
/** 3231 */
Connection_Role,
/** 3233 */
Connection_Role_Object_Type_Code,
/** 372 */
Connector,
/** 2 */
Contact,
/** 10040 */
ConversationTranscript,
/** 9105 */
Currency,
/** 10068 */
Custom_API,
/** 10069 */
Custom_API_Request_Parameter,
/** 10070 */
Custom_API_Response_Property,
/** 9753 */
Custom_Control,
/** 9755 */
Custom_Control_Default_Config,
/** 9754 */
Custom_Control_Resource,
/** 4502 */
Customer_Relationship,
/** 4410 */
Data_Import,
/** 10014 */
Data_Lake_Folder,
/** 10015 */
Data_Lake_Folder_Permission,
/** 10016 */
Data_Lake_Workspace,
/** 10017 */
Data_Lake_Workspace_Permission,
/** 4411 */
Data_Map,
/** 4450 */
Data_Performance_Dashboard,
/** 10164 */
Data_Source,
/** 10167 */
Data_Source_2,
/** 10168 */
Data_Source_3,
/** 418 */
Dataflow,
/** 9961 */
DelveActionHub,
/** 7105 */
Dependency,
/** 7108 */
Dependency_Feature,
/** 7106 */
Dependency_Node,
/** 4102 */
Display_String,
/** 4101 */
Display_String_Map,
/** 9508 */
Document_Location,
/** 1189 */
Document_Suggestions,
/** 9940 */
Document_Template,
/** 4414 */
Duplicate_Detection_Rule,
/** 4415 */
Duplicate_Record,
/** 4416 */
Duplicate_Rule_Condition,
/** 4202 */
Email,
/** 4023 */
Email_Hash,
/** 4299 */
Email_Search,
/** 9605 */
Email_Server_Profile,
/** 9997 */
Email_Signature,
/** 2010 */
Email_Template,
/** 9800 */
Entity,
/** 430 */
Entity_Analytics_Config,
/** 432 */
Entity_Image_Configuration,
/** 9810 */
Entity_Key,
/** 4600 */
Entity_Map,
/** 9811 */
Entity_Relationship,
/** 380 */
Environment_Variable_Definition,
/** 381 */
Environment_Variable_Value,
/** 4120 */
Exchange_Sync_Id_Mapping,
/** 4711 */
Expander_Event,
/** 955 */
Expired_Process,
/** 10010 */
ExportSolutionUpload,
/** 3008 */
External_Party,
/** 9987 */
External_Party_Item,
/** 4204 */
Fax,
/** 10165 */
FeatureControlSetting,
/** 9958 */
Feedback,
/** 1201 */
Field_Permission,
/** 1200 */
Field_Security_Profile,
/** 44 */
Field_Sharing,
/** 55 */
FileAttachment,
/** 30 */
Filter_Template,
/** 2004 */
Fixed_Monthly_Fiscal_Calendar,
/** 10033 */
Flow_Machine,
/** 10034 */
Flow_Machine_Group,
/** 4720 */
Flow_Session,
/** 8003 */
Follow,
/** 54 */
Global_Search_Configuration,
/** 9600 */
Goal,
/** 9603 */
Goal_Metric,
/** 10116 */
Help_Page,
/** 8840 */
Hierarchy_Rule,
/** 9919 */
Hierarchy_Security_Configuration,
/** 9996 */
HolidayWrapper,
/** 431 */
Image_Attribute_Configuration,
/** 1007 */
Image_Descriptor,
/** 4413 */
Import_Data,
/** 4428 */
Import_Entity_Mapping,
/** 9107 */
Import_Job,
/** 4423 */
Import_Log,
/** 4412 */
Import_Source_File,
/** 126 */
Indexed_Article,
/** 3000 */
Integration_Status,
/** 4011 */
Inter_Process_Lock,
/** 9986 */
Interaction_for_Email,
/** 1003 */
Internal_Address,
/** 10067 */
Internal_Catalog_Assignment,
/** 7107 */
Invalid_Dependency,
/** 4705 */
ISV_Config,
/** 10063 */
KeyVaultReference,
/** 9953 */
Knowledge_Article,
/** 9960 */
Knowledge_Article_Category,
/** 10055 */
Knowledge_Article_Image,
/** 10058 */
Knowledge_article_language_setting,
/** 10060 */
Knowledge_Article_Template,
/** 9955 */
Knowledge_Article_Views,
/** 9930 */
Knowledge_Base_Record,
/** 10052 */
Knowledge_Federated_Article,
/** 10053 */
Knowledge_FederatedArticle_Incident,
/** 10056 */
Knowledge_Interaction_Insight,
/** 10059 */
Knowledge_personalization,
/** 10062 */
Knowledge_search_filter,
/** 10057 */
Knowledge_Search_Insight,
/** 9947 */
Knowledge_Search_Model,
/** 10061 */
Knowledge_search_personal_filter_config,
/** 9957 */
Language,
/** 9875 */
Language_Provisioning_State,
/** 4207 */
Letter,
/** 2027 */
License,
/** 8006 */
Like,
/** 4418 */
List_Value_Mapping,
/** 9201 */
LocalConfigStore,
/** 4419 */
Lookup_Mapping,
/** 9106 */
Mail_Merge_Template,
/** 9606 */
Mailbox,
/** 9608 */
Mailbox_Auto_Tracking_Folder,
/** 9607 */
Mailbox_Statistics,
/** 9609 */
Mailbox_Tracking_Category,
/** 9812 */
Managed_Property,
/** 10064 */
ManagedIdentity,
/** 4231 */
Metadata_Difference,
/** 9866 */
Mobile_Offline_Profile,
/** 9867 */
Mobile_Offline_Profile_Item,
/** 9868 */
Mobile_Offline_Profile_Item_Association,
/** 9006 */
Model_driven_App,
/** 10026 */
Model_Driven_App_Component_Node,
/** 10025 */
Model_Driven_App_Component_Nodes_Edge,
/** 10024 */
Model_Driven_App_Element,
/** 10027 */
Model_Driven_App_Setting,
/** 10028 */
Model_Driven_App_User_Setting,
/** 2003 */
Monthly_Fiscal_Calendar,
/** 9912 */
Multi_Select_Option_Value,
/** 9910 */
MultiEntitySearch,
/** 9900 */
Navigation_Setting,
/** 950 */
New_Process,
/** 10077 */
NonRelational_Data_Source,
/** 5 */
Note,
/** 10075 */
Notification_10075,
/** 4110 */
Notification_4110,
/** 10032 */
OData_v4_Data_Source,
/** 4490 */
Office_Document,
/** 9950 */
Office_Graph_Document,
/** 9870 */
Offline_Command_Definition,
/** 9809 */
OptionSet,
/** 1019 */
Organization,
/** 9699 */
Organization_Insights_Metric,
/** 9690 */
Organization_Insights_Notification,
/** 10029 */
Organization_Setting,
/** 4708 */
Organization_Statistic,
/** 1021 */
Organization_UI,
/** 10073 */
OrganizationDataSyncSubscription,
/** 10074 */
OrganizationDataSyncSubscriptionEntity,
/** 7 */
Owner,
/** 4420 */
Owner_Mapping,
/** 10007 */
Package,
/** 1095 */
Partner_Application,
/** 10048 */
PDF_Setting,
/** 9941 */
Personal_Document_Template,
/** 4210 */
Phone_Call,
/** 4605 */
Plug_in_Assembly,
/** 4619 */
Plug_in_Trace_Log,
/** 4602 */
Plug_in_Type,
/** 4603 */
Plug_in_Type_Statistic,
/** 10166 */
Plugin_Package,
/** 10091 */
PM_Inferred_Task,
/** 10092 */
PM_Recording,
/** 50 */
Position,
/** 8000 */
Post,
/** 8002 */
Post_Regarding,
/** 8001 */
Post_Role,
/** 1404 */
Principal_Sync_Attribute_Map,
/** 1023 */
Privilege,
/** 31 */
Privilege_Object_Type_Code,
/** 4703 */
Process,
/** 9650 */
Process_Configuration,
/** 4704 */
Process_Dependency,
/** 4706 */
Process_Log,
/** 4710 */
Process_Session,
/** 4724 */
Process_Stage,
/** 4712 */
Process_Trigger,
/** 10035 */
ProcessStageParameter,
/** 10013 */
ProvisionLanguageForUser,
/** 7101 */
Publisher,
/** 7102 */
Publisher_Address,
/** 2002 */
Quarterly_Fiscal_Calendar,
/** 2020 */
Queue,
/** 2029 */
Queue_Item,
/** 2023 */
QueueItemCount,
/** 2024 */
QueueMemberCount,
/** 9300 */
Record_Creation_and_Update_Rule,
/** 9301 */
Record_Creation_and_Update_Rule_Item,
/** 4250 */
Recurrence_Rule,
/** 4251 */
Recurring_Appointment,
/** 9814 */
Relationship_Attribute,
/** 9813 */
Relationship_Entity,
/** 4500 */
Relationship_Role,
/** 4501 */
Relationship_Role_Map,
/** 1140 */
Replication_Backlog,
/** 9100 */
Report,
/** 9104 */
Report_Link,
/** 9102 */
Report_Related_Category,
/** 9101 */
Report_Related_Entity,
/** 9103 */
Report_Visibility,
/** 90001 */
RevokeInheritedAccessRecordsTracker,
/** 4579 */
Ribbon_Client_Metadata,
/** 1116 */
Ribbon_Command,
/** 1115 */
Ribbon_Context_Group,
/** 1130 */
Ribbon_Difference,
/** 9880 */
Ribbon_Metadata_To_Process,
/** 1117 */
Ribbon_Rule,
/** 1113 */
Ribbon_Tab_To_Command_Mapping,
/** 10076 */
Rich_Text_Attachment,
/** 1037 */
Role_Template,
/** 9604 */
Rollup_Field,
/** 9511 */
Rollup_Job,
/** 9510 */
Rollup_Properties,
/** 9602 */
Rollup_Query,
/** 8181 */
Routing_Rule_Set,
/** 8199 */
Rule_Item,
/** 7200 */
RuntimeDependency,
/** 1309 */
Saved_Organization_Insights_Configuration,
/** 4230 */
Saved_View,
/** 4606 */
Sdk_Message,
/** 4607 */
Sdk_Message_Filter,
/** 4613 */
Sdk_Message_Pair,
/** 4608 */
Sdk_Message_Processing_Step,
/** 4615 */
Sdk_Message_Processing_Step_Image,
/** 4616 */
Sdk_Message_Processing_Step_Secure_Configuration,
/** 4609 */
Sdk_Message_Request,
/** 4614 */
Sdk_Message_Request_Field,
/** 4610 */
Sdk_Message_Response,
/** 4611 */
Sdk_Message_Response_Field,
/** 10054 */
Search_provider,
/** 10078 */
Search_Telemetry,
/** 1036 */
Security_Role,
/** 2001 */
Semiannual_Fiscal_Calendar,
/** 10050 */
Service_Configuration,
/** 4618 */
Service_Endpoint,
/** 101 */
Service_Plan,
/** 10170 */
Service_Plan_Mapping,
/** 10030 */
Setting_Definition,
/** 9509 */
SharePoint_Data,
/** 9507 */
Sharepoint_Document,
/** 9502 */
SharePoint_Site,
/** 9951 */
Similarity_Rule,
/** 4709 */
Site_Map,
/** 9750 */
SLA,
/** 9751 */
SLA_Item,
/** 10051 */
SLA_KPI,
/** 9752 */
SLA_KPI_Instance,
/** 4216 */
Social_Activity,
/** 99 */
Social_Profile,
/** 1300 */
SocialInsightsConfiguration,
/** 7100 */
Solution,
/** 7103 */
Solution_Component,
/** 10000 */
Solution_Component_Attribute_Configuration,
/** 10169 */
Solution_Component_Batch_Configuration,
/** 10001 */
Solution_Component_Configuration,
/** 10012 */
Solution_Component_Data_Source,
/** 7104 */
Solution_Component_Definition,
/** 10002 */
Solution_Component_Relationship_Configuration,
/** 10011 */
Solution_Component_Summary,
/** 10003 */
Solution_History,
/** 10004 */
Solution_History_Data_Source,
/** 9890 */
SolutionHistoryData,
/** 10009 */
StageSolutionUpload,
/** 1075 */
Status_Map,
/** 1043 */
String_Map,
/** 129 */
Subject,
/** 29 */
Subscription,
/** 1072 */
Subscription_Clients,
/** 37 */
Subscription_Manually_Tracked_Object,
/** 45 */
Subscription_Statistic_Offline,
/** 46 */
Subscription_Statistic_Outlook,
/** 47 */
Subscription_Sync_Entry_Offline,
/** 48 */
Subscription_Sync_Entry_Outlook,
/** 33 */
Subscription_Synchronization_Information,
/** 1190 */
SuggestionCardTemplate,
/** 1401 */
Sync_Attribute_Mapping,
/** 1400 */
Sync_Attribute_Mapping_Profile,
/** 9869 */
Sync_Error,
/** 7000 */
System_Application_Metadata,
/** 1111 */
System_Chart,
/** 1030 */
System_Form,
/** 4700 */
System_Job,
/** 51 */
System_User_Manager_Map,
/** 14 */
System_User_Principal,
/** 42 */
SystemUser_BusinessUnit_Entity_Map,
/** 60 */
SystemUserAuthorizationChangeTracker,
/** 4212 */
Task,
/** 9 */
Team,
/** 1203 */
Team_Profiles,
/** 1403 */
Team_Sync_Attribute_Mapping_Profiles,
/** 92 */
Team_template,
/** 10071 */
TeamMobileOfflineProfileMembership,
/** 2013 */
Territory,
/** 9945 */
Text_Analytics_Entity_Mapping,
/** 2015 */
Theme,
/** 9932 */
Time_Stamp_Date_Mapping,
/** 4810 */
Time_Zone_Definition,
/** 4812 */
Time_Zone_Localized_Name,
/** 4811 */
Time_Zone_Rule,
/** 10117 */
Tour,
/** 8050 */
Trace,
/** 8051 */
Trace_Association,
/** 8052 */
Trace_Regarding,
/** 35 */
Tracking_information_for_deleted_entities,
/** 4426 */
Transformation_Mapping,
/** 4427 */
Transformation_Parameter_Mapping,
/** 951 */
Translation_Process,
/** 2012 */
Unresolved_Address,
/** 4220 */
UntrackedEmail,
/** 8 */
User,
/** 7001 */
User_Application_Metadata,
/** 1112 */
User_Chart,
/** 1031 */
User_Dashboard,
/** 2501 */
User_Entity_Instance_Data,
/** 2500 */
User_Entity_UI_Settings,
/** 1086 */
User_Fiscal_Calendar,
/** 2016 */
User_Mapping,
/** 52 */
User_Search_Facet,
/** 150 */
User_Settings,
/** 10072 */
UserMobileOfflineProfileMembership,
/** 1039 */
View,
/** 78 */
Virtual_Entity_Data_Provider,
/** 85 */
Virtual_Entity_Data_Source,
/** 10118 */
Virtual_Entity_Metadata,
/** 9333 */
Web_Resource,
/** 4800 */
Web_Wizard,
/** 4803 */
Web_Wizard_Access_Privilege,
/** 4802 */
Wizard_Page,
/** 10036 */
Workflow_Binary,
/** 4702 */
Workflow_Wait_Subscription
}
enum MatchingEntityTypeCode {
/** 1 */
Account,
/** 8040 */
ACIViewMapper,
/** 9962 */
Action_Card,
/** 9983 */
Action_Card_Type,
/** 9973 */
Action_Card_User_Settings,
/** 9968 */
ActionCardUserState,
/** 4200 */
Activity,
/** 10049 */
Activity_File_Attachment,
/** 135 */
Activity_Party,
/** 1071 */
Address,
/** 9949 */
Advanced_Similarity_Rule,
/** 10079 */
AI_Builder_Dataset,
/** 10080 */
AI_Builder_Dataset_File,
/** 10081 */
AI_Builder_Dataset_Record,
/** 10082 */
AI_Builder_Datasets_Container,
/** 10083 */
AI_Builder_File,
/** 10084 */
AI_Builder_File_Attached_Data,
/** 402 */
AI_Configuration,
/** 10085 */
AI_Form_Processing_Document,
/** 401 */
AI_Model,
/** 10088 */
AI_Object_Detection_Bounding_Box,
/** 10086 */
AI_Object_Detection_Image,
/** 10089 */
AI_Object_Detection_Image_Mapping,
/** 10087 */
AI_Object_Detection_Label,
/** 400 */
AI_Template,
/** 132 */
Announcement,
/** 2000 */
Annual_Fiscal_Calendar,
/** 9011 */
App_Config_Master,
/** 9012 */
App_Configuration,
/** 9013 */
App_Configuration_Instance,
/** 9007 */
App_Module_Component,
/** 9009 */
App_Module_Roles,
/** 4707 */
Application_File,
/** 1120 */
Application_Ribbons,
/** 10021 */
ApplicationUser,
/** 8700 */
AppModule_Metadata,
/** 8702 */
AppModule_Metadata_Async_Operation,
/** 8701 */
AppModule_Metadata_Dependency,
/** 4201 */
Appointment,
/** 127 */
Article,
/** 1082 */
Article_Comment,
/** 1016 */
Article_Template,
/** 1001 */
Attachment_1001,
/** 1002 */
Attachment_1002,
/** 9808 */
Attribute,
/** 4601 */
Attribute_Map,
/** 4567 */
Auditing,
/** 1094 */
Authorization_Server,
/** 9936 */
Azure_Service_Connection,
/** 10039 */
BotContent,
/** 10115 */
BPF_Account,
/** 4425 */
Bulk_Delete_Failure,
/** 4424 */
Bulk_Delete_Operation,
/** 4232 */
Business_Data_Localized_Label,
/** 4725 */
Business_Process_Flow_Instance,
/** 10 */
Business_Unit,
/** 6 */
Business_Unit_Map,
/** 4003 */
Calendar,
/** 4004 */
Calendar_Rule,
/** 301 */
Callback_Registration,
/** 300 */
Canvas_App,
/** 10031 */
CanvasApp_Extended_Metadata,
/** 10018 */
CascadeGrantRevokeAccessRecordsTracker,
/** 10019 */
CascadeGrantRevokeAccessVersionTracker,
/** 10065 */
Catalog,
/** 10066 */
Catalog_Assignment,
/** 9959 */
Category,
/** 3005 */
Channel_Access_Profile,
/** 9400 */
Channel_Access_Profile_Rule,
/** 9401 */
Channel_Access_Profile_Rule_Item,
/** 1236 */
Channel_Property,
/** 1234 */
Channel_Property_Group,
/** 10041 */
Chatbot,
/** 10042 */
Chatbot_subcomponent,
/** 36 */
Client_update,
/** 4417 */
Column_Mapping,
/** 8005 */
Comment,
/** 10005 */
Component_Layer,
/** 10006 */
Component_Layer_Data_Source,
/** 3234 */
Connection,
/** 10037 */
Connection_Reference,
/** 3231 */
Connection_Role,
/** 3233 */
Connection_Role_Object_Type_Code,
/** 372 */
Connector,
/** 2 */
Contact,
/** 10040 */
ConversationTranscript,
/** 9105 */
Currency,
/** 10068 */
Custom_API,
/** 10069 */
Custom_API_Request_Parameter,
/** 10070 */
Custom_API_Response_Property,
/** 9753 */
Custom_Control,
/** 9755 */
Custom_Control_Default_Config,
/** 9754 */
Custom_Control_Resource,
/** 4502 */
Customer_Relationship,
/** 4410 */
Data_Import,
/** 10014 */
Data_Lake_Folder,
/** 10015 */
Data_Lake_Folder_Permission,
/** 10016 */
Data_Lake_Workspace,
/** 10017 */
Data_Lake_Workspace_Permission,
/** 4411 */
Data_Map,
/** 4450 */
Data_Performance_Dashboard,
/** 10164 */
Data_Source,
/** 10167 */
Data_Source_2,
/** 10168 */
Data_Source_3,
/** 418 */
Dataflow,
/** 9961 */
DelveActionHub,
/** 7105 */
Dependency,
/** 7108 */
Dependency_Feature,
/** 7106 */
Dependency_Node,
/** 4102 */
Display_String,
/** 4101 */
Display_String_Map,
/** 9508 */
Document_Location,
/** 1189 */
Document_Suggestions,
/** 9940 */
Document_Template,
/** 4414 */
Duplicate_Detection_Rule,
/** 4415 */
Duplicate_Record,
/** 4416 */
Duplicate_Rule_Condition,
/** 4202 */
Email,
/** 4023 */
Email_Hash,
/** 4299 */
Email_Search,
/** 9605 */
Email_Server_Profile,
/** 9997 */
Email_Signature,
/** 2010 */
Email_Template,
/** 9800 */
Entity,
/** 430 */
Entity_Analytics_Config,
/** 432 */
Entity_Image_Configuration,
/** 9810 */
Entity_Key,
/** 4600 */
Entity_Map,
/** 9811 */
Entity_Relationship,
/** 380 */
Environment_Variable_Definition,
/** 381 */
Environment_Variable_Value,
/** 4120 */
Exchange_Sync_Id_Mapping,
/** 4711 */
Expander_Event,
/** 955 */
Expired_Process,
/** 10010 */
ExportSolutionUpload,
/** 3008 */
External_Party,
/** 9987 */
External_Party_Item,
/** 4204 */
Fax,
/** 10165 */
FeatureControlSetting,
/** 9958 */
Feedback,
/** 1201 */
Field_Permission,
/** 1200 */
Field_Security_Profile,
/** 44 */
Field_Sharing,
/** 55 */
FileAttachment,
/** 30 */
Filter_Template,
/** 2004 */
Fixed_Monthly_Fiscal_Calendar,
/** 10033 */
Flow_Machine,
/** 10034 */
Flow_Machine_Group,
/** 4720 */
Flow_Session,
/** 8003 */
Follow,
/** 54 */
Global_Search_Configuration,
/** 9600 */
Goal,
/** 9603 */
Goal_Metric,
/** 10116 */
Help_Page,
/** 8840 */
Hierarchy_Rule,
/** 9919 */
Hierarchy_Security_Configuration,
/** 9996 */
HolidayWrapper,
/** 431 */
Image_Attribute_Configuration,
/** 1007 */
Image_Descriptor,
/** 4413 */
Import_Data,
/** 4428 */
Import_Entity_Mapping,
/** 9107 */
Import_Job,
/** 4423 */
Import_Log,
/** 4412 */
Import_Source_File,
/** 126 */
Indexed_Article,
/** 3000 */
Integration_Status,
/** 4011 */
Inter_Process_Lock,
/** 9986 */
Interaction_for_Email,
/** 1003 */
Internal_Address,
/** 10067 */
Internal_Catalog_Assignment,
/** 7107 */
Invalid_Dependency,
/** 4705 */
ISV_Config,
/** 10063 */
KeyVaultReference,
/** 9953 */
Knowledge_Article,
/** 9960 */
Knowledge_Article_Category,
/** 10055 */
Knowledge_Article_Image,
/** 10058 */
Knowledge_article_language_setting,
/** 10060 */
Knowledge_Article_Template,
/** 9955 */
Knowledge_Article_Views,
/** 9930 */
Knowledge_Base_Record,
/** 10052 */
Knowledge_Federated_Article,
/** 10053 */
Knowledge_FederatedArticle_Incident,
/** 10056 */
Knowledge_Interaction_Insight,
/** 10059 */
Knowledge_personalization,
/** 10062 */
Knowledge_search_filter,
/** 10057 */
Knowledge_Search_Insight,
/** 9947 */
Knowledge_Search_Model,
/** 10061 */
Knowledge_search_personal_filter_config,
/** 9957 */
Language,
/** 9875 */
Language_Provisioning_State,
/** 4207 */
Letter,
/** 2027 */
License,
/** 8006 */
Like,
/** 4418 */
List_Value_Mapping,
/** 9201 */
LocalConfigStore,
/** 4419 */
Lookup_Mapping,
/** 9106 */
Mail_Merge_Template,
/** 9606 */
Mailbox,
/** 9608 */
Mailbox_Auto_Tracking_Folder,
/** 9607 */
Mailbox_Statistics,
/** 9609 */
Mailbox_Tracking_Category,
/** 9812 */
Managed_Property,
/** 10064 */
ManagedIdentity,
/** 4231 */
Metadata_Difference,
/** 9866 */
Mobile_Offline_Profile,
/** 9867 */
Mobile_Offline_Profile_Item,
/** 9868 */
Mobile_Offline_Profile_Item_Association,
/** 9006 */
Model_driven_App,
/** 10026 */
Model_Driven_App_Component_Node,
/** 10025 */
Model_Driven_App_Component_Nodes_Edge,
/** 10024 */
Model_Driven_App_Element,
/** 10027 */
Model_Driven_App_Setting,
/** 10028 */
Model_Driven_App_User_Setting,
/** 2003 */
Monthly_Fiscal_Calendar,
/** 9912 */
Multi_Select_Option_Value,
/** 9910 */
MultiEntitySearch,
/** 9900 */
Navigation_Setting,
/** 950 */
New_Process,
/** 10077 */
NonRelational_Data_Source,
/** 5 */
Note,
/** 10075 */
Notification_10075,
/** 4110 */
Notification_4110,
/** 10032 */
OData_v4_Data_Source,
/** 4490 */
Office_Document,
/** 9950 */
Office_Graph_Document,
/** 9870 */
Offline_Command_Definition,
/** 9809 */
OptionSet,
/** 1019 */
Organization,
/** 9699 */
Organization_Insights_Metric,
/** 9690 */
Organization_Insights_Notification,
/** 10029 */
Organization_Setting,
/** 4708 */
Organization_Statistic,
/** 1021 */
Organization_UI,
/** 10073 */
OrganizationDataSyncSubscription,
/** 10074 */
OrganizationDataSyncSubscriptionEntity,
/** 7 */
Owner,
/** 4420 */
Owner_Mapping,
/** 10007 */
Package,
/** 1095 */
Partner_Application,
/** 10048 */
PDF_Setting,
/** 9941 */
Personal_Document_Template,
/** 4210 */
Phone_Call,
/** 4605 */
Plug_in_Assembly,
/** 4619 */
Plug_in_Trace_Log,
/** 4602 */
Plug_in_Type,
/** 4603 */
Plug_in_Type_Statistic,
/** 10166 */
Plugin_Package,
/** 10091 */
PM_Inferred_Task,
/** 10092 */
PM_Recording,
/** 50 */
Position,
/** 8000 */
Post,
/** 8002 */
Post_Regarding,
/** 8001 */
Post_Role,
/** 1404 */
Principal_Sync_Attribute_Map,
/** 1023 */
Privilege,
/** 31 */
Privilege_Object_Type_Code,
/** 4703 */
Process,
/** 9650 */
Process_Configuration,
/** 4704 */
Process_Dependency,
/** 4706 */
Process_Log,
/** 4710 */
Process_Session,
/** 4724 */
Process_Stage,
/** 4712 */
Process_Trigger,
/** 10035 */
ProcessStageParameter,
/** 10013 */
ProvisionLanguageForUser,
/** 7101 */
Publisher,
/** 7102 */
Publisher_Address,
/** 2002 */
Quarterly_Fiscal_Calendar,
/** 2020 */
Queue,
/** 2029 */
Queue_Item,
/** 2023 */
QueueItemCount,
/** 2024 */
QueueMemberCount,
/** 9300 */
Record_Creation_and_Update_Rule,
/** 9301 */
Record_Creation_and_Update_Rule_Item,
/** 4250 */
Recurrence_Rule,
/** 4251 */
Recurring_Appointment,
/** 9814 */
Relationship_Attribute,
/** 9813 */
Relationship_Entity,
/** 4500 */
Relationship_Role,
/** 4501 */
Relationship_Role_Map,
/** 1140 */
Replication_Backlog,
/** 9100 */
Report,
/** 9104 */
Report_Link,
/** 9102 */
Report_Related_Category,
/** 9101 */
Report_Related_Entity,
/** 9103 */
Report_Visibility,
/** 90001 */
RevokeInheritedAccessRecordsTracker,
/** 4579 */
Ribbon_Client_Metadata,
/** 1116 */
Ribbon_Command,
/** 1115 */
Ribbon_Context_Group,
/** 1130 */
Ribbon_Difference,
/** 9880 */
Ribbon_Metadata_To_Process,
/** 1117 */
Ribbon_Rule,
/** 1113 */
Ribbon_Tab_To_Command_Mapping,
/** 10076 */
Rich_Text_Attachment,
/** 1037 */
Role_Template,
/** 9604 */
Rollup_Field,
/** 9511 */
Rollup_Job,
/** 9510 */
Rollup_Properties,
/** 9602 */
Rollup_Query,
/** 8181 */
Routing_Rule_Set,
/** 8199 */
Rule_Item,
/** 7200 */
RuntimeDependency,
/** 1309 */
Saved_Organization_Insights_Configuration,
/** 4230 */
Saved_View,
/** 4606 */
Sdk_Message,
/** 4607 */
Sdk_Message_Filter,
/** 4613 */
Sdk_Message_Pair,
/** 4608 */
Sdk_Message_Processing_Step,
/** 4615 */
Sdk_Message_Processing_Step_Image,
/** 4616 */
Sdk_Message_Processing_Step_Secure_Configuration,
/** 4609 */
Sdk_Message_Request,
/** 4614 */
Sdk_Message_Request_Field,
/** 4610 */
Sdk_Message_Response,
/** 4611 */
Sdk_Message_Response_Field,
/** 10054 */
Search_provider,
/** 10078 */
Search_Telemetry,
/** 1036 */
Security_Role,
/** 2001 */
Semiannual_Fiscal_Calendar,
/** 10050 */
Service_Configuration,
/** 4618 */
Service_Endpoint,
/** 101 */
Service_Plan,
/** 10170 */
Service_Plan_Mapping,
/** 10030 */
Setting_Definition,
/** 9509 */
SharePoint_Data,
/** 9507 */
Sharepoint_Document,
/** 9502 */
SharePoint_Site,
/** 9951 */
Similarity_Rule,
/** 4709 */
Site_Map,
/** 9750 */
SLA,
/** 9751 */
SLA_Item,
/** 10051 */
SLA_KPI,
/** 9752 */
SLA_KPI_Instance,
/** 4216 */
Social_Activity,
/** 99 */
Social_Profile,
/** 1300 */
SocialInsightsConfiguration,
/** 7100 */
Solution,
/** 7103 */
Solution_Component,
/** 10000 */
Solution_Component_Attribute_Configuration,
/** 10169 */
Solution_Component_Batch_Configuration,
/** 10001 */
Solution_Component_Configuration,
/** 10012 */
Solution_Component_Data_Source,
/** 7104 */
Solution_Component_Definition,
/** 10002 */
Solution_Component_Relationship_Configuration,
/** 10011 */
Solution_Component_Summary,
/** 10003 */
Solution_History,
/** 10004 */
Solution_History_Data_Source,
/** 9890 */
SolutionHistoryData,
/** 10009 */
StageSolutionUpload,
/** 1075 */
Status_Map,
/** 1043 */
String_Map,
/** 129 */
Subject,
/** 29 */
Subscription,
/** 1072 */
Subscription_Clients,
/** 37 */
Subscription_Manually_Tracked_Object,
/** 45 */
Subscription_Statistic_Offline,
/** 46 */
Subscription_Statistic_Outlook,
/** 47 */
Subscription_Sync_Entry_Offline,
/** 48 */
Subscription_Sync_Entry_Outlook,
/** 33 */
Subscription_Synchronization_Information,
/** 1190 */
SuggestionCardTemplate,
/** 1401 */
Sync_Attribute_Mapping,
/** 1400 */
Sync_Attribute_Mapping_Profile,
/** 9869 */
Sync_Error,
/** 7000 */
System_Application_Metadata,
/** 1111 */
System_Chart,
/** 1030 */
System_Form,
/** 4700 */
System_Job,
/** 51 */
System_User_Manager_Map,
/** 14 */
System_User_Principal,
/** 42 */
SystemUser_BusinessUnit_Entity_Map,
/** 60 */
SystemUserAuthorizationChangeTracker,
/** 4212 */
Task,
/** 9 */
Team,
/** 1203 */
Team_Profiles,
/** 1403 */
Team_Sync_Attribute_Mapping_Profiles,
/** 92 */
Team_template,
/** 10071 */
TeamMobileOfflineProfileMembership,
/** 2013 */
Territory,
/** 9945 */
Text_Analytics_Entity_Mapping,
/** 2015 */
Theme,
/** 9932 */
Time_Stamp_Date_Mapping,
/** 4810 */
Time_Zone_Definition,
/** 4812 */
Time_Zone_Localized_Name,
/** 4811 */
Time_Zone_Rule,
/** 10117 */
Tour,
/** 8050 */
Trace,
/** 8051 */
Trace_Association,
/** 8052 */
Trace_Regarding,
/** 35 */
Tracking_information_for_deleted_entities,
/** 4426 */
Transformation_Mapping,
/** 4427 */
Transformation_Parameter_Mapping,
/** 951 */
Translation_Process,
/** 2012 */
Unresolved_Address,
/** 4220 */
UntrackedEmail,
/** 8 */
User,
/** 7001 */
User_Application_Metadata,
/** 1112 */
User_Chart,
/** 1031 */
User_Dashboard,
/** 2501 */
User_Entity_Instance_Data,
/** 2500 */
User_Entity_UI_Settings,
/** 1086 */
User_Fiscal_Calendar,
/** 2016 */
User_Mapping,
/** 52 */
User_Search_Facet,
/** 150 */
User_Settings,
/** 10072 */
UserMobileOfflineProfileMembership,
/** 1039 */
View,
/** 78 */
Virtual_Entity_Data_Provider,
/** 85 */
Virtual_Entity_Data_Source,
/** 10118 */
Virtual_Entity_Metadata,
/** 9333 */
Web_Resource,
/** 4800 */
Web_Wizard,
/** 4803 */
Web_Wizard_Access_Privilege,
/** 4802 */
Wizard_Page,
/** 10036 */
Workflow_Binary,
/** 4702 */
Workflow_Wait_Subscription
}
enum StateCode {
/** 1 */
Active,
/** 0 */
Inactive
}
enum StatusCode {
/** 2 */
Published,
/** 1 */
Publishing,
/** 0 */
Unpublished
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { SoftwareInventories } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { SecurityCenter } from "../securityCenter";
import {
Software,
SoftwareInventoriesListByExtendedResourceNextOptionalParams,
SoftwareInventoriesListByExtendedResourceOptionalParams,
SoftwareInventoriesListBySubscriptionNextOptionalParams,
SoftwareInventoriesListBySubscriptionOptionalParams,
SoftwareInventoriesListByExtendedResourceResponse,
SoftwareInventoriesListBySubscriptionResponse,
SoftwareInventoriesGetOptionalParams,
SoftwareInventoriesGetResponse,
SoftwareInventoriesListByExtendedResourceNextResponse,
SoftwareInventoriesListBySubscriptionNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing SoftwareInventories operations. */
export class SoftwareInventoriesImpl implements SoftwareInventories {
private readonly client: SecurityCenter;
/**
* Initialize a new instance of the class SoftwareInventories class.
* @param client Reference to the service client
*/
constructor(client: SecurityCenter) {
this.client = client;
}
/**
* Gets the software inventory of the virtual machine.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param resourceNamespace The namespace of the resource.
* @param resourceType The type of the resource.
* @param resourceName Name of the resource.
* @param options The options parameters.
*/
public listByExtendedResource(
resourceGroupName: string,
resourceNamespace: string,
resourceType: string,
resourceName: string,
options?: SoftwareInventoriesListByExtendedResourceOptionalParams
): PagedAsyncIterableIterator<Software> {
const iter = this.listByExtendedResourcePagingAll(
resourceGroupName,
resourceNamespace,
resourceType,
resourceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByExtendedResourcePagingPage(
resourceGroupName,
resourceNamespace,
resourceType,
resourceName,
options
);
}
};
}
private async *listByExtendedResourcePagingPage(
resourceGroupName: string,
resourceNamespace: string,
resourceType: string,
resourceName: string,
options?: SoftwareInventoriesListByExtendedResourceOptionalParams
): AsyncIterableIterator<Software[]> {
let result = await this._listByExtendedResource(
resourceGroupName,
resourceNamespace,
resourceType,
resourceName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByExtendedResourceNext(
resourceGroupName,
resourceNamespace,
resourceType,
resourceName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByExtendedResourcePagingAll(
resourceGroupName: string,
resourceNamespace: string,
resourceType: string,
resourceName: string,
options?: SoftwareInventoriesListByExtendedResourceOptionalParams
): AsyncIterableIterator<Software> {
for await (const page of this.listByExtendedResourcePagingPage(
resourceGroupName,
resourceNamespace,
resourceType,
resourceName,
options
)) {
yield* page;
}
}
/**
* Gets the software inventory of all virtual machines in the subscriptions.
* @param options The options parameters.
*/
public listBySubscription(
options?: SoftwareInventoriesListBySubscriptionOptionalParams
): PagedAsyncIterableIterator<Software> {
const iter = this.listBySubscriptionPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listBySubscriptionPagingPage(options);
}
};
}
private async *listBySubscriptionPagingPage(
options?: SoftwareInventoriesListBySubscriptionOptionalParams
): AsyncIterableIterator<Software[]> {
let result = await this._listBySubscription(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listBySubscriptionNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listBySubscriptionPagingAll(
options?: SoftwareInventoriesListBySubscriptionOptionalParams
): AsyncIterableIterator<Software> {
for await (const page of this.listBySubscriptionPagingPage(options)) {
yield* page;
}
}
/**
* Gets the software inventory of the virtual machine.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param resourceNamespace The namespace of the resource.
* @param resourceType The type of the resource.
* @param resourceName Name of the resource.
* @param options The options parameters.
*/
private _listByExtendedResource(
resourceGroupName: string,
resourceNamespace: string,
resourceType: string,
resourceName: string,
options?: SoftwareInventoriesListByExtendedResourceOptionalParams
): Promise<SoftwareInventoriesListByExtendedResourceResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceNamespace,
resourceType,
resourceName,
options
},
listByExtendedResourceOperationSpec
);
}
/**
* Gets the software inventory of all virtual machines in the subscriptions.
* @param options The options parameters.
*/
private _listBySubscription(
options?: SoftwareInventoriesListBySubscriptionOptionalParams
): Promise<SoftwareInventoriesListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{ options },
listBySubscriptionOperationSpec
);
}
/**
* Gets a single software data of the virtual machine.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param resourceNamespace The namespace of the resource.
* @param resourceType The type of the resource.
* @param resourceName Name of the resource.
* @param softwareName Name of the installed software.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
resourceNamespace: string,
resourceType: string,
resourceName: string,
softwareName: string,
options?: SoftwareInventoriesGetOptionalParams
): Promise<SoftwareInventoriesGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceNamespace,
resourceType,
resourceName,
softwareName,
options
},
getOperationSpec
);
}
/**
* ListByExtendedResourceNext
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param resourceNamespace The namespace of the resource.
* @param resourceType The type of the resource.
* @param resourceName Name of the resource.
* @param nextLink The nextLink from the previous successful call to the ListByExtendedResource method.
* @param options The options parameters.
*/
private _listByExtendedResourceNext(
resourceGroupName: string,
resourceNamespace: string,
resourceType: string,
resourceName: string,
nextLink: string,
options?: SoftwareInventoriesListByExtendedResourceNextOptionalParams
): Promise<SoftwareInventoriesListByExtendedResourceNextResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceNamespace,
resourceType,
resourceName,
nextLink,
options
},
listByExtendedResourceNextOperationSpec
);
}
/**
* ListBySubscriptionNext
* @param nextLink The nextLink from the previous successful call to the ListBySubscription method.
* @param options The options parameters.
*/
private _listBySubscriptionNext(
nextLink: string,
options?: SoftwareInventoriesListBySubscriptionNextOptionalParams
): Promise<SoftwareInventoriesListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listBySubscriptionNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByExtendedResourceOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Security/softwareInventories",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SoftwaresList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion16],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceNamespace,
Parameters.resourceType,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Security/softwareInventories",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SoftwaresList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion16],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Security/softwareInventories/{softwareName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.Software
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion16],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceNamespace,
Parameters.resourceType,
Parameters.resourceName,
Parameters.softwareName
],
headerParameters: [Parameters.accept],
serializer
};
const listByExtendedResourceNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SoftwaresList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion16],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.nextLink,
Parameters.resourceNamespace,
Parameters.resourceType,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SoftwaresList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion16],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as SDK from '../../core/sdk/sdk.js';
import * as ObjectUI from '../../ui/legacy/components/object_ui/object_ui.js';
// eslint-disable-next-line rulesdir/es_modules_import
import objectValueStyles from '../../ui/legacy/components/object_ui/objectValue.css.js';
import type * as CodeMirror from '../../third_party/codemirror.next/codemirror.next.js';
import type * as TextEditor from '../../ui/components/text_editor/text_editor.js';
import * as UI from '../../ui/legacy/legacy.js';
import consolePinPaneStyles from './consolePinPane.css.js';
const UIStrings = {
/**
*@description A context menu item in the Console Pin Pane of the Console panel
*/
removeExpression: 'Remove expression',
/**
*@description A context menu item in the Console Pin Pane of the Console panel
*/
removeAllExpressions: 'Remove all expressions',
/**
*@description Screen reader label for delete button on a non-blank live expression
*@example {document} PH1
*/
removeExpressionS: 'Remove expression: {PH1}',
/**
*@description Screen reader label for delete button on a blank live expression
*/
removeBlankExpression: 'Remove blank expression',
/**
*@description Text in Console Pin Pane of the Console panel
*/
liveExpressionEditor: 'Live expression editor',
/**
*@description Text in Console Pin Pane of the Console panel
*/
expression: 'Expression',
/**
*@description Side effect label title in Console Pin Pane of the Console panel
*/
evaluateAllowingSideEffects: 'Evaluate, allowing side effects',
/**
*@description Text of a DOM element in Console Pin Pane of the Console panel
*/
notAvailable: 'not available',
};
const str_ = i18n.i18n.registerUIStrings('panels/console/ConsolePinPane.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
const elementToConsolePin = new WeakMap<Element, ConsolePin>();
export class ConsolePinPane extends UI.ThrottledWidget.ThrottledWidget {
private pins: Set<ConsolePin>;
private readonly pinsSetting: Common.Settings.Setting<string[]>;
constructor(private readonly liveExpressionButton: UI.Toolbar.ToolbarButton, private readonly focusOut: () => void) {
super(true, 250);
this.contentElement.classList.add('console-pins', 'monospace');
this.contentElement.addEventListener('contextmenu', this.contextMenuEventFired.bind(this), false);
this.pins = new Set();
this.pinsSetting = Common.Settings.Settings.instance().createLocalSetting('consolePins', []);
for (const expression of this.pinsSetting.get()) {
this.addPin(expression);
}
}
wasShown(): void {
super.wasShown();
this.registerCSSFiles([consolePinPaneStyles, objectValueStyles]);
}
willHide(): void {
for (const pin of this.pins) {
pin.setHovered(false);
}
}
savePins(): void {
const toSave = Array.from(this.pins).map(pin => pin.expression());
this.pinsSetting.set(toSave);
}
private contextMenuEventFired(event: Event): void {
const contextMenu = new UI.ContextMenu.ContextMenu(event);
const target = UI.UIUtils.deepElementFromEvent(event);
if (target) {
const targetPinElement = target.enclosingNodeOrSelfWithClass('console-pin');
if (targetPinElement) {
const targetPin = elementToConsolePin.get(targetPinElement);
if (targetPin) {
contextMenu.editSection().appendItem(
i18nString(UIStrings.removeExpression), this.removePin.bind(this, targetPin));
targetPin.appendToContextMenu(contextMenu);
}
}
}
contextMenu.editSection().appendItem(i18nString(UIStrings.removeAllExpressions), this.removeAllPins.bind(this));
contextMenu.show();
}
private removeAllPins(): void {
for (const pin of this.pins) {
this.removePin(pin);
}
}
removePin(pin: ConsolePin): void {
pin.element().remove();
const newFocusedPin = this.focusedPinAfterDeletion(pin);
this.pins.delete(pin);
this.savePins();
if (newFocusedPin) {
newFocusedPin.focus();
} else {
this.liveExpressionButton.focus();
}
}
addPin(expression: string, userGesture?: boolean): void {
const pin = new ConsolePin(expression, this, this.focusOut);
this.contentElement.appendChild(pin.element());
this.pins.add(pin);
this.savePins();
if (userGesture) {
pin.focus();
}
this.update();
}
private focusedPinAfterDeletion(deletedPin: ConsolePin): ConsolePin|null {
const pinArray = Array.from(this.pins);
for (let i = 0; i < pinArray.length; i++) {
if (pinArray[i] === deletedPin) {
if (pinArray.length === 1) {
return null;
}
if (i === pinArray.length - 1) {
return pinArray[i - 1];
}
return pinArray[i + 1];
}
}
return null;
}
async doUpdate(): Promise<void> {
if (!this.pins.size || !this.isShowing()) {
return;
}
if (this.isShowing()) {
this.update();
}
const updatePromises = Array.from(this.pins, pin => pin.updatePreview());
await Promise.all(updatePromises);
this.updatedForTest();
}
private updatedForTest(): void {
}
}
let consolePinNumber = 0;
export class ConsolePin {
private readonly pinElement: Element;
private readonly pinPreview: HTMLElement;
private lastResult: SDK.RuntimeModel.EvaluationResult|null;
private lastExecutionContext: SDK.RuntimeModel.ExecutionContext|null;
private editor: TextEditor.TextEditor.TextEditor|null;
private committedExpression: string;
private hovered: boolean;
private lastNode: SDK.RemoteObject.RemoteObject|null;
private readonly editorPromise: Promise<TextEditor.TextEditor.TextEditor>;
private consolePinNumber: number;
private deletePinIcon: UI.UIUtils.DevToolsCloseButton;
constructor(expression: string, private readonly pinPane: ConsolePinPane, private readonly focusOut: () => void) {
this.consolePinNumber = ++consolePinNumber;
this.deletePinIcon = document.createElement('div', {is: 'dt-close-button'}) as UI.UIUtils.DevToolsCloseButton;
this.deletePinIcon.gray = true;
this.deletePinIcon.classList.add('close-button');
this.deletePinIcon.setTabbable(true);
if (expression.length) {
this.deletePinIcon.setAccessibleName(i18nString(UIStrings.removeExpressionS, {PH1: expression}));
} else {
this.deletePinIcon.setAccessibleName(i18nString(UIStrings.removeBlankExpression));
}
self.onInvokeElement(this.deletePinIcon, event => {
pinPane.removePin(this);
event.consume(true);
});
const fragment = UI.Fragment.Fragment.build`
<div class='console-pin'>
${this.deletePinIcon}
<div class='console-pin-name' $='name'></div>
<div class='console-pin-preview' $='preview'></div>
</div>`;
this.pinElement = fragment.element();
this.pinPreview = (fragment.$('preview') as HTMLElement);
const nameElement = (fragment.$('name') as HTMLElement);
UI.Tooltip.Tooltip.install(nameElement, expression);
elementToConsolePin.set(this.pinElement, this);
this.lastResult = null;
this.lastExecutionContext = null;
this.editor = null;
this.committedExpression = expression;
this.hovered = false;
this.lastNode = null;
this.pinPreview.addEventListener('mouseenter', this.setHovered.bind(this, true), false);
this.pinPreview.addEventListener('mouseleave', this.setHovered.bind(this, false), false);
this.pinPreview.addEventListener('click', (event: Event) => {
if (this.lastNode) {
Common.Revealer.reveal(this.lastNode);
event.consume();
}
}, false);
// Prevent Esc from toggling the drawer
nameElement.addEventListener('keydown', event => {
if (event.key === 'Escape') {
event.consume();
}
});
this.editorPromise = this.createEditor(expression, nameElement);
}
async createEditor(expression: string, parent: HTMLElement): Promise<TextEditor.TextEditor.TextEditor> {
const CM = await import('../../third_party/codemirror.next/codemirror.next.js');
const TE = await import('../../ui/components/text_editor/text_editor.js');
this.editor = new TE.TextEditor.TextEditor(CM.EditorState.create({
doc: expression,
extensions: [
CM.EditorView.contentAttributes.of({'aria-label': i18nString(UIStrings.liveExpressionEditor)}),
CM.EditorView.lineWrapping,
(await CM.javascript()).javascriptLanguage,
await TE.JavaScript.completion(),
TE.Config.showCompletionHint,
CM.placeholder(i18nString(UIStrings.expression)),
CM.keymap.of([
{
key: 'Escape',
run: (view: CodeMirror.EditorView): boolean => {
view.dispatch({changes: {from: 0, to: view.state.doc.length, insert: this.committedExpression}});
this.focusOut();
return true;
},
},
{
key: 'Mod-Enter',
run: (): boolean => {
this.focusOut();
return true;
},
},
]),
CM.EditorView.domEventHandlers({blur: (_e, view) => this.onBlur(view)}),
TE.Config.baseConfiguration(expression),
],
}));
parent.appendChild(this.editor);
return this.editor;
}
onBlur(editor: CodeMirror.EditorView): void {
const text = editor.state.doc.toString();
const trimmedText = text.trim();
this.committedExpression = trimmedText;
this.pinPane.savePins();
if (this.committedExpression.length) {
this.deletePinIcon.setAccessibleName(i18nString(UIStrings.removeExpressionS, {PH1: this.committedExpression}));
} else {
this.deletePinIcon.setAccessibleName(i18nString(UIStrings.removeBlankExpression));
}
editor.dispatch({
selection: {anchor: trimmedText.length},
changes: trimmedText !== text ? {from: 0, to: text.length, insert: trimmedText} : undefined,
});
}
setHovered(hovered: boolean): void {
if (this.hovered === hovered) {
return;
}
this.hovered = hovered;
if (!hovered && this.lastNode) {
SDK.OverlayModel.OverlayModel.hideDOMNodeHighlight();
}
}
expression(): string {
return this.committedExpression;
}
element(): Element {
return this.pinElement;
}
async focus(): Promise<void> {
const editor = this.editor || await this.editorPromise;
editor.editor.focus();
editor.editor.dispatch({selection: {anchor: editor.state.doc.length}});
}
appendToContextMenu(contextMenu: UI.ContextMenu.ContextMenu): void {
if (this.lastResult && !('error' in this.lastResult) && this.lastResult.object) {
contextMenu.appendApplicableItems(this.lastResult.object);
// Prevent result from being released manually. It will release along with 'console' group.
this.lastResult = null;
}
}
async updatePreview(): Promise<void> {
if (!this.editor) {
return;
}
const TE = await import('../../ui/components/text_editor/text_editor.js');
const text = TE.Config.contentIncludingHint(this.editor.editor);
const isEditing = this.pinElement.hasFocus();
const throwOnSideEffect = isEditing && text !== this.committedExpression;
const timeout = throwOnSideEffect ? 250 : undefined;
const executionContext = UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext);
const preprocessedExpression = ObjectUI.JavaScriptREPL.JavaScriptREPL.preprocessExpression(text);
const {preview, result} = await ObjectUI.JavaScriptREPL.JavaScriptREPL.evaluateAndBuildPreview(
`${preprocessedExpression}\n//# sourceURL=watch-expression-${this.consolePinNumber}.devtools`,
throwOnSideEffect, false /* replMode */, timeout, !isEditing /* allowErrors */, 'console');
if (this.lastResult && this.lastExecutionContext) {
this.lastExecutionContext.runtimeModel.releaseEvaluationResult(this.lastResult);
}
this.lastResult = result || null;
this.lastExecutionContext = executionContext || null;
const previewText = preview.deepTextContent();
if (!previewText || previewText !== this.pinPreview.deepTextContent()) {
this.pinPreview.removeChildren();
if (result && SDK.RuntimeModel.RuntimeModel.isSideEffectFailure(result)) {
const sideEffectLabel =
(this.pinPreview.createChild('span', 'object-value-calculate-value-button') as HTMLElement);
sideEffectLabel.textContent = '(…)';
UI.Tooltip.Tooltip.install(sideEffectLabel, i18nString(UIStrings.evaluateAllowingSideEffects));
} else if (previewText) {
this.pinPreview.appendChild(preview);
} else if (!isEditing) {
UI.UIUtils.createTextChild(this.pinPreview, i18nString(UIStrings.notAvailable));
}
UI.Tooltip.Tooltip.install(this.pinPreview, previewText);
}
let node: SDK.RemoteObject.RemoteObject|null = null;
if (result && !('error' in result) && result.object.type === 'object' && result.object.subtype === 'node') {
node = result.object;
}
if (this.hovered) {
if (node) {
SDK.OverlayModel.OverlayModel.highlightObjectAsDOMNode(node);
} else if (this.lastNode) {
SDK.OverlayModel.OverlayModel.hideDOMNodeHighlight();
}
}
this.lastNode = node || null;
const isError = result && !('error' in result) && result.exceptionDetails &&
!SDK.RuntimeModel.RuntimeModel.isSideEffectFailure(result);
this.pinElement.classList.toggle('error-level', Boolean(isError));
}
} | the_stack |
import { format } from 'fecha';
interface PlayingInfo {
src: 'YTMusic' | 'SoundCloud' | 'Spotify' | 'YouTube' | 'Jamendo';
name: string;
artists: string;
album?: string;
year?: string;
url?: string;
albumCoverImage: string;
updatedAt: Date;
liked?: boolean;
}
const enable = () => {
chrome.storage.local.set({ enabled: true }, () => {
chrome.alarms.create('refresh', { periodInMinutes: 1 });
report();
chrome.browserAction.setIcon({ path: '/assets/24.png' });
});
};
const disable = () => {
chrome.storage.local.set({ enabled: false }, () => {
chrome.alarms.clear('refresh');
chrome.browserAction.setIcon({ path: '/assets/24-grayscale.png' });
});
}
chrome.alarms.onAlarm.addListener(a => {
if (a.name !== 'refresh') return;
report();
});
chrome.browserAction.onClicked.addListener(tab => {
chrome.storage.local.get(['enabled'], items => {
if (items.enabled === true) {
disable();
} else if (items.enabled === false || items.enabled === undefined) {
enable();
}
});
});
chrome.runtime.onMessage.addListener((message, sender) => {
if (message.data === 'manualReport') {
report();
}
if (message.data === 'enabled') {
enable();
}
if (message.data === 'disabled') {
disable();
}
});
chrome.storage.local.get(['enabled'], items => {
if (items.enabled === true) {
enable();
} else {
disable();
}
});
const report = () => {
chrome.tabs.query({ audible: true }, tabs => {
var updated = false;
const tryupdate = (info: PlayingInfo) => {
if (updated) {
return;
}
chrome.storage.local.get(['last'], res => {
const last = res.last as PlayingInfo;
if (last !== undefined) {
if (last.src === info.src && last.name === info.name && last.artists === info.artists) {
return;
}
}
update(info).then(succeed => {
if (succeed) {
chrome.storage.local.set({ last: info });
updated = true;
}
});
});
}
tabs.forEach(t => {
if (t.audible && t.url.startsWith('https://soundcloud.com/')) {
chrome.tabs.executeScript(t.id, {
code: `[
document.querySelector('.playControls__soundBadge .playbackSoundBadge__titleLink').title,
document.querySelector('.playControls__soundBadge .playbackSoundBadge__lightLink').title,
document.querySelector('.playControls__soundBadge .playbackSoundBadge__titleLink').href,
document.querySelector('.playControls__soundBadge span.sc-artwork').style.backgroundImage,
document.querySelector('.playbackSoundBadge__actions .sc-button-like').getAttribute('aria-label'),
]`
}, results => {
const res = results[0] as string[];
const [name, artists, url, albumCoverImg, likeLabel] = res;
const albumCoverImgSmallSrc = new RegExp('url\\(\\"(.*)\\"\\)').exec(albumCoverImg)[1];
const albumCoverImgBigSrc = (albumCoverImgSmallSrc || '').replace('50x50', '500x500');
const liked = likeLabel === 'Unlike';
tryupdate({
src: 'SoundCloud',
name,
artists,
url,
albumCoverImage: albumCoverImgBigSrc,
updatedAt: new Date(),
liked,
});
});
}
if (t.audible && t.url.startsWith('https://music.youtube.com/')) {
chrome.tabs.executeScript(t.id, {
code: `[
document.querySelector('yt-formatted-string.ytmusic-player-bar.title').innerText,
document.querySelector('yt-formatted-string.ytmusic-player-bar.byline').title,
document.querySelector('img.ytmusic-player-bar').src,
document.querySelector('.ytp-title-link').href,
document.querySelector('tp-yt-paper-icon-button.like').getAttribute('aria-pressed'),
]`
}, results => {
const res = results[0] as string[];
const name = res[0];
const infos = res[1].split(" • ");
const [artists, album, year] = infos;
const albumCoverImgSrc = res[2];
const albumCoverImgOriginal = new RegExp('(.*)=.*').exec(albumCoverImgSrc)[1];
const ytMediaUrl = res[3];
const url = `https://music.youtube.com/watch?v=${new RegExp('.*=(.*)').exec(ytMediaUrl)[1]}`;
const liked = res[4] === 'true';
tryupdate({
src: 'YTMusic',
name,
artists,
album,
year,
url,
albumCoverImage: albumCoverImgOriginal,
updatedAt: new Date(),
liked: liked,
});
});
}
if (t.audible && t.url.startsWith('https://open.spotify.com/')) {
chrome.tabs.executeScript(t.id, {
/*
* Spotify web player doesn't give album and year information
* TrackName
* Artists
* Cover Image URL (currently there are several images in different resolutions, workaround needed)
* Track Album Link
*/
code: `[
document.querySelector('a[data-testid="nowplaying-track-link"]').innerText,
[...document.querySelectorAll('div[class="Root__top-container"] a[data-testid="nowplaying-artist"]')].map(x => x.innerText),
document.querySelector('div[class*="cover-art shadow"] img').src,
document.querySelector('a[data-testid="nowplaying-track-link"]').href
]`
}, results => {
const name = results[0][0];
const artists = (results[0][1] as string[]).join(' ');
const albumCoverImage = results[0][2];
const url = results[0][3];
tryupdate({
src: 'Spotify',
name,
artists,
url,
albumCoverImage,
updatedAt: new Date(),
});
});
}
if (t.audible && t.url.startsWith('https://www.youtube.com/')) {
chrome.tabs.executeScript(t.id, {
code: `[
document.querySelector('.title.ytd-video-primary-info-renderer').innerText,
document.querySelector('ytd-video-secondary-info-renderer ytd-channel-name').innerText,
document.querySelector('ytd-video-secondary-info-renderer ytd-video-owner-renderer img').src,
document.querySelector('ytd-video-secondary-info-renderer ytd-video-owner-renderer a').href,
document.querySelector('ytd-video-primary-info-renderer yt-icon-button button')?.getAttribute('aria-pressed'),
(!!document.querySelector('ytd-video-secondary-info-renderer ytd-video-owner-renderer .badge-style-type-verified-artist')).toString(),
]`
}, results => {
const res = results[0] as string[];
const verified = res[5];
if (verified === 'true') {
const artists = res[1];
const name = res[0].replace(artists + " - ", ""); // Remove artist from music title.
const albumCoverImage = res[2];
const url = res[3];
const liked = res[4] === 'true';
tryupdate({
src: 'YouTube',
name,
artists,
url,
albumCoverImage,
updatedAt: new Date(),
liked: liked,
});
}
});
}
if (t.audible && t.url.startsWith('https://www.jamendo.com/')) {
chrome.tabs.executeScript(t.id, {
code: `[
document.getElementsByClassName('player-mini_track_information_title js-player-name')[0].innerText,
document.getElementsByClassName('player-mini_track_information_artist js-player-artistId')[0].innerText,
new URL(new URL(document.getElementsByClassName('js-full-player-cover-img')[0].src).pathname.split("/")[3] + '/' + document.getElementsByClassName('player-mini_track_information_title js-player-name')[0].innerText.replace("(", "").replace(")", ""), 'https://www.jamendo.com/track/').href,
document.getElementsByClassName('js-full-player-cover-img')[0].src,
(document.getElementsByClassName('btn-icon btn--overlay is-on')[0] != undefined).toString(),
]`
}, results => {
const res = results[0] as string[];
const name = res[0];
const artists = res[1];
const url = res[2];
const albumCoverImg = res[3].split("?")[0];
const liked = (res[4] == "true");
tryupdate({
src: 'Jamendo',
name,
artists,
url,
albumCoverImage: albumCoverImg,
updatedAt: new Date(),
liked,
});
});
}
});
});
}
const update = (info: PlayingInfo): Promise<boolean> => {
return new Promise<boolean>(resolve => {
chrome.storage.local.get(['id', 'key', 'etag', 'modified'], items => {
const id = items.id as string;
const oauth = items.key as string;
const lastEtag = items.etag as string;
const lastModified = items.modified as string;
const message = 'auto update by github-now';
const auth = `token ${oauth}`;
try {
fetch(`https://api.github.com/repos/${id}/${id}/contents/README.template.md`, {
headers: {
"Authorization": auth
},
}).then(async resp => {
const json = await resp.json();
if (resp.status !== 200) {
console.error(json.message);
return;
}
const template = decodeURIComponent(escape(atob(json.content)));
// looks like need a template engine..
const content = template
.replace(/{CURRENT_PLAYING_SOURCE}/gi, info.src)
.replace(/{CURRENT_PLAYING_NAME}/gi, info.name)
.replace(/{CURRENT_PLAYING_ARTISTS}/gi, info.artists)
.replace(/{CURRENT_PLAYING_ALBUM}/gi, info.album ?? 'Not supported')
.replace(/{CURRENT_PLAYING_RELEASED}/gi, info.year)
.replace(/{CURRENT_PLAYING_ALBUM_SRC}/gi, info.albumCoverImage)
.replace(/{CURRENT_PLAYING_URL}/gi, info.url)
.replace(/{CURRENT_PLAYING_LAST_UPDATED}/gi, format(info.updatedAt, 'MM/DD/YYYY HH:mm'));
const encoded = btoa(unescape(encodeURIComponent(content)));
const headers = !lastEtag ? {} : {
"If-Modified-Since": lastModified,
"If-None-Match": lastEtag,
};
const target = await fetch(`https://api.github.com/repos/${id}/${id}/contents/README.md`, {
headers,
});
const etag = target.headers.get("ETag");
const modified = target.headers.get("Last-Modified");
chrome.storage.local.set({ etag, modified });
if (target.status === 304) {
console.log("got cached; retry after 1 second");
setTimeout(report, 1000);
resolve(false);
return;
}
const sha = (await target.json()).sha;
try {
const postResp = await fetch(`https://api.github.com/repos/${id}/${id}/contents/README.md`, {
method: "PUT",
headers: {
"Authorization": auth
},
body: JSON.stringify({
"message": message,
"content": encoded,
"sha": sha,
"committer": {
"name": "github-now",
"email": "2+github-now@0chan.dev",
},
}),
});
if (postResp.status === 409) {
console.log("cached");
resolve(false);
return;
}
if (postResp.status !== 200) {
const postJson = await postResp.json();
console.error(postJson.message);
resolve(false);
return;
}
if (postResp.ok) {
resolve(true);
console.log("updated");
return;
}
resolve(false);
} catch (postResp) {
console.log(`Error ${postResp}`);
resolve(false);
}
});
} catch {
resolve(false);
}
});
});
} | the_stack |
import { IStorageDriver, Isanitize, Iexist} from "../../src";
import * as fs from "fs";
import ErrnoException = NodeJS.ErrnoException;
export class MockStorageDriver implements IStorageDriver {
public allKeys: string[];
private filePath: string;
constructor(filePath: string) {
this.filePath = filePath;
this.allKeys = [];
const cwd = process.cwd();
if (!fs.existsSync(`${cwd}/spec/example/db/${this.filePath}`)) {
fs.mkdirSync(`${cwd}/spec/example/db/${this.filePath}`);
}
}
/**
* using the cwd use the file path to read the file contents
* parse the file and return the item with the given key
* else reject a new error message.
*/
public getItem(key: string): Promise<any> {
return new Promise<any>((resolve, reject) => {
const cwd = process.cwd();
if (!fs.existsSync(`${cwd}/spec/example/db/${this.filePath}/${key}.db`)) {
reject(`No doc with key: ${key} found in ${cwd}/spec/example/db/${this.filePath}`);
} else {
fs.readFile(`${cwd}/spec/example/db/${this.filePath}/${key}.db`, "utf8", (err: ErrnoException, data: string) => {
if (err) {
reject(err);
}
let a: any;
try {
a = JSON.parse(data);
} catch (e) {
reject(e);
}
resolve(a);
});
}
});
}
/**
* using the cwd use the filepath to write to the file
* given the key send the data
* else reject a new error message.
*/
public setItem(key: string, value: any): Promise<any> {
return new Promise<any>((resolve, reject) => {
const cwd = process.cwd();
let data;
try {
data = JSON.stringify(value);
} catch (e) {
reject(e);
}
fs.writeFile(`${cwd}/spec/example/db/${this.filePath}/${key}.db`, data, (err: ErrnoException) => {
if (err) {
reject(err);
}
if (this.allKeys.indexOf(key) === -1) {
this.allKeys.push(key);
}
resolve(value);
});
});
}
/**
* This is only for testing
* using the cwd the file path read in the file convert
* the file to an object remove the proposed obj and
* rewrite the file.
*/
public removeItem(key: string): Promise<null> {
return new Promise<null>((resolve, reject) => {
const cwd = process.cwd();
if (!fs.existsSync(`${cwd}/spec/example/db/${this.filePath}/${key}.db`)) {
resolve();
} else {
fs.unlink(`${cwd}/spec/example/db/${this.filePath}/${key}.db`, (err: ErrnoException) => {
if (err) {
reject(err);
}
try {
this.allKeys = this.allKeys.filter((cur) => cur !== key);
} catch (e) {
reject(e);
}
resolve();
});
}
});
}
/**
* using the cwd, the file path and the key name create a file
* name that represents a reference to the associated database file,
* a reference to the associated object element.
* example Obj: { "name": "fred", "internal": { "age": 33 } }
* example filename: BTTindex_users_internal-age.db
* where the file path of the associated index is "users" and the key
* given in the method is the path to the element indexed "internal.age".
*/
public storeIndex(key: string, index: string): Promise<null> {
return new Promise<null>((resolve, reject) => {
const cwd = process.cwd();
const fileName = `${this.filePath}/index_${key}.db`;
if (index === '[{"key":null,"value":[null]}]' || index === '[{"key":null, "value":[]}]') {
if (fs.existsSync(`${cwd}/spec/example/db/${fileName}`)) {
fs.unlink(`${cwd}/spec/example/db/${fileName}`, (err: ErrnoException) => {
if (err) {
reject(err);
}
try {
this.allKeys = [];
} catch (e) {
reject(e);
}
resolve();
});
}
} else {
fs.writeFile(`${cwd}/spec/example/db/${fileName}`, index, (err: ErrnoException) => {
if (err) {
reject(err);
}
resolve();
});
}
});
}
/**
* using the cwd, the file path and the key name to create
* a string that will find the correct file. Then read the contents
* and return the the stores JSON
*/
public fetchIndex(key: string): Promise<any[]> {
return new Promise<any>((resolve, reject) => {
const cwd = process.cwd();
const fileName = `${this.filePath}/index_${key}.db`;
let index: any;
if (!fs.existsSync(`${cwd}/spec/example/db/${fileName}`)) {
resolve([]);
} else {
fs.readFile(`${cwd}/spec/example/db/${fileName}`, "utf8", (err: ErrnoException, data) => {
if (err) {
reject(err);
}
try {
index = JSON.parse(data);
if (index.length > 0) {
index.forEach((obj: any) => {
if (obj.value.length === 1) {
if (this.allKeys.indexOf(obj.value[0]) === -1) {
this.allKeys.push(obj.value[0]);
}
} else if (obj.value.length > 1 && !(obj.value.length < 0)) {
obj.value.forEach((id: string) => {
if (this.allKeys.indexOf(id) === -1) {
this.allKeys.push(id);
}
});
}
});
}
} catch (e) {
reject(e);
}
resolve(index);
});
}
});
}
public removeIndex(key: string): Promise<null> {
return new Promise<any>((resolve, reject) => {
const cwd = process.cwd();
const fileName = `index_${key}.db`;
if (!fs.existsSync(`${cwd}/spec/example/db/${this.filePath}/${fileName}`)) {
resolve();
} else {
fs.unlink(`${cwd}/spec/example/db/${this.filePath}/${fileName}`, (err: ErrnoException) => {
if (err) {
return reject(err);
}
resolve();
});
}
});
}
/**
* Need to have a collection scan. Go over every file in the directory
* get the Id, pull the dock out an put into iteratorCallback for each file.
*/
public iterate(iteratorCallback: (key: string, value: any, iteratorNumber?: number) => any): Promise<any> {
return new Promise<any>((resolve, reject) => {
const cwd = process.cwd();
if (!fs.existsSync(`${cwd}/spec/example/db/${this.filePath}`)) {
reject(`No directory at ${this.filePath}`);
} else {
fs.readdir(`${cwd}/spec/example/db/${this.filePath}`, (err: ErrnoException, files) => {
if (err) {
reject(err);
}
if (files.length > 0) {
files.forEach((v) => {
try {
const fileName = `${cwd}/spec/example/db/${this.filePath}/${v}`;
const data = fs.readFileSync(fileName).toString();
if (data) {
const doc = JSON.parse(data);
if (doc.hasOwnProperty("_id")) {
iteratorCallback(doc, doc._id);
}
}
} catch (e) {
reject(e);
}
});
}
resolve();
});
}
});
}
/**
* Return all the keys = _ids of all documents.
*/
public keys(): Promise<string[]> {
return new Promise<string[]>((resolve, reject) => {
if (this.allKeys.length === 0) {
const cwd = process.cwd();
fs.readdir(`${cwd}/spec/example/db/${this.filePath}`, (err: ErrnoException, files) => {
if (err) {
return reject(err);
}
if (files.length > 0) {
const ids: string[] = [];
files.forEach((v) => {
try {
const fileName = `${cwd}/spec/example/db/${this.filePath}/${v}`;
const data = fs.readFileSync(fileName).toString();
if (data) {
const doc = JSON.parse(data);
if (this.allKeys.indexOf(doc._id) === -1) {
this.allKeys.push(doc._id);
ids.push(doc._id);
}
}
} catch (e) {
reject(e);
}
});
resolve(ids);
}
resolve([]);
});
} else {
resolve(this.allKeys);
}
});
}
/**
* Check for existing file and make sure its contents are readable
* here is a simple example of just making sure it exists.
* @param {Isanitize} obj
* @param index
* @param {string} fieldName
* @returns {Promise<any>}
*/
public exists(obj: Isanitize, index: any, fieldName: string): Promise<Iexist> {
return new Promise((resolve, reject) => {
const cwd = process.cwd();
try {
if (fs.existsSync(`${cwd}/spec/example/db/${this.filePath}/${obj.value}.db`)) {
resolve({key: obj.key, value: obj.value, doesExist: true, index, fieldName});
} else {
resolve({key: obj.key, value: obj.value, doesExist: false, index, fieldName});
}
} catch (e) {
return reject(e);
}
});
}
/**
* An extra sanitizer for the storage side as an extra check.
* NOT used in tedb but is available if need be. It is recommended to
* have one available for testing and for assurance.
* @param {string[]} keys
* @returns {Promise<any>}
*/
public collectionSanitize(keys: string[]): Promise<null> {
return new Promise((resolve, reject) => {
const cwd = process.cwd();
if (!fs.existsSync(`${cwd}/spec/example/db/${this.filePath}`)) {
resolve();
} else {
fs.readdir(`${cwd}/spec/example/db/${this.filePath}`, (err: ErrnoException, files) => {
if (err) {
return reject(err);
}
const reg = new RegExp("index_");
const filteredKeys = files.reduce((acc: string[], file: string) => {
if (!reg.test(file)) {
const key = String(file).substr(0, String(file).indexOf("."));
return acc.concat(key);
} else {
return acc;
}
}, []);
filteredKeys.forEach((key) => {
if (keys.indexOf(key) === -1) {
if (fs.existsSync(`${cwd}/spec/example/db/${this.filePath}/${key}.db`)) {
this.allKeys = this.allKeys.filter((cur) => cur !== key);
fs.unlinkSync(`${cwd}/spec/example/db/${this.filePath}/${key}.db`);
}
}
});
resolve();
});
}
});
}
/**
* Clear collection
*/
public clear(): Promise<null> {
return new Promise<null>((resolve, reject) => {
const cwd = process.cwd();
if (!fs.existsSync(`${cwd}/spec/example/db/${this.filePath}`)) {
resolve();
} else {
fs.readdir(`${cwd}/spec/example/db/${this.filePath}`, (err: ErrnoException, files) => {
if (err) {
reject(err);
}
if (files.length > 0) {
files.forEach((v) => {
const fileName = `${cwd}/spec/example/db/${this.filePath}/${v}`;
try {
fs.unlinkSync(fileName);
} catch (e) {
reject(`Error removing file ${fileName}: ERROR: ${e}`);
}
});
}
fs.rmdir(`${cwd}/spec/example/db/${this.filePath}`, (error: ErrnoException) => {
if (error) {
reject(error);
}
this.allKeys = [];
resolve();
});
});
}
});
}
} | the_stack |
import * as assert from 'assert';
import {
getLineAtPosition,
extractStyleTag,
extractScriptTags,
updateRelativeImport,
getWordAt
} from '../../../src/lib/documents/utils';
import { Position } from 'vscode-languageserver';
describe('document/utils', () => {
describe('extractTag', () => {
it('supports boolean attributes', () => {
const extracted = extractStyleTag('<style test></style>');
assert.deepStrictEqual(extracted?.attributes, { test: 'test' });
});
it('supports unquoted attributes', () => {
const extracted = extractStyleTag('<style type=text/css></style>');
assert.deepStrictEqual(extracted?.attributes, {
type: 'text/css'
});
});
it('does not extract style tag inside comment', () => {
const text = `
<p>bla</p>
<!--<style>h1{ color: blue; }</style>-->
<style>p{ color: blue; }</style>
`;
assert.deepStrictEqual(extractStyleTag(text), {
content: 'p{ color: blue; }',
attributes: {},
start: 108,
end: 125,
startPos: Position.create(3, 23),
endPos: Position.create(3, 40),
container: { start: 101, end: 133 }
});
});
it('does not extract tags starting with style/script', () => {
// https://github.com/sveltejs/language-tools/issues/43
// this would previously match <styles>....</style> due to misconfigured attribute matching regex
const text = `
<styles>p{ color: blue; }</styles>
<p>bla</p>
></style>
`;
assert.deepStrictEqual(extractStyleTag(text), null);
});
it('is canse sensitive to style/script', () => {
const text = `
<Style></Style>
<Script></Script>
`;
assert.deepStrictEqual(extractStyleTag(text), null);
assert.deepStrictEqual(extractScriptTags(text), null);
});
it('only extract attribute until tag ends', () => {
const text = `
<script type="typescript">
() => abc
</script>
`;
const extracted = extractScriptTags(text);
const attributes = extracted?.script?.attributes;
assert.deepStrictEqual(attributes, { type: 'typescript' });
});
it('can extract with self-closing component before it', () => {
const extracted = extractStyleTag('<SelfClosing /><style></style>');
assert.deepStrictEqual(extracted, {
start: 22,
end: 22,
startPos: {
character: 22,
line: 0
},
endPos: {
character: 22,
line: 0
},
attributes: {},
content: '',
container: {
end: 30,
start: 15
}
});
});
it('can extract with unclosed component after it', () => {
const extracted = extractStyleTag('<style></style><C {#if asd}<p>asd</p>{/if}');
assert.deepStrictEqual(extracted, {
start: 7,
end: 7,
startPos: {
character: 7,
line: 0
},
endPos: {
character: 7,
line: 0
},
attributes: {},
content: '',
container: {
start: 0,
end: 15
}
});
});
it('extracts style tag', () => {
const text = `
<p>bla</p>
<style>p{ color: blue; }</style>
`;
assert.deepStrictEqual(extractStyleTag(text), {
content: 'p{ color: blue; }',
attributes: {},
start: 51,
end: 68,
startPos: Position.create(2, 23),
endPos: Position.create(2, 40),
container: { start: 44, end: 76 }
});
});
it('extracts style tag with attributes', () => {
const text = `
<style lang="scss">p{ color: blue; }</style>
`;
assert.deepStrictEqual(extractStyleTag(text), {
content: 'p{ color: blue; }',
attributes: { lang: 'scss' },
start: 36,
end: 53,
startPos: Position.create(1, 35),
endPos: Position.create(1, 52),
container: { start: 17, end: 61 }
});
});
it('extracts style tag with attributes and extra whitespace', () => {
const text = `
<style lang="scss" > p{ color: blue; } </style>
`;
assert.deepStrictEqual(extractStyleTag(text), {
content: ' p{ color: blue; } ',
attributes: { lang: 'scss' },
start: 44,
end: 65,
startPos: Position.create(1, 43),
endPos: Position.create(1, 64),
container: { start: 17, end: 73 }
});
});
it('extracts top level script tag only', () => {
const text = `
{#if name}
<script>
console.log('if not top level')
</script>
{/if}
<ul>
{#each cats as cat}
<script>
console.log('each not top level')
</script>
{/each}
</ul>
{#await promise}
<script>
console.log('await not top level')
</script>
{:then number}
<script>
console.log('then not top level')
</script>
{:catch error}
<script>
console.log('catch not top level')
</script>
{/await}
<p>{@html <script> console.log('html not top level')</script>}</p>
{@html mycontent}
{@debug myvar}
<!-- p{ color: blue; }</script> -->
<!--<script lang="scss">
p{ color: blue; }
</script> -->
<scrit>blah</scrit>
<script>top level script</script>
`;
assert.deepStrictEqual(extractScriptTags(text)?.script, {
content: 'top level script',
attributes: {},
start: 1243,
end: 1259,
startPos: Position.create(34, 24),
endPos: Position.create(34, 40),
container: { start: 1235, end: 1268 }
});
});
it('ignores script tag in svelte:head', () => {
// https://github.com/sveltejs/language-tools/issues/143#issuecomment-636422045
const text = `
<svelte:head>
<link rel="stylesheet" href="/lib/jodit.es2018.min.css" />
<script src="/lib/jodit.es2018.min.js">
</script>
</svelte:head>
<p>jo</p>
<script>top level script</script>
<h1>Hello, world!</h1>
<style>.bla {}</style>
`;
assert.deepStrictEqual(extractScriptTags(text)?.script, {
content: 'top level script',
attributes: {},
start: 254,
end: 270,
startPos: Position.create(7, 20),
endPos: Position.create(7, 36),
container: { start: 246, end: 279 }
});
});
it('extracts script and module script', () => {
const text = `
<script context="module">a</script>
<script>b</script>
`;
assert.deepStrictEqual(extractScriptTags(text), {
moduleScript: {
attributes: {
context: 'module'
},
container: {
end: 48,
start: 13
},
content: 'a',
start: 38,
end: 39,
startPos: {
character: 37,
line: 1
},
endPos: {
character: 38,
line: 1
}
},
script: {
attributes: {},
container: {
end: 79,
start: 61
},
content: 'b',
start: 69,
end: 70,
startPos: {
character: 20,
line: 2
},
endPos: {
character: 21,
line: 2
}
}
});
});
it('extract tag correctly with #if and < operator', () => {
const text = `
{#if value < 3}
<div>
bla
</div>
{:else if value < 4}
{/if}
<script>let value = 2</script>
<div>
{#if value < 3}
<div>
bla
</div>
{:else if value < 4}
{/if}
</div>`;
assert.deepStrictEqual(extractScriptTags(text)?.script, {
content: 'let value = 2',
attributes: {},
start: 159,
end: 172,
startPos: Position.create(7, 18),
endPos: Position.create(7, 31),
container: { start: 151, end: 181 }
});
});
});
describe('#getLineAtPosition', () => {
it('should return line at position (only one line)', () => {
assert.deepStrictEqual(getLineAtPosition(Position.create(0, 1), 'ABC'), 'ABC');
});
it('should return line at position (multiple lines)', () => {
assert.deepStrictEqual(
getLineAtPosition(Position.create(1, 1), 'ABC\nDEF\nGHI'),
'DEF\n'
);
});
});
describe('#updateRelativeImport', () => {
it('should update path of component with ending', () => {
const newPath = updateRelativeImport(
'C:/absolute/path/oldPath',
'C:/absolute/newPath',
'./Component.svelte'
);
assert.deepStrictEqual(newPath, '../path/oldPath/Component.svelte');
});
it('should update path of file without ending', () => {
const newPath = updateRelativeImport(
'C:/absolute/path/oldPath',
'C:/absolute/newPath',
'./someTsFile'
);
assert.deepStrictEqual(newPath, '../path/oldPath/someTsFile');
});
it('should update path of file going one up', () => {
const newPath = updateRelativeImport(
'C:/absolute/path/oldPath',
'C:/absolute/path',
'./someTsFile'
);
assert.deepStrictEqual(newPath, './oldPath/someTsFile');
});
});
describe('#getWordAt', () => {
it('returns word between whitespaces', () => {
assert.equal(getWordAt('qwd asd qwd', 5), 'asd');
});
it('returns word between whitespace and end of string', () => {
assert.equal(getWordAt('qwd asd', 5), 'asd');
});
it('returns word between start of string and whitespace', () => {
assert.equal(getWordAt('asd qwd', 2), 'asd');
});
it('returns word between start of string and end of string', () => {
assert.equal(getWordAt('asd', 2), 'asd');
});
it('returns word with custom delimiters', () => {
assert.equal(
getWordAt('asd on:asd-qwd="asd" ', 10, { left: /\S+$/, right: /[\s=]/ }),
'on:asd-qwd'
);
});
function testEvent(str: string, pos: number, expected: string) {
assert.equal(getWordAt(str, pos, { left: /\S+$/, right: /[^\w$:]/ }), expected);
}
it('returns event #1', () => {
testEvent('<div on:>', 8, 'on:');
});
it('returns event #2', () => {
testEvent('<div on: >', 8, 'on:');
});
it('returns empty string when only whitespace', () => {
assert.equal(getWordAt('a a', 2), '');
});
});
}); | the_stack |
import pg from "pg";
import _ from "lodash";
import { Maybe } from "tsmonad";
const textTree = require("text-treeview");
export interface NodeRecord {
id?: string;
name: string;
description?: string;
[key: string]: any;
}
export class NodeNotFoundError extends Error {}
function isNonEmptyArray(v: any): boolean {
if (!v || !_.isArray(v) || !v.length) return false;
return true;
}
const INVALID_CHAR_REGEX = /[^a-z_\d]/i;
function isValidSqlIdentifier(id: string): boolean {
if (INVALID_CHAR_REGEX.test(id)) return false;
return true;
}
export type TextTreeNode =
| string
| {
text: string;
children?: TextTreeNode[];
};
export type CompareNodeResult =
| "ancestor"
| "descendant"
| "equal"
| "unrelated";
type NodesQuery = {
name?: string;
leafNodesOnly?: boolean;
};
class NestedSetModelQueryer {
private pool: pg.Pool;
private tableName: string;
/**
* default select fields if [], all fields (i.e. `SELECT "id", "name"`) will be returned
*
* @type {string[]}
* @memberof NestedSetModelQueryer
*/
public defaultSelectFieldList: string[] = ["id", "name"];
/**
* Default field list that will be used when insert nodes into tree.
* By default, only `name` field will be saved to database
* e.g. If your tree nodes have three properties (besides `id`, `left`, `right` --- they auto generated):
* - name
* - description
* - fullName
*
* Then you should set `defaultInsertFieldList` to ["name", "description", "fullName"]
*
* @type {string[]}
* @memberof NestedSetModelQueryer
*/
public defaultInsertFieldList: string[] = ["name"];
/**
* Creates an instance of NestedSetModelQueryer.
* @param {pg.Pool} dbPool
* @param {string} tableName
* @param {string[]} [defaultSelectFieldList=null] default select fields; If null, all fields (i.e. `SELECT "id", "name"`) will be returned
* @memberof NestedSetModelQueryer
*/
constructor(
dbPool: pg.Pool,
tableName: string,
defaultSelectFieldList: string[] = null,
defaultInsertFieldList: string[] = null
) {
if (!dbPool) throw new Error("dbPool cannot be empty!");
if (!tableName) throw new Error("tableName cannot be empty!");
if (!isValidSqlIdentifier(tableName)) {
throw new Error(
`tableName: ${tableName} contains invalid characters!`
);
}
this.pool = dbPool;
this.tableName = tableName;
if (defaultSelectFieldList) {
if (!_.isArray(defaultSelectFieldList))
throw new Error("defaultSelectFieldList should be an array");
this.defaultSelectFieldList = defaultSelectFieldList;
}
if (defaultSelectFieldList) {
if (!_.isArray(defaultSelectFieldList))
throw new Error("defaultSelectFieldList should be an array");
this.defaultSelectFieldList = defaultSelectFieldList;
}
if (defaultInsertFieldList) {
if (!_.isArray(defaultInsertFieldList))
throw new Error("defaultInsertFieldList should be an array");
this.defaultInsertFieldList = defaultInsertFieldList;
}
}
private selectFields(
tableAliasOrName: string = "",
fields: string[] = null
) {
const fieldList = isNonEmptyArray(fields)
? fields
: this.defaultSelectFieldList;
if (!isNonEmptyArray(fieldList)) {
return "*";
}
if (!isValidSqlIdentifier(tableAliasOrName)) {
throw new Error(
`'tableAliasOrName' ${tableAliasOrName} contains invalid characters.`
);
}
// --- do not double quote `tableAliasOrName`
// --- or you will get missing FROM-clause entry for table error
return fieldList
.map((f) => {
if (!isValidSqlIdentifier(f)) {
throw new Error(
`Field name ${f} contains invalid characters.`
);
}
return tableAliasOrName === ""
? `"${f}"`
: `${tableAliasOrName}."${f}"`;
})
.join(", ");
}
/**
* Get nodes by name
* You hardly need this one --- only for write test case (you can get a id from name)
*
* @param {string} name
* @param {string[]} [fields=null] Selected Fields; If null, use this.defaultSelectFieldList
* @param {pg.Client} [client=null] Optional pg client; Use supplied client connection for query rather than a random connection from Pool
* @returns {Promise<NodeRecord[]>}
* @memberof NestedSetModelQueryer
*/
async getNodes(
nodesQuery: NodesQuery = {},
fields: string[] = null,
client: pg.Client = null
): Promise<NodeRecord[]> {
const getParamPlaceholder = (() => {
let currentPlaceholder = 1;
return () => currentPlaceholder++;
})();
const clauses = [
nodesQuery.name && {
sql: `"name" = $${getParamPlaceholder()}`,
values: [nodesQuery.name]
},
nodesQuery.leafNodesOnly && {
sql: `"left" = ( "right" - 1 )`
}
].filter((x) => !!x);
const whereClause =
clauses.length > 0
? `WHERE ${clauses.map(({ sql }) => sql).join(" AND ")}`
: "";
const query = `SELECT ${this.selectFields("", fields)} FROM "${
this.tableName
}" ${whereClause}`;
const result = await (client ? client : this.pool).query(
query,
_.flatMap(clauses, ({ values }) => values || [])
);
if (!result || !result.rows || !result.rows.length) return [];
return result.rows;
}
/**
*
* Get a node by its id
* @param {string} id
* @param {string[]} [fields=null] Selected Fields; If null, use this.defaultSelectFieldList
* @param {pg.Client} [client=null] Optional pg client; Use supplied client connection for query rather than a random connection from Pool
* @returns {Promise<NodeRecord>}
* @memberof NestedSetModelQueryer
*/
async getNodeById(
id: string,
fields: string[] = null,
client: pg.Client = null
): Promise<Maybe<NodeRecord>> {
const result = await (client
? client
: this.pool
).query(
`SELECT ${this.selectFields("", fields)} FROM "${
this.tableName
}" WHERE "id" = $1`,
[id]
);
if (!result || !result.rows || !result.rows.length)
return Maybe.nothing();
return Maybe.just(result.rows[0]);
}
/**
* Get the root node of the tree
* Return null if empty tree
*
* @param {string[]} [fields=null] Selected Fields; If null, use this.defaultSelectFieldList
* @param {pg.Client} [client=null] Optional pg client; Use supplied client connection for query rather than a random connection from Pool
* @returns {Promise<NodeRecord>}
* @memberof NestedSetModelQueryer
*/
async getRootNode(
fields: string[] = null,
client: pg.Client = null
): Promise<Maybe<NodeRecord>> {
const result = await (client ? client : this.pool).query(
`SELECT ${this.selectFields("", fields)} FROM "${
this.tableName
}" WHERE "left" = 1`
);
if (!result || !result.rows || !result.rows.length)
return Maybe.nothing();
return Maybe.just(result.rows[0]);
}
/**
* Get All children of a given node
* (including immediate children and children of immediate children etc.)
* If the node has no child (i.e. a leaf node), an empty array will be returned
*
* @param {string} parentNodeId
* @param {boolean} [includeMyself=false]
* @param {string[]} [fields=null] Selected Fields; If null, use this.defaultSelectFieldList
* @param {pg.Client} [client=null] Optional pg client; Use supplied client connection for query rather than a random connection from Pool
* @returns {Promise<NodeRecord[]>}
* @memberof NestedSetModelQueryer
*/
async getAllChildren(
parentNodeId: string,
includeMyself: boolean = false,
fields: string[] = null,
client: pg.Client = null
): Promise<NodeRecord[]> {
const tbl = this.tableName;
const result = await (client ? client : this.pool).query(
`SELECT ${this.selectFields("Children", fields)}
FROM "${tbl}" AS Parents, "${tbl}" AS Children
WHERE Children."left" ${
includeMyself ? ">=" : ">"
} Parents."left" AND Children."left" ${
includeMyself ? "<=" : "<"
} Parents."right" AND Parents."id" = $1`,
[parentNodeId]
);
if (!result || !result.rows || !result.rows.length) return [];
return result.rows;
}
/**
* Get All parents of a given node
* (including immediate parent and parents of immediate parent etc.)
* If the node has no parent (i.e. a root node), an empty array will be returned (unless `includeMyself` = true)
*
* @param {string} childNodeId
* @param {boolean} [includeMyself=false]
* @param {string[]} [fields=null] Selected Fields; If null, use this.defaultSelectFieldList
* @param {pg.Client} [client=null] Optional pg client; Use supplied client connection for query rather than a random connection from Pool
* @returns {Promise<NodeRecord[]>}
* @memberof NestedSetModelQueryer
*/
async getAllParents(
childNodeId: string,
includeMyself: boolean = false,
fields: string[] = null,
client: pg.Client = null
): Promise<NodeRecord[]> {
const tbl = this.tableName;
const result = await (client ? client : this.pool).query(
`SELECT ${this.selectFields("Parents", fields)}
FROM "${tbl}" AS Parents, "${tbl}" AS Children
WHERE Children."left" ${
includeMyself ? ">=" : ">"
} Parents."left" AND Children."left" ${
includeMyself ? "<=" : "<"
} Parents."right" AND Children."id" = $1`,
[childNodeId]
);
if (!result || !result.rows || !result.rows.length) return [];
return result.rows;
}
/**
* Get Immediate Children of a Node
* If the node has no child (i.e. a leaf node), an empty array will be returned
*
* @param {string} parentNodeId
* @param {string[]} [fields=null] Selected Fields; If null, use this.defaultSelectFieldList
* @param {pg.Client} [client=null] Optional pg client; Use supplied client connection for query rather than a random connection from Pool
* @returns {Promise<NodeRecord[]>}
* @memberof NestedSetModelQueryer
*/
async getImmediateChildren(
parentNodeId: string,
fields: string[] = null,
client: pg.Client = null
): Promise<NodeRecord[]> {
const tbl = this.tableName;
const result = await (client ? client : this.pool).query(
`SELECT ${this.selectFields("Children", fields)}
FROM "${tbl}" AS Parents, "${tbl}" AS Children
WHERE Children."left" BETWEEN Parents."left" AND Parents."right"
AND Parents."left" = (
SELECT MAX(S."left") FROM "${tbl}" AS S
WHERE S."left" < Children."left" AND S."right" > Children."right"
)
AND Parents."id" = $1
ORDER BY Children."left" ASC`,
[parentNodeId]
);
if (!result || !result.rows || !result.rows.length) return [];
return result.rows;
}
/**
* Get Immediate Parent of a Node
* If the node has no parent (i.e. a root node), null will be returned
*
* @param {string} childNodeId
* @param {string[]} [fields=null] Selected Fields; If null, use this.defaultSelectFieldList
* @param {pg.Client} [client=null] Optional pg client; Use supplied client connection for query rather than a random connection from Pool
* @returns {Promise<NodeRecord>}
* @memberof NestedSetModelQueryer
*/
async getImmediateParent(
childNodeId: string,
fields: string[] = null,
client: pg.Client = null
): Promise<Maybe<NodeRecord>> {
const tbl = this.tableName;
const result = await (client ? client : this.pool).query(
`SELECT ${this.selectFields("Parents", fields)}
FROM "${tbl}" AS Parents, "${tbl}" AS Children
WHERE Children.left BETWEEN Parents.left AND Parents.right
AND Parents.left = (
SELECT MAX(S.left) FROM "${tbl}" AS S
WHERE S.left < Children.left AND S.right > Children.right
)
AND Children.id = $1`,
[childNodeId]
);
if (!result || !result.rows || !result.rows.length)
return Maybe.nothing();
return Maybe.just(result.rows[0]);
}
/**
* Get all nodes at level n from top
* e.g. get all nodes at level 3:
* this.getAllNodesAtLevel(3)
* Root node is at level 1
*
* @param {number} level
* @returns {Promise<NodeRecord[]>}
* @memberof NestedSetModelQueryer
*/
async getAllNodesAtLevel(level: number): Promise<NodeRecord[]> {
const tbl = this.tableName;
const result = await this.pool.query(
`SELECT ${this.selectFields("t2")}
FROM "${tbl}" AS t1, "${tbl}" AS t2
WHERE t2.left BETWEEN t1.left AND t1.right
GROUP BY t2.id
HAVING COUNT(t1.id) = $1`,
[level]
);
if (!result || !result.rows || !result.rows.length) return [];
return result.rows;
}
/**
* Get level no. of a given node
* Starts from 1. i.e. The root node is 1
*
* @param {string} nodeId
* @returns {Promise<number>}
* @throws NodeNotFoundError If the node can't be found in the tree
* @memberof NestedSetModelQueryer
*/
async getLevelOfNode(nodeId: string): Promise<number> {
const tbl = this.tableName;
const result = await this.pool.query(
`SELECT COUNT(Parents.id) AS level
FROM "${tbl}" AS Parents, "${tbl}" AS Children
WHERE Children.left BETWEEN Parents.left AND Parents.right AND Children.id = $1`,
[nodeId]
);
if (!result || !result.rows || !result.rows.length)
throw new NodeNotFoundError();
const level: number = parseInt(result.rows[0]["level"]);
if (!_.isNumber(level) || _.isNaN(level) || level < 1)
throw new Error(
`Could find a valid level for node ${nodeId}: ${level}`
);
return level;
}
/**
* Get total height (no. of the levels) of the tree
* Starts with 1 level.
*
* @returns {Promise<number>}
* @throws NodeNotFoundError If the root node can't be found in the tree
* @memberof NestedSetModelQueryer
*/
async getTreeHeight(): Promise<number> {
const tbl = this.tableName;
const result = await this.pool.query(
`SELECT MAX(level) AS height
FROM(
SELECT COUNT(t1.id)
FROM "${tbl}" AS t1, "${tbl}" AS t2
WHERE t2.left BETWEEN t1.left AND t1.right
GROUP BY t2.id
) AS L(level)`
);
if (!result || !result.rows || !result.rows.length)
throw new NodeNotFoundError();
const height: number = parseInt(result.rows[0]["height"]);
if (!_.isNumber(height) || _.isNaN(height) || height < 0)
throw new Error(`Invalid height for tree: ${height}`);
return height;
}
/**
* Get left most immediate child of a node
*
* @param {string} parentNodeId
* @returns {Promise<Maybe<NodeRecord>>}
* @memberof NestedSetModelQueryer
*/
async getLeftMostImmediateChild(
parentNodeId: string
): Promise<Maybe<NodeRecord>> {
const tbl = this.tableName;
const result = await this.pool.query(
`SELECT ${this.selectFields("Children")}
FROM "${tbl}" AS Parents, "${tbl}" AS Children
WHERE Children.left = Parents.left + 1 AND Parents.id = $1`,
[parentNodeId]
);
if (!result || !result.rows || !result.rows.length)
return Maybe.nothing();
return Maybe.just(result.rows[0]);
}
/**
* Get right most immediate child of a node
*
* @param {string} parentNodeId
* @returns {Promise<Maybe<NodeRecord>>}
* @memberof NestedSetModelQueryer
*/
async getRightMostImmediateChild(
parentNodeId: string
): Promise<Maybe<NodeRecord>> {
const tbl = this.tableName;
const result = await this.pool.query(
`SELECT ${this.selectFields("Children")}
FROM "${tbl}" AS Parents, "${tbl}" AS Children
WHERE Children.right = Parents.right - 1 AND Parents.id = $1`,
[parentNodeId]
);
if (!result || !result.rows || !result.rows.length)
return Maybe.nothing();
return Maybe.just(result.rows[0]);
}
/**
* Get all nodes on the top to down path between the `higherNode` to the `lowerNode`
* Sort from higher level nodes to lower level node
* If a path doesn't exist, null will be returned
* If you pass a lower node to the `higherNodeId` and a higher node to `lowerNodeId`, null will be returned
*
* @param {string} higherNodeId
* @param {string} lowerNodeId
* @returns {Promise<Maybe<NodeRecord[]>}
* @memberof NestedSetModelQueryer
*/
async getTopDownPathBetween(
higherNodeId: string,
lowerNodeId: string
): Promise<Maybe<NodeRecord[]>> {
const tbl = this.tableName;
const result = await this.pool.query(
`SELECT ${this.selectFields("t2")}
FROM "${tbl}" AS t1, "${tbl}" AS t2, "${tbl}" AS t3
WHERE t1.id = $1 AND t3.id = $2
AND t2.left BETWEEN t1.left AND t1.right
AND t3.left BETWEEN t2.left AND t2.right
ORDER BY (t2.right-t2.left) DESC`,
[higherNodeId, lowerNodeId]
);
if (!result || !result.rows || !result.rows.length)
return Maybe.nothing();
return Maybe.just(result.rows);
}
/**
* Compare the relative position of the two nodes
* If node1 is superior to node2, return "ancestor"
* if node1 is the subordinate of node2, return "descendant"
* If node1 = node2 return "equal"
* If there is no path can be found between Node1 and Node2 return "unrelated"
*
* @param {string} node1Id
* @param {string} node2Id
* @param {pg.Client} [client=null] Optional pg client; Use supplied client connection for query rather than a random connection from Pool
* @returns {Promise<CompareNodeResult>}
* @memberof NestedSetModelQueryer
*/
async compareNodes(
node1Id: string,
node2Id: string,
client: pg.Client = null
): Promise<CompareNodeResult> {
const tbl = this.tableName;
const result = await (client ? client : this.pool).query(
`SELECT (
CASE
WHEN CAST($1 AS varchar) = CAST($2 AS varchar)
THEN 0
WHEN t1.left BETWEEN t2.left AND t2.right
THEN -1
WHEN t2.left BETWEEN t1.left AND t1.right
THEN 1
ELSE null
END
) AS "result"
FROM "${tbl}" AS t1, "${tbl}" AS t2
WHERE t1.id = CAST($1 AS uuid) AND t2.id = CAST($2 AS uuid)`,
[node1Id, node2Id]
);
if (!result || !result.rows || !result.rows.length) return "unrelated";
const comparisonResult: number = result.rows[0]["result"];
if (typeof comparisonResult === "number") {
switch (comparisonResult) {
case 1:
return "ancestor";
case -1:
return "descendant";
case 0:
return "equal";
}
}
return "unrelated";
}
private getInsertFields(insertFieldList: string[] = null) {
const fieldList = isNonEmptyArray(insertFieldList)
? insertFieldList
: this.defaultInsertFieldList;
if (!isNonEmptyArray(fieldList)) {
throw new Error("Insert fields must be an non-empty array!");
}
return fieldList;
}
private getNodesInsertSql(
nodes: NodeRecord[],
sqlValues: any[],
insertFieldList: string[] = null,
tableAliasOrName: string = ""
) {
if (!isNonEmptyArray(nodes)) {
throw new Error(
"`sqlValues` parameter should be an non-empty array!"
);
}
if (!_.isArray(sqlValues)) {
throw new Error("`sqlValues` parameter should be an array!");
}
if (!isValidSqlIdentifier(tableAliasOrName)) {
throw new Error(
`tableAliasOrName: ${tableAliasOrName} contains invalid characters!`
);
}
const tbl = this.tableName;
const fieldList = this.getInsertFields(insertFieldList);
const columnsList = fieldList
.map((f) => {
if (!isValidSqlIdentifier(f)) {
throw new Error(
`column name: ${f} contains invalid characters!`
);
}
return tableAliasOrName == ""
? `"${f}"`
: `${tableAliasOrName}."${f}"`;
})
.join(", ");
const valuesList = nodes
.map(
(node) =>
"(" +
fieldList
.map((f) => {
sqlValues.push(node[f]);
return `$${sqlValues.length}`;
})
.join(", ") +
")"
)
.join(", ");
return `INSERT INTO "${tbl}" (${columnsList}) VALUES ${valuesList}`;
}
/**
* Create the root node of the tree.
* If a root node already exists, an error will be thrown.
*
* @param {NodeRecord} node
* @param {pg.Client} [existingClient=null] Optional pg client; Use supplied client connection for query rather than a random connection from Pool
* @returns {Promise<string>} newly created node ID
* @memberof NestedSetModelQueryer
*/
async createRootNode(
node: NodeRecord,
existingClient: pg.Client = null
): Promise<string> {
const tbl = this.tableName;
const client = existingClient
? existingClient
: await this.pool.connect();
const fields = Object.keys(node);
if (!fields.length) {
throw new Error(
"`node` parameter cannot be an empty object with no key."
);
}
let nodeId: string;
try {
await client.query("BEGIN");
let result = await client.query(
`SELECT "id" FROM "${tbl}" WHERE "left" = 1 LIMIT 1`
);
if (result && isNonEmptyArray(result.rows)) {
throw new Error(
`A root node with id: ${result.rows[0]["id"]} already exists`
);
}
const countResult = await client.query(
`SELECT COUNT("id") AS "num" FROM "${tbl}" WHERE "left" != 1`
);
let countNum =
countResult && countResult.rows && countResult.rows.length
? parseInt(countResult.rows[0].num)
: 0;
countNum = isNaN(countNum) ? 0 : countNum;
const right = countNum ? (countNum + 1) * 2 : 2;
const sqlValues: any[] = [];
result = await client.query(
this.getNodesInsertSql(
[
{
...node,
left: 1,
right
}
],
sqlValues,
fields.concat(["left", "right"])
) + " RETURNING id",
sqlValues
);
if (!result || !isNonEmptyArray(result.rows)) {
throw new Error("Cannot locate create root node ID!");
}
await client.query("COMMIT");
nodeId = result.rows[0]["id"];
} catch (e) {
await client.query("ROLLBACK");
throw e;
} finally {
if (!existingClient) {
client.release();
}
}
return nodeId;
}
private async getNodeDataWithinTx(
client: pg.Client,
nodeId: string,
fields: string[]
): Promise<NodeRecord> {
const node = await this.getNodeById(nodeId, fields, client);
return node.caseOf({
just: (node) => node,
nothing: () => {
throw new NodeNotFoundError(
`Cannot locate tree node record with id: ${nodeId}`
);
}
});
}
/**
* Insert a node to the tree under a parent node
*
* @param {string} parentNodeId
* @param {NodeRecord} node
* @returns {Promise<string>}
* @throws NodeNotFoundError if parent node not found
* @memberof NestedSetModelQueryer
*/
async insertNode(parentNodeId: string, node: NodeRecord): Promise<string> {
if (!parentNodeId) {
throw new Error("`parentNodeId` cannot be empty!");
}
const fields = Object.keys(node);
if (!fields.length) {
throw new Error(
"`node` parameter cannot be an empty object with no key."
);
}
const tbl = this.tableName;
const client = await this.pool.connect();
let nodeId: string;
try {
await client.query("BEGIN");
const {
right: parentRight
} = await this.getNodeDataWithinTx(client, parentNodeId, ["right"]);
await client.query(
`UPDATE "${tbl}"
SET
"left" = CASE WHEN "left" > $1 THEN "left" + 2 ELSE "left" END,
"right" = CASE WHEN "right" >= $1 THEN "right" + 2 ELSE "right" END
WHERE "right" >= $1`,
[parentRight]
);
const sqlValues: any[] = [];
const result = await client.query(
this.getNodesInsertSql(
[
{
...node,
left: parentRight,
right: parentRight + 1
}
],
sqlValues,
fields.concat(["left", "right"])
) + " RETURNING id",
sqlValues
);
if (!result || !isNonEmptyArray(result.rows)) {
throw new Error("Cannot locate created node ID!");
}
await client.query("COMMIT");
nodeId = result.rows[0]["id"];
} catch (e) {
await client.query("ROLLBACK");
throw e;
} finally {
client.release();
}
return nodeId;
}
/**
* Insert a node to the right of its sibling
* If `siblingNodeId` belongs to a root node, an error will be thrown
*
* @param {string} siblingNodeId
* @param {NodeRecord} node
* @returns {Promise<string>}
* @throws NodeNotFoundError If the node can't be found in the tree
* @memberof NestedSetModelQueryer
*/
async insertNodeToRightOfSibling(
siblingNodeId: string,
node: NodeRecord
): Promise<string> {
if (!siblingNodeId) {
throw new Error("`siblingNodeId` cannot be empty!");
}
const fields = Object.keys(node);
if (!fields.length) {
throw new Error(
"`node` parameter cannot be an empty object with no key."
);
}
const tbl = this.tableName;
const client = await this.pool.connect();
let nodeId: string;
try {
await client.query("BEGIN");
const {
left: siblingLeft,
right: siblingRight
} = await this.getNodeDataWithinTx(client, siblingNodeId, [
"left",
"right"
]);
if (siblingLeft === 1) {
throw new Error("Cannot add sibling to the Root node!");
}
await client.query(
`UPDATE "${tbl}"
SET
"left" = CASE WHEN "left" < $1 THEN "left" ELSE "left" + 2 END,
"right" = CASE WHEN "right" < $1 THEN "right" ELSE "right" + 2 END
WHERE "right" > $1`,
[siblingRight]
);
const sqlValues: any[] = [];
const result = await client.query(
this.getNodesInsertSql(
[
{
...node,
left: siblingRight + 1,
right: siblingRight + 2
}
],
sqlValues,
fields.concat(["left", "right"])
) + " RETURNING id",
sqlValues
);
if (!result || !isNonEmptyArray(result.rows)) {
throw new Error("Cannot locate created node ID!");
}
await client.query("COMMIT");
nodeId = result.rows[0]["id"];
} catch (e) {
await client.query("ROLLBACK");
throw e;
} finally {
client.release();
}
return nodeId;
}
/**
* Move a subtree (the specified root node and all its subordinates)
* to under a new parent.
*
* If the specifed sub tree root node is a child of the new parent node,
* an error will be be thrown
*
* @param {string} subTreeRootNodeId
* @param {string} newParentId
* @returns {Promise<void>}
* @throws NodeNotFoundError If the node can't be found in the tree
* @memberof NestedSetModelQueryer
*/
async moveSubTreeTo(
subTreeRootNodeId: string,
newParentId: string
): Promise<void> {
if (!subTreeRootNodeId) {
throw new Error("`subTreeRootNodeId` cannot be empty!");
}
if (!newParentId) {
throw new Error("`newParentId` cannot be empty!");
}
const tbl = this.tableName;
const client = await this.pool.connect();
try {
await client.query("BEGIN");
const comparisonResult = await this.compareNodes(
subTreeRootNodeId,
newParentId,
client
);
if (comparisonResult === "ancestor") {
throw new Error(
`Cannot move a higher level node (id: ${subTreeRootNodeId})to its subordinate (id: ${newParentId})`
);
}
const {
left: originRootLeft,
right: originRootRight
} = await this.getNodeDataWithinTx(client, subTreeRootNodeId, [
"left",
"right"
]);
if (originRootLeft === "1") {
throw new Error("Cannot move Tree root node as substree.");
}
const {
right: newParentRight
} = await this.getNodeDataWithinTx(client, newParentId, ["right"]);
await client.query(
`
UPDATE "${tbl}"
SET
"left" = "left" + CASE
WHEN $3::int4 < $1::int4
THEN CASE
WHEN "left" BETWEEN $1 AND $2
THEN $3 - $1
WHEN "left" BETWEEN $3 AND ($1 - 1)
THEN $2 - $1 + 1
ELSE 0 END
WHEN $3::int4 > $2::int4
THEN CASE
WHEN "left" BETWEEN $1 AND $2
THEN $3 - $2 - 1
WHEN "left" BETWEEN ($2 + 1) AND ($3 - 1)
THEN $1 - $2 - 1
ELSE 0 END
ELSE 0 END,
"right" = "right" + CASE
WHEN $3::int4 < $1::int4
THEN CASE
WHEN "right" BETWEEN $1 AND $2
THEN $3 - $1
WHEN "right" BETWEEN $3 AND ($1 - 1)
THEN $2 - $1 + 1
ELSE 0 END
WHEN $3::int4 > $2::int4
THEN CASE
WHEN "right" BETWEEN $1 AND $2
THEN $3 - $2 - 1
WHEN "right" BETWEEN ($2 + 1) AND ($3 - 1)
THEN $1 - $2 - 1
ELSE 0 END
ELSE 0 END
`,
[originRootLeft, originRootRight, newParentRight]
);
await client.query("COMMIT");
} catch (e) {
await client.query("ROLLBACK");
throw e;
} finally {
client.release();
}
}
/**
* Delete a subtree (and all its dependents)
* If you sent in a root node id (and `allowRootNodeId` is true), the whole tree will be removed
* When `allowRootNodeId` is false and you passed a root node id, an error will be thrown
*
* @param {string} subTreeRootNodeId
* @param {boolean} [allowRootNodeId=false]
* @returns {Promise<void>}
* @throws NodeNotFoundError If the node can't be found in the tree
* @memberof NestedSetModelQueryer
*/
async deleteSubTree(
subTreeRootNodeId: string,
allowRootNodeId: boolean = false
): Promise<void> {
if (!subTreeRootNodeId) {
throw new Error("`subTreeRootNodeId` cannot be empty!");
}
const tbl = this.tableName;
const client = await this.pool.connect();
try {
await client.query("BEGIN");
const {
left: subTreeRootLeft,
right: subTreeRootRight
} = await this.getNodeDataWithinTx(client, subTreeRootNodeId, [
"left",
"right"
]);
if (subTreeRootLeft === 1 && !allowRootNodeId) {
throw new Error("Root node id is not allowed!");
}
// --- delete the sub tree nodes
await client.query(
`DELETE FROM "${tbl}" WHERE "left" BETWEEN $1 AND $2`,
[subTreeRootLeft, subTreeRootRight]
);
// --- closing the gap after deletion
await client.query(
`
UPDATE "${tbl}"
SET "left" = CASE
WHEN "left" > $1
THEN "left" - ($2 - $1 + 1)
ELSE "left" END,
"right" = CASE
WHEN "right" > $1
THEN "right" - ($2 - $1 + 1)
ELSE "right" END
WHERE "left" > $1 OR "right" > $1
`,
[subTreeRootLeft, subTreeRootRight]
);
await client.query("COMMIT");
} catch (e) {
await client.query("ROLLBACK");
throw e;
} finally {
client.release();
}
}
/**
* Delete a single node from the tree
* Its childrens will become its parent's children
* Deleting a root node is not allowed.
* You can, however, delete the whole sub tree from root node or update the root node, instead.
*
* @param {string} nodeId
* @returns {Promise<void>}
* @throws NodeNotFoundError If the node can't be found in the tree
* @memberof NestedSetModelQueryer
*/
async deleteNode(nodeId: string): Promise<void> {
if (!nodeId) {
throw new Error("`nodeId` cannot be empty!");
}
const tbl = this.tableName;
const client = await this.pool.connect();
try {
await client.query("BEGIN");
const {
left: subTreeRootLeft,
right: subTreeRootRight
} = await this.getNodeDataWithinTx(client, nodeId, [
"left",
"right"
]);
if (subTreeRootLeft === 1) {
throw new Error("Delete a root node is not allowed!");
}
// --- delete the node
// --- In nested set model, children are still bind to the deleted node's parent after deletion
await client.query(`DELETE FROM "${tbl}" WHERE "id" = $1`, [
nodeId
]);
// --- closing the gap after deletion
await client.query(
`
UPDATE "${tbl}"
SET "left" = CASE
WHEN "left" > $1 AND "right" < $2
THEN "left" - 1
WHEN "left" > $1 AND "right" > $2
THEN "left" - 2
ELSE "left" END,
"right" = CASE
WHEN "left" > $1 AND "right" < $2
THEN "right" - 1
ELSE ("right" - 2) END
WHERE "left" > $1 OR "right" > $1
`,
[subTreeRootLeft, subTreeRootRight]
);
await client.query("COMMIT");
} catch (e) {
await client.query("ROLLBACK");
throw e;
} finally {
client.release();
}
}
/**
* Update node data of the node specified by the nodeId
* The followings fields will be ignored (as they should be generated by program):
* - `left`
* - `right`
* - `id`
*
* @param {string} nodeId
* @param {NodeRecord} nodeData
* @param {pg.Client} [client=null]
* @returns {Promise<void>}
* @memberof NestedSetModelQueryer
*/
async updateNode(
nodeId: string,
nodeData: NodeRecord,
client: pg.Client = null
): Promise<void> {
if (nodeId.trim() === "") {
throw new Error("nodeId can't be empty!");
}
const sqlValues: any[] = [nodeId];
const updateFields: string[] = Object.keys(nodeData).filter(
(k) => k !== "left" && k !== "right" && k !== "id"
);
if (!updateFields.length) {
throw new Error("No valid node data passed for updating.");
}
const setFieldList = updateFields
.map((f) => {
if (!isValidSqlIdentifier(f)) {
throw new Error(
`field name: ${f} contains invalid characters!`
);
}
sqlValues.push(nodeData[f]);
return `"${f}" = $${sqlValues.length}`;
})
.join(", ");
await (client ? client : this.pool).query(
`UPDATE "${this.tableName}" SET ${setFieldList} WHERE "id" = $1`,
sqlValues
);
}
private async getChildTextTreeNodes(
parentId: string
): Promise<TextTreeNode[]> {
const nodes = await this.getImmediateChildren(parentId);
if (!nodes || !nodes.length) return [];
const textNodeList: TextTreeNode[] = [];
for (let i = 0; i < nodes.length; i++) {
const nodeChildren = await this.getChildTextTreeNodes(nodes[i].id);
if (nodeChildren.length) {
textNodeList.push({
text: nodes[i].name,
children: nodeChildren
});
} else {
textNodeList.push(nodes[i].name);
}
}
return textNodeList;
}
/**
* Generate the Text View of the tree
* Provided as Dev tool only
*
* E.g. output could be:
* └─ Albert
* ├─ Chuck
* │ ├─ Fred
* │ ├─ Eddie
* │ └─ Donna
* └─ Bert
*
* @returns {Promise<string>}
* @memberof NestedSetModelQueryer
*/
async getTreeTextView(): Promise<string> {
const rootNodeMaybe = await this.getRootNode();
return rootNodeMaybe.caseOf({
just: async (rootNode) => {
const tree: TextTreeNode[] = [];
const children = await this.getChildTextTreeNodes(rootNode.id);
if (children.length) {
tree.push({
text: rootNode.name,
children
});
} else {
tree.push(rootNode.name);
}
return textTree(tree);
},
nothing: async () => "Empty Tree"
});
}
}
export default NestedSetModelQueryer; | the_stack |
import * as Gio from 'gio';
import * as GLib from 'glib';
import * as Meta from 'meta';
import * as Shell from 'shell';
import { MsWindow } from 'src/layout/msWorkspace/msWindow';
import { TilingLayoutByKey } from 'src/manager/layoutManager';
import { getSettings } from 'src/utils/settings';
import { MsApplicationLauncher } from 'src/widget/msApplicationLauncher';
import { main as Main } from 'ui';
/** Extension imports */
const Me = imports.misc.extensionUtils.getCurrentExtension();
/* exported HotKeysModule, KeyBindingAction */
export const KeyBindingAction: Record<string, string> = {
// window actions
PREVIOUS_WINDOW: 'previous-window',
NEXT_WINDOW: 'next-window',
APP_LAUNCHER: 'app-launcher',
KILL_FOCUSED_WINDOW: 'kill-focused-window',
MOVE_WINDOW_LEFT: 'move-window-left',
MOVE_WINDOW_RIGHT: 'move-window-right',
MOVE_WINDOW_TOP: 'move-window-top',
MOVE_WINDOW_BOTTOM: 'move-window-bottom',
RESIZE_WINDOW_LEFT: 'resize-window-left',
RESIZE_WINDOW_UP: 'resize-window-up',
RESIZE_WINDOW_RIGHT: 'resize-window-right',
RESIZE_WINDOW_DOWN: 'resize-window-down',
FOCUS_MONITOR_LEFT: 'focus-monitor-left',
FOCUS_MONITOR_UP: 'focus-monitor-up',
FOCUS_MONITOR_RIGHT: 'focus-monitor-right',
FOCUS_MONITOR_DOWN: 'focus-monitor-down',
MOVE_WINDOW_MONITOR_LEFT: 'move-window-monitor-left',
MOVE_WINDOW_MONITOR_UP: 'move-window-monitor-up',
MOVE_WINDOW_MONITOR_RIGHT: 'move-window-monitor-right',
MOVE_WINDOW_MONITOR_DOWN: 'move-window-monitor-down',
// layout actions
CYCLE_TILING_LAYOUT: 'cycle-tiling-layout',
REVERSE_CYCLE_TILING_LAYOUT: 'reverse-cycle-tiling-layout',
TOGGLE_MATERIAL_SHELL_UI: 'toggle-material-shell-ui',
// workspaces actions
PREVIOUS_WORKSPACE: 'previous-workspace',
NEXT_WORKSPACE: 'next-workspace',
LAST_WORKSPACE: 'last-workspace',
};
export class HotKeysModule {
workspaceManager: Meta.WorkspaceManager;
settings: Gio.Settings;
actionIdToNameMap: Map<number, string>;
actionNameToActionMap: Map<string, () => void>;
connectId: number;
lastStash: number | null;
nextStash: number | null;
constructor() {
this.workspaceManager = global.workspace_manager;
this.settings = getSettings('bindings');
this.actionIdToNameMap = new Map();
this.actionNameToActionMap = new Map();
this.lastStash = null;
this.nextStash = null;
this.resetStash();
this.connectId = global.window_manager.connect(
'switch-workspace',
(_, from: number, _to: number) => {
if (this.lastStash !== null && from != this.lastStash) {
this.resetStash();
}
}
);
this.actionNameToActionMap.set(KeyBindingAction.PREVIOUS_WINDOW, () => {
const msWorkspace = Me.msWorkspaceManager.getActiveMsWorkspace();
msWorkspace.focusPreviousTileable();
});
this.actionNameToActionMap.set(KeyBindingAction.NEXT_WINDOW, () => {
const msWorkspace = Me.msWorkspaceManager.getActiveMsWorkspace();
msWorkspace.focusNextTileable();
});
this.actionNameToActionMap.set(KeyBindingAction.APP_LAUNCHER, () => {
const msWorkspace = Me.msWorkspaceManager.getActiveMsWorkspace();
msWorkspace.focusAppLauncher();
});
this.actionNameToActionMap.set(
KeyBindingAction.PREVIOUS_WORKSPACE,
() => {
Me.msWorkspaceManager.activatePreviousMsWorkspace();
}
);
this.actionNameToActionMap.set(KeyBindingAction.NEXT_WORKSPACE, () => {
Me.msWorkspaceManager.activateNextMsWorkspace();
});
this.actionNameToActionMap.set(KeyBindingAction.LAST_WORKSPACE, () => {
const currentIndex =
this.workspaceManager.get_active_workspace_index();
const lastIndex = this.workspaceManager.n_workspaces - 1;
if (currentIndex < lastIndex) {
Me.msWorkspaceManager.primaryMsWorkspaces[lastIndex].activate();
}
});
this.actionNameToActionMap.set(
KeyBindingAction.KILL_FOCUSED_WINDOW,
() => {
const msWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspace();
if (msWorkspace.tileableFocused instanceof MsWindow) {
msWorkspace.tileableFocused.kill();
}
}
);
this.actionNameToActionMap.set(
KeyBindingAction.MOVE_WINDOW_LEFT,
() => {
const msWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspace();
const focused = msWorkspace.tileableFocused;
if (focused !== null) {
msWorkspace.swapTileableLeft(focused);
}
}
);
this.actionNameToActionMap.set(
KeyBindingAction.MOVE_WINDOW_RIGHT,
() => {
const msWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspace();
const focused = msWorkspace.tileableFocused;
if (focused !== null) {
msWorkspace.swapTileableRight(focused);
}
}
);
this.actionNameToActionMap.set(KeyBindingAction.MOVE_WINDOW_TOP, () => {
const activeMsWorkspace =
Me.msWorkspaceManager.getActivePrimaryMsWorkspace();
if (
activeMsWorkspace.tileableFocused instanceof
MsApplicationLauncher ||
activeMsWorkspace.tileableFocused == null
) {
return;
}
if (
activeMsWorkspace ===
Me.msWorkspaceManager.primaryMsWorkspaces[0]
) {
if (
!Me.msWorkspaceManager.shouldCycleWorkspacesNavigation() &&
(!Meta.prefs_get_dynamic_workspaces() ||
activeMsWorkspace.msWindowList.length === 1)
) {
return;
}
const nextMsWorkspace =
Me.msWorkspaceManager.primaryMsWorkspaces[
Me.msWorkspaceManager.primaryMsWorkspaces.length - 1
];
Me.msWorkspaceManager.setWindowToMsWorkspace(
activeMsWorkspace.tileableFocused,
nextMsWorkspace
);
if (!Me.msWorkspaceManager.shouldCycleWorkspacesNavigation()) {
Me.msWorkspaceManager.setMsWorkspaceAt(nextMsWorkspace, 0);
}
nextMsWorkspace.activate();
return;
}
const currentMsWorkspaceIndex =
Me.msWorkspaceManager.primaryMsWorkspaces.indexOf(
activeMsWorkspace
);
const nextMsWorkspace =
Me.msWorkspaceManager.primaryMsWorkspaces[
currentMsWorkspaceIndex - 1
];
Me.msWorkspaceManager.setWindowToMsWorkspace(
activeMsWorkspace.tileableFocused,
nextMsWorkspace
);
nextMsWorkspace.activate();
});
Meta.keybindings_set_custom_handler(
'move-to-workspace-up',
this.actionNameToActionMap.get(KeyBindingAction.MOVE_WINDOW_TOP)
);
this.actionNameToActionMap.set(
KeyBindingAction.MOVE_WINDOW_BOTTOM,
() => {
const activeMsWorkspace =
Me.msWorkspaceManager.getActivePrimaryMsWorkspace();
if (
activeMsWorkspace.tileableFocused instanceof
MsApplicationLauncher ||
activeMsWorkspace.tileableFocused == null
) {
return;
}
if (
activeMsWorkspace ===
Me.msWorkspaceManager.primaryMsWorkspaces[
Me.msWorkspaceManager.primaryMsWorkspaces.length -
(Meta.prefs_get_dynamic_workspaces() ? 2 : 1)
]
) {
if (
(Meta.prefs_get_dynamic_workspaces() &&
activeMsWorkspace.msWindowList.length === 1 &&
!Me.msWorkspaceManager.shouldCycleWorkspacesNavigation()) ||
(!Meta.prefs_get_dynamic_workspaces() &&
!Me.msWorkspaceManager.shouldCycleWorkspacesNavigation())
) {
return;
}
if (
!Meta.prefs_get_dynamic_workspaces() ||
(activeMsWorkspace.msWindowList.length === 1 &&
Me.msWorkspaceManager.shouldCycleWorkspacesNavigation())
) {
const nextMsWorkspace =
Me.msWorkspaceManager.msWorkspaceList[0];
Me.msWorkspaceManager.setWindowToMsWorkspace(
activeMsWorkspace.tileableFocused,
nextMsWorkspace
);
Me.msWorkspaceManager.setMsWorkspaceAt(
nextMsWorkspace,
0
);
nextMsWorkspace.activate();
return;
}
}
const currentMsWorkspaceIndex =
Me.msWorkspaceManager.primaryMsWorkspaces.indexOf(
activeMsWorkspace
);
const nextMsWorkspace =
Me.msWorkspaceManager.primaryMsWorkspaces[
currentMsWorkspaceIndex + 1
];
Me.msWorkspaceManager.setWindowToMsWorkspace(
activeMsWorkspace.tileableFocused,
nextMsWorkspace
);
nextMsWorkspace.activate();
}
);
Meta.keybindings_set_custom_handler(
'move-to-workspace-down',
this.actionNameToActionMap.get(KeyBindingAction.MOVE_WINDOW_BOTTOM)
);
this.actionNameToActionMap.set(
KeyBindingAction.RESIZE_WINDOW_LEFT,
() => {
const msWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspace();
const focused = msWorkspace.tileableFocused;
if (focused !== null) {
Me.msWindowManager.msResizeManager.resizeTileable(
focused,
Meta.GrabOp.RESIZING_W,
5
);
}
}
);
this.actionNameToActionMap.set(
KeyBindingAction.RESIZE_WINDOW_UP,
() => {
const msWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspace();
const focused = msWorkspace.tileableFocused;
if (focused !== null) {
Me.msWindowManager.msResizeManager.resizeTileable(
focused,
Meta.GrabOp.RESIZING_N,
5
);
}
}
);
this.actionNameToActionMap.set(
KeyBindingAction.RESIZE_WINDOW_RIGHT,
() => {
const msWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspace();
const focused = msWorkspace.tileableFocused;
if (focused !== null) {
Me.msWindowManager.msResizeManager.resizeTileable(
focused,
Meta.GrabOp.RESIZING_E,
5
);
}
}
);
this.actionNameToActionMap.set(
KeyBindingAction.RESIZE_WINDOW_DOWN,
() => {
const msWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspace();
const focused = msWorkspace.tileableFocused;
if (focused !== null) {
Me.msWindowManager.msResizeManager.resizeTileable(
focused,
Meta.GrabOp.RESIZING_S,
5
);
}
}
);
(['LEFT', 'UP', 'RIGHT', 'DOWN'] as const).forEach((DIRECTION) => {
this.actionNameToActionMap.set(
KeyBindingAction[`FOCUS_MONITOR_${DIRECTION}`],
() => {
const currentMsWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspace();
const monitorIndex =
global.display.get_monitor_neighbor_index(
currentMsWorkspace.monitor.index,
Meta.DisplayDirection[DIRECTION]
);
if (monitorIndex !== -1) {
const msWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspaceOfMonitor(
monitorIndex
);
Me.msWorkspaceManager.focusMsWorkspace(msWorkspace);
}
}
);
this.actionNameToActionMap.set(
KeyBindingAction[`MOVE_WINDOW_MONITOR_${DIRECTION}`],
() => {
const currentMsWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspace();
const focused = currentMsWorkspace.tileableFocused;
if (
focused instanceof MsApplicationLauncher ||
focused === null
) {
return;
}
const monitorIndex =
global.display.get_monitor_neighbor_index(
currentMsWorkspace.monitor.index,
Meta.DisplayDirection[DIRECTION]
);
if (monitorIndex !== -1) {
const msWorkspace =
monitorIndex ===
global.display.get_primary_monitor()
? Me.msWorkspaceManager.getActivePrimaryMsWorkspace()
: Me.msWorkspaceManager.getMsWorkspacesOfMonitorIndex(
monitorIndex
)[0];
Me.msWorkspaceManager.setWindowToMsWorkspace(
focused,
msWorkspace
);
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
Me.msWorkspaceManager.focusMsWorkspace(msWorkspace);
return GLib.SOURCE_REMOVE;
});
}
}
);
Meta.keybindings_set_custom_handler(
`move-to-monitor-${DIRECTION.toLowerCase()}`,
this.actionNameToActionMap.get(
KeyBindingAction[`MOVE_WINDOW_MONITOR_${DIRECTION}`]
)
);
});
[...Array(10).keys()].forEach((workspaceIndex) => {
const actionKey = `MOVE_WINDOW_TO_${workspaceIndex + 1}`;
KeyBindingAction[actionKey] = `move-window-to-workspace-${
workspaceIndex + 1
}`;
this.actionNameToActionMap.set(KeyBindingAction[actionKey], () => {
const activeMsWorkspace =
Me.msWorkspaceManager.getActivePrimaryMsWorkspace();
const currentMsWorkspaceIndex =
Me.msWorkspaceManager.primaryMsWorkspaces.indexOf(
activeMsWorkspace
);
const focused = activeMsWorkspace.tileableFocused;
if (
focused instanceof MsApplicationLauncher ||
focused === null ||
workspaceIndex === currentMsWorkspaceIndex
) {
return;
}
if (
workspaceIndex >=
Me.msWorkspaceManager.primaryMsWorkspaces.length
) {
workspaceIndex =
Me.msWorkspaceManager.primaryMsWorkspaces.length - 1;
}
const nextMsWorkspace =
Me.msWorkspaceManager.primaryMsWorkspaces[workspaceIndex];
Me.msWorkspaceManager.setWindowToMsWorkspace(
focused,
nextMsWorkspace
);
nextMsWorkspace.activate();
});
});
this.actionNameToActionMap.set(
KeyBindingAction.CYCLE_TILING_LAYOUT,
() => {
const msWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspace();
msWorkspace.nextLayout(1);
}
);
this.actionNameToActionMap.set(
KeyBindingAction.REVERSE_CYCLE_TILING_LAYOUT,
() => {
const msWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspace();
msWorkspace.nextLayout(-1);
}
);
this.actionNameToActionMap.set(
KeyBindingAction.TOGGLE_MATERIAL_SHELL_UI,
() => {
Me.layout.togglePanelsVisibilities();
}
);
Object.keys(TilingLayoutByKey).forEach((layoutKey) => {
const actionKey = `USE_${layoutKey}_LAYOUT`;
KeyBindingAction[actionKey] = `use-${layoutKey}-layout`;
this.actionNameToActionMap.set(KeyBindingAction[actionKey], () => {
const msWorkspace =
Me.msWorkspaceManager.getActiveMsWorkspace();
msWorkspace.setLayoutByKey(layoutKey);
});
});
[...Array(10).keys()].forEach((workspaceIndex) => {
const actionKey = `NAVIGATE_TO_${workspaceIndex + 1}`;
KeyBindingAction[actionKey] = `navigate-to-workspace-${
workspaceIndex + 1
}`;
this.actionNameToActionMap.set(KeyBindingAction[actionKey], () => {
const currentNumOfWorkspaces =
Me.msWorkspaceManager.msWorkspaceList.length - 1;
const currentWorkspaceIndex =
this.workspaceManager.get_active_workspace_index();
let nextWorkspaceIndex = workspaceIndex;
if (
this.lastStash === null ||
nextWorkspaceIndex !== this.nextStash
) {
this.lastStash = currentWorkspaceIndex;
this.nextStash = nextWorkspaceIndex;
} else {
if (nextWorkspaceIndex === this.nextStash) {
nextWorkspaceIndex = this.lastStash;
}
this.resetStash();
}
// go to new workspace if attempting to go to index bigger than currently available
nextWorkspaceIndex =
nextWorkspaceIndex > currentNumOfWorkspaces
? currentNumOfWorkspaces
: nextWorkspaceIndex;
Me.msWorkspaceManager.primaryMsWorkspaces[
nextWorkspaceIndex
].activate();
});
});
this.actionNameToActionMap.forEach((action, name) => {
this.addKeybinding(name);
});
}
resetStash() {
this.lastStash = null;
this.nextStash = null;
}
addKeybinding(name: string) {
const actionCallback = this.actionNameToActionMap.get(name);
if (actionCallback === undefined) {
Me.log(
'Error: Cannot add keybinding. No such action exists: ' + name
);
return;
}
const actionId = Main.wm.addKeybinding(
name,
this.settings,
Meta.KeyBindingFlags.IGNORE_AUTOREPEAT,
Shell.ActionMode.NORMAL,
actionCallback
);
this.actionIdToNameMap.set(actionId, name);
}
destroy() {
for (const [_, value] of this.actionIdToNameMap) {
Main.wm.removeKeybinding(value);
}
this.actionIdToNameMap.clear();
if (this.connectId) {
global.window_manager.disconnect(this.connectId);
}
}
} | the_stack |
import { Injectable } from '@angular/core';
import { Cordova, CordovaProperty, AwesomeCordovaNativePlugin, Plugin } from '@awesome-cordova-plugins/core';
import { Observable } from 'rxjs';
export interface AdmobBaseOptions {
/**
* (Optional) Your interstitial id code from your AdMob account. Defaults to bannerAdId
*/
interstitialAdId?: string;
/**
* (Optional) Indicates whether to put banner ads at top when set to true or at bottom when set to false. Defaults to false
*/
bannerAtTop?: boolean;
/**
* (Optional) Set to true to receive test ads (do not test with real ads as your account may be banned). Defaults to false
*/
isTesting?: boolean;
/**
* (Optional) Auto show banner ads when available (onAdLoaded event is called). Defaults to true
*/
autoShowBanner?: boolean;
/**
* (Optional) Auto show interstitial ads when available (onAdLoaded event is called). Defaults to true
*/
autoShowInterstitial?: boolean;
}
export interface AdmobOptions extends AdmobBaseOptions {
/**
* Your banner id code from your AdMob account (https://support.google.com/admob/answer/7356431?hl=en)
*/
bannerAdId: string;
/**
* Deprecated. Now is only used in web. It will be used as a bannerAdId only in case it is undefined.
*/
publisherId?: string;
/**
* (Optional) Your tappx id for iOS apps. If Admob is configured, it is also used to backfill your lost inventory (when there are no Admob ads available)
*/
tappxIdiOS?: string;
/**
* (Optional) Your tappx id for Android apps. Admob is configured, it is also used to backfill your lost inventory when there are no Admob ads available
*/
tappxIdAndroid?: string;
/**
* AdMob rewarded id (https://support.google.com/admob/answer/7356431?hl=en)
*/
rewardedAdId?: string;
/**
* (Optional) Auto show rewarded ads when available (onAdLoaded event is called). Defaults to true
*/
autoShowRewarded?: boolean;
/**
* (Optional) If any of tappxId is present, it tells the percentage of traffic diverted to tappx. Defaults to 0.5 (50% of the traffic will be requested to Tappx)
*/
tappxShare?: number;
/**
* (Optional) Indicates the size of banner ads
*/
adSize?: string;
/**
* (Optional) Allow banner overlap webview. Default false
*/
overlap?: boolean;
/**
* (Optional) Set to true to avoid ios7 status bar overlap. Default false
*/
offsetStatusBar?: boolean;
/**
* (Options) A JSON object with additional {key: value} pairs
*/
adExtras?: any;
}
export interface AdmobWebOptions extends AdmobBaseOptions {
/**
* (Required) AdSense Publisher ID (https://support.google.com/adsense/answer/105516)
*/
publisherId: string;
/**
* (Required) Your ad slot code from your AdSense account. Only for browser platform https://support.google.com/adsense/answer/105516
*/
adSlot: string;
/**
* (Optional) Indicates if show a close button on interstitial browser ads. Only for browser platform
*/
interstitialShowCloseButton?: boolean;
/**
* (Optional) Indicates the number of seconds that the interstitial ad waits before show the close button. Only for browser platform
*/
secondsToShowCloseButton?: number;
/**
* (Optional) Indicates the number of seconds that the interstitial ad waits before close the ad. Only for browser platform
*/
secondsToCloseInterstitial?: number;
}
export interface AdMobEvent {
/**
* (Optional) AdMob supported type as seen in AD_TYPE
*/
adType?: string;
/**
* (Optional) AdMob error code
*/
error?: number;
/**
* (Optional) AdMob error reason
*/
reason?: string;
}
/**
* @name AdMob
* @description
* Most complete Admob plugin with support for [Tappx](http://www.tappx.com/?h=dec334d63287772de859bdb4e977fce6) ads.
* Monetize your apps and games with AdMob ads, using latest Google AdMob SDK. With this plugin you can show AdMob ads easily!
*
* Supports:**
* - Banner ads (top and bottom)
* - Interstitial ads
* - Rewarded ads
* - [Tappx](http://www.tappx.com/?h=dec334d63287772de859bdb4e977fce6) ads
* @usage
* Note:** No ads will be served on apps with package name `io.ionic.starter`. This is the default package name for new `ionic` apps. Make sure to rename the package name so ads can be displayed.
* ```typescript
* import { Admob, AdmobOptions } from '@awesome-cordova-plugins/admob';
*
*
* constructor(private admob: Admob) {
* // Admob options config
* const admobOptions: AdmobOptions = {
* bannerAdId: 'XXX-XXXX-XXXX',
* interstitialAdId: 'XXX-XXXX-XXXX',
* rewardedAdId: 'XXX-XXXX-XXXX',
* isTesting: true,
* autoShowBanner: false,
* autoShowInterstitial: false,
* autoShowRewarded: false,
* adSize: this.admob.AD_SIZE.BANNER
* };
*
* // Set admob options
* this.admob.setOptions(admobOptions)
* .then(() => console.log('Admob options have been successfully set'))
* .catch(err => console.error('Error setting admob options:', err));
* }
*
*
*
* // (Optionally) Load banner ad, in order to have it ready to show
* this.admob.createBannerView()
* .then(() => console.log('Banner ad loaded'))
* .catch(err => console.error('Error loading banner ad:', err));
*
*
* // Show banner ad (createBannerView must be called before and onAdLoaded() event raised)
* this.admob.onAdLoaded().subscribe((ad) => {
* if (ad.adType === this.admob.AD_TYPE.BANNER) {
* this.admob.showBannerAd()
* .then(() => console.log('Banner ad shown'))
* .catch(err => console.error('Error showing banner ad:', err));
* }
* });
*
*
* // Hide banner ad, but do not destroy it, so it can be shown later on
* // See destroyBannerView in order to hide and destroy banner ad
* this.admob.showBannerAd(false)
* .then(() => console.log('Banner ad hidden'))
* .catch(err => console.error('Error hiding banner ad:', err));
*
*
*
* // Request an interstitial ad, in order to be shown later on
* // It is possible to autoshow it via options parameter, see docs
* this.admob.requestInterstitialAd()
* .then(() => console.log('Interstitial ad loaded'))
* .catch(err => console.error('Error loading interstitial ad:', err));
*
*
* // Show an interstitial ad (requestInterstitialAd must be called before)
* this.admob.onAdLoaded().subscribe((ad) => {
* if (ad.adType === this.admob.AD_TYPE.INTERSTITIAL) {
* this.admob.showInterstitialAd()
* .then(() => console.log('Interstitial ad shown'))
* .catch(err => console.error('Error showing interstitial ad:', err));
* }
* });
*
*
* // Request a rewarded ad
* this.admob.requestRewardedAd()
* .then(() => console.log('Rewarded ad loaded'))
* .catch(err => console.error('Error loading rewarded ad:', err));
*
*
* // Show rewarded ad (requestRewardedAd must be called before)
* this.admob.onAdLoaded().subscribe((ad) => {
* if (ad.adType === this.admob.AD_TYPE.REWARDED) {
* this.admob.showRewardedAd()
* .then(() => console.log('Rewarded ad shown'))
* .catch(err => console.error('Error showing rewarded ad:', err));
* }
* });
*
*
* // Hide and destroy banner or interstitial ad
* this.admob.destroyBannerView()
* .then(() => console.log('Banner or interstitial ad destroyed'))
* .catch(err => console.error('Error destroying banner or interstitial ad:', err));
*
*
*
* // On Ad loaded event
* this.admob.onAdLoaded().subscribe((ad) => {
* if (ad.adType === this.admob.AD_TYPE.BANNER) {
* console.log('Banner ad is loaded');
* this.admob.showBannerAd();
* } else if (ad.adType === this.admob.AD_TYPE.INTERSTITIAL) {
* console.log('Interstitial ad is loaded');
* this.admob.showInterstitialAd();
* } else if (ad.adType === this.admob.AD_TYPE.REWARDED) {
* console.log('Rewarded ad is loaded');
* this.admob.showRewardedAd();
* }
* });
*
*
*
* // On ad failed to load
* this.admob.onAdFailedToLoad().subscribe(err => console.log('Error loading ad:', err));
*
*
*
* // On interstitial ad opened
* this.admob.onAdOpened().subscribe(() => console.log('Interstitial ad opened'));
*
*
*
* // On interstitial ad closed
* this.admob.onAdClosed().subscribe(() => console.log('Interstitial ad closed'));
*
*
*
* // On ad clicked and left application
* this.admob.onAdLeftApplication().subscribe(() => console.log('Ad lefted application'));
*
*
*
* // On user ad rewarded
* this.admob.onRewardedAd().subscribe(() => console.log('The user has been rewarded'));
*
*
*
* // On rewarded ad video started
* this.admob.onRewardedAdVideoStarted().subscribe(() => console.log('Rewarded ad vieo started'));
*
*
*
* // On rewarded ad video completed
* this.admob.onRewardedAdVideoCompleted().subscribe(() => console.log('Rewarded ad video completed'));
*
* ```
*/
@Plugin({
pluginName: 'AdMob',
plugin: 'cordova-admob',
pluginRef: 'admob',
repo: 'https://github.com/appfeel/admob-google-cordova',
platforms: ['Android', 'iOS', 'Browser'],
})
@Injectable()
export class Admob extends AwesomeCordovaNativePlugin {
/**
* This enum represents AdMob's supported ad sizes.
* Use one of these constants as adSize option when calling createBannerView
*
* @readonly
*/
@CordovaProperty()
readonly AD_SIZE: {
BANNER: string;
IAB_MRECT: string;
IAB_BANNER: string;
IAB_LEADERBOARD: string;
SMART_BANNER: string;
};
/**
* This enum represents AdMob's supported ad types
*
* @readonly
*/
@CordovaProperty()
readonly AD_TYPE: {
BANNER: string;
INTERSTITIAL: string;
REWARDED: string;
};
/**
* Set the options to start displaying ads.
* Although it is not required to call this method, as options can be specified in other methods, it is highly recommended
*
* @param options {AdmobOptions} Some param to configure something
* @returns {Promise<any>} Returns a promise that resolves when the options are set
*/
@Cordova()
setOptions(options: AdmobOptions | AdmobWebOptions): Promise<any> {
return;
}
/**
* Creates a new banner ad view. Call this method in order to be able to start showing banners
*
* @param options {AdmobOptions} (Optional) Setup options
* @returns {Promise<any>} Returns a promise that resolves when the banner view is created
*/
@Cordova()
createBannerView(options?: AdmobOptions | AdmobWebOptions): Promise<any> {
return;
}
/**
* Show banner ads. You must call createBannerView first, otherwise it will result in failure callback and no ads will be shown
*
* @param show {boolean} (Optional) Indicates whether to show or hide banner ads. Defaults to `true`
* @returns {Promise<any>} Returns a promise that resolves when the banner shown or hidden
*/
@Cordova()
showBannerAd(show?: boolean): Promise<any> {
return;
}
/**
* Hide and destroy banner view. Call this method when you want to destroy banner view.
* It is not necessary to call this method when the app closed, as it will be automatically called by the plugin
*/
@Cordova()
destroyBannerView() {}
/**
* Request an interstitial ad
* If `options.autoShowInterstitial` is set to `true` (default), the ad will automatically be displayed.
* Otherwise you need to subscribe to `onAdLoaded()` event and call `showInterstitialAd()` after it will be raised specifying that an interstitial ad is available.
* If you already called `requestInterstitialAd()` but the interstitial has never been shown, the successive calls to `requestInterstitialAd()` will result in the ad being inmediately available (the one that was obtained on the first call)
*
* @param options {AdmobOptions} (Optional) Setup options
* @returns {Promise<any>} Returns a promise that resolves when the interstitial ad is loaded
*/
@Cordova()
requestInterstitialAd(options?: AdmobOptions | AdmobWebOptions): Promise<any> {
return;
}
/**
* Show an interstitial ad. Call it after `requestInterstitialAd()` and `onAdLoaded()` event raised.
*
* @returns {Promise<any>} Returns a promise that resolves when the interstitial ad is shown
*/
@Cordova()
showInterstitialAd(): Promise<any> {
return;
}
/**
* Request an rewarded ad
* If `options.autoShowRewarded` is set to `true` (default), the ad will automatically be displayed.
* Otherwise you need to subscribe to `onAdLoaded()` enent and call `showRewardedAd()` after it will be raised specifying that a rewarded ad is available.
* If you already called `requestRewardedAd()` but the rewarded has never been shown, the successive calls to `requestRewardedAd()` will result in the ad being inmediately available (the one that was obtained on the first call)
*
* @param options {AdmobOptions} (Optional) Setup options
* @returns {Promise<any>} Returns a promise that resolves when the rewarded ad is loaded
*/
@Cordova()
requestRewardedAd(options?: AdmobOptions | AdmobWebOptions): Promise<any> {
return;
}
/**
* Show a rewarded ad
*
* @returns {Promise<any>} Returns a promise that resolves when the rewarded ad is shown
*/
@Cordova()
showRewardedAd(): Promise<any> {
return;
}
/**
* Called when an ad is received.
*
* WARNING*: only **ionic^4**. Older versions of ionic, use:
*
* ```js
* document.addEventListener(window.admob.events.onAdLoaded, () => { });
* ```
*
* Please refer to the documentation on https://admob-ionic.com/Events.
*
* @returns {Observable<AdMobEvent>} Returns an observable when an ad is received
*/
@Cordova({
eventObservable: true,
event: 'appfeel.cordova.admob.onAdLoaded',
element: document,
})
onAdLoaded(): Observable<AdMobEvent> {
return;
}
/**
* Called when an ad request failed.
*
* WARNING*: only **ionic^4**. Older versions of ionic, use:
*
* ```js
* document.addEventListener(window.admob.events.onAdFailedToLoad, () => { });
* ```
*
* Please refer to the documentation on https://admob-ionic.com/Events.
*
* @returns {Observable<AdMobEvent>} Returns an observable when an ad request is failed
*/
@Cordova({
eventObservable: true,
event: 'appfeel.cordova.admob.onAdFailedToLoad',
element: document,
})
onAdFailedToLoad(): Observable<AdMobEvent> {
return;
}
/**
* Called when an ad opens an overlay that covers the screen.
* Please note that onPause cordova event is raised when an interstitial is shown.
*
* WARNING*: only **ionic^4**. Older versions of ionic, use:
*
* ```js
* document.addEventListener(window.admob.events.onAdOpened, () => { });
* ```
*
* Please refer to the documentation on https://admob-ionic.com/Events.
*
* @returns {Observable<AdMobEvent>} Returns an observable when an ad is opened
*/
@Cordova({
eventObservable: true,
event: 'appfeel.cordova.admob.onAdOpened',
element: document,
})
onAdOpened(): Observable<AdMobEvent> {
return;
}
/**
* Called when the user is about to return to the application after clicking on an ad.
* Please note that onResume cordova event is raised when an interstitial is closed.
*
* WARNING*: only **ionic^4**. Older versions of ionic, use:
*
* ```js
* document.addEventListener(window.admob.events.onAdClosed, () => { });
* ```
*
* Please refer to the documentation on https://admob-ionic.com/Events.
*
* @returns {Observable<AdMobEvent>} Returns an observable when an ad is closed
*/
@Cordova({
eventObservable: true,
event: 'appfeel.cordova.admob.onAdClosed',
element: document,
})
onAdClosed(): Observable<AdMobEvent> {
return;
}
/**
* Called when the user leaves the application after clicking an ad (e.g., to go to the browser)
*
* @returns {Observable<AdMobEvent>} Returns an observable when an ad leaves the application.
*
* WARNING*: only **ionic^4**. Older versions of ionic, use:
*
* ```js
* document.addEventListener(window.admob.events.onAdLeftApplication, () => { });
* ```
*
* Please refer to the documentation on https://admob-ionic.com/Events.
* @returns {Observable<AdMobEvent>} Returns an observable when application is left due to an ad click
*/
@Cordova({
eventObservable: true,
event: 'appfeel.cordova.admob.onAdLeftApplication',
element: document,
})
onAdLeftApplication(): Observable<AdMobEvent> {
return;
}
/**
* Called when the user has been rewarded by an ad.
*
* WARNING*: only **ionic^4**. Older versions of ionic, use:
*
* ```js
* document.addEventListener(window.admob.events.onRewardedAd, () => { });
* ```
*
* Please refer to the documentation on https://admob-ionic.com/Events.
*
* @returns {Observable<AdMobEvent>} Returns an observable when the user rewards an ad
*/
@Cordova({
eventObservable: true,
event: 'appfeel.cordova.admob.onRewardedAd',
element: document,
})
onRewardedAd(): Observable<AdMobEvent> {
return;
}
/**
* Called when the video of a rewarded ad started.
*
* WARNING*: only **ionic^4**. Older versions of ionic, use:
*
* ```js
* document.addEventListener(window.admob.events.onRewardedAdVideoStarted, () => { });
* ```
*
* Please refer to the documentation on https://admob-ionic.com/Events.
*
* @returns {Observable<AdMobEvent>} Returns an observable when the video is started
*/
@Cordova({
eventObservable: true,
event: 'appfeel.cordova.admob.onRewardedAdVideoStarted',
element: document,
})
onRewardedAdVideoStarted(): Observable<AdMobEvent> {
return;
}
/**
* Called when the video of a rewarded ad has completed.
*
* WARNING*: only **ionic^4**. Older versions of ionic, use:
*
* ```js
* document.addEventListener(window.admob.events.onRewardedAdVideoCompleted, () => { });
* ```
*
* Please refer to the documentation on https://admob-ionic.com/Events.
*
* @returns {Observable<AdMobEvent>} Returns an observable when the video is completed
*/
@Cordova({
eventObservable: true,
event: 'appfeel.cordova.admob.onRewardedAdVideoCompleted',
element: document,
})
onRewardedAdVideoCompleted(): Observable<AdMobEvent> {
return;
}
} | the_stack |
import _ from "lodash";
import { ExportProvider } from "./exportProvider";
import { IProject, IAssetMetadata, ITag, IExportProviderOptions } from "../../models/applicationState";
import Guard from "../../common/guard";
import HtmlFileReader from "../../common/htmlFileReader";
import { itemTemplate, annotationTemplate, objectTemplate } from "./pascalVOC/pascalVOCTemplates";
import { interpolate } from "../../common/strings";
import os from "os";
import { splitTestAsset } from "./testAssetsSplitHelper";
interface IObjectInfo {
name: string;
xmin: number;
ymin: number;
xmax: number;
ymax: number;
}
interface IImageInfo {
width: number;
height: number;
objects: IObjectInfo[];
}
/**
* Export options for Pascal VOC Export Provider
*/
export interface IPascalVOCExportProviderOptions extends IExportProviderOptions {
/** The test / train split ratio for exporting data */
testTrainSplit?: number;
/** Whether or not to include unassigned tags in exported data */
exportUnassigned?: boolean;
}
/**
* @name - PascalVOC Export Provider
* @description - Exports a project into a Pascal VOC
*/
export class PascalVOCExportProvider extends ExportProvider<IPascalVOCExportProviderOptions> {
private imagesInfo = new Map<string, IImageInfo>();
constructor(project: IProject, options: IPascalVOCExportProviderOptions) {
super(project, options);
Guard.null(options);
}
/**
* Export project to PascalVOC
*/
public async export(): Promise<void> {
const allAssets = await this.getAssetsForExport();
const exportObject: any = { ...this.project };
exportObject.assets = _.keyBy(allAssets, (assetMetadata) => assetMetadata.asset.id);
// Create Export Folder
const exportFolderName = `${this.project.name.replace(/\s/g, "-")}-PascalVOC-export`;
await this.storageProvider.createContainer(exportFolderName);
await this.exportImages(exportFolderName, allAssets);
await this.exportPBTXT(exportFolderName, this.project);
await this.exportAnnotations(exportFolderName, allAssets);
// TestSplit && exportUnassignedTags are optional parameter in the UI Exporter configuration
const testSplit = (100 - (this.options.testTrainSplit || 80)) / 100;
await this.exportImageSets(
exportFolderName,
allAssets,
this.project.tags,
testSplit,
this.options.exportUnassigned,
);
}
private async exportImages(exportFolderName: string, allAssets: IAssetMetadata[]) {
// Create JPEGImages Sub Folder
const jpegImagesFolderName = `${exportFolderName}/JPEGImages`;
await this.storageProvider.createContainer(jpegImagesFolderName);
await allAssets.mapAsync(async (assetMetadata) => {
await this.exportSingleImage(jpegImagesFolderName, assetMetadata);
});
}
private async exportSingleImage(jpegImagesFolderName: string, assetMetadata: IAssetMetadata): Promise<void> {
try {
const arrayBuffer = await HtmlFileReader.getAssetArray(assetMetadata.asset);
const buffer = Buffer.from(arrayBuffer);
const imageFileName = `${jpegImagesFolderName}/${assetMetadata.asset.name}`;
// Write Binary
await this.storageProvider.writeBinary(imageFileName, buffer);
// Get Array of all Box shaped tag for the Asset
const tagObjects = this.getAssetTagArray(assetMetadata);
const imageInfo: IImageInfo = {
width: assetMetadata.asset.size ? assetMetadata.asset.size.width : 0,
height: assetMetadata.asset.size ? assetMetadata.asset.size.height : 0,
objects: tagObjects,
};
this.imagesInfo.set(assetMetadata.asset.name, imageInfo);
if (!assetMetadata.asset.size ||
assetMetadata.asset.size.width === 0 ||
assetMetadata.asset.size.height === 0) {
await this.updateImageSizeInfo(arrayBuffer, imageFileName, assetMetadata.asset.name);
}
} catch (err) {
// Ignore the error at the moment
// TODO: Refactor ExportProvider abstract class export() method
// to return Promise<object> with an object containing
// the number of files successfully exported out of total
console.log(`Error downloading asset ${assetMetadata.asset.path} - ${err}`);
}
}
private getAssetTagArray(element: IAssetMetadata): IObjectInfo[] {
const tagObjects = [];
element.regions.forEach((region) => {
region.tags.forEach((tagName) => {
const objectInfo: IObjectInfo = {
name: tagName,
xmin: region.boundingBox.left,
ymin: region.boundingBox.top,
xmax: region.boundingBox.left + region.boundingBox.width,
ymax: region.boundingBox.top + region.boundingBox.height,
};
tagObjects.push(objectInfo);
});
});
return tagObjects;
}
private async updateImageSizeInfo(imageBuffer: ArrayBuffer, imageFileName: string, assetName: string) {
// Get Base64
const image64 = btoa(new Uint8Array(imageBuffer).
reduce((data, byte) => data + String.fromCharCode(byte), ""));
if (image64.length < 10) {
// Ignore the error at the moment
// TODO: Refactor ExportProvider abstract class export() method
// to return Promise<object> with an object containing
// the number of files successfully exported out of total
console.log(`Image not valid ${imageFileName}`);
} else {
const assetProps = await HtmlFileReader.readAssetAttributesWithBuffer(image64);
const imageInfo = this.imagesInfo.get(assetName);
if (imageInfo && assetProps) {
imageInfo.width = assetProps.width;
imageInfo.height = assetProps.height;
} else {
console.log(`imageInfo for element ${assetName} not found (${assetProps})`);
}
}
}
private async exportPBTXT(exportFolderName: string, project: IProject) {
if (project.tags && project.tags.length > 0) {
// Save pascal_label_map.pbtxt
const pbtxtFileName = `${exportFolderName}/pascal_label_map.pbtxt`;
let id = 1;
const items = project.tags.map((element) => {
const params = {
id: (id++).toString(),
tag: element.name,
};
return interpolate(itemTemplate, params);
});
await this.storageProvider.writeText(pbtxtFileName, items.join(""));
}
}
private async exportAnnotations(exportFolderName: string, allAssets: IAssetMetadata[]) {
// Create Annotations Sub Folder
const annotationsFolderName = `${exportFolderName}/Annotations`;
await this.storageProvider.createContainer(annotationsFolderName);
try {
// Save Annotations
await this.imagesInfo.forEachAsync(async (imageInfo, imageName) => {
const imageFilePath = `${annotationsFolderName}/${imageName}`;
const assetFilePath = `${imageFilePath.substr(0, imageFilePath.lastIndexOf("."))
|| imageFilePath}.xml`;
const objectsXML = imageInfo.objects.map((o) => {
const params = {
name: o.name,
xmin: o.xmin.toString(),
ymin: o.ymin.toString(),
xmax: o.xmax.toString(),
ymax: o.ymax.toString(),
};
return interpolate(objectTemplate, params);
});
const params = {
fileName: imageName,
filePath: imageFilePath,
width: imageInfo.width.toString(),
height: imageInfo.height.toString(),
objects: objectsXML.join(""),
};
// Save Annotation File
await this.storageProvider.writeText(assetFilePath, interpolate(annotationTemplate, params));
});
} catch (err) {
console.log("Error writing Pascal VOC annotation file");
}
}
private async exportImageSets(
exportFolderName: string,
allAssets: IAssetMetadata[],
tags: ITag[],
testSplit: number,
exportUnassignedTags: boolean) {
if (!tags) {
return;
}
// Create ImageSets Sub Folder (Main ?)
const imageSetsFolderName = `${exportFolderName}/ImageSets`;
await this.storageProvider.createContainer(imageSetsFolderName);
const imageSetsMainFolderName = `${exportFolderName}/ImageSets/Main`;
await this.storageProvider.createContainer(imageSetsMainFolderName);
const assetUsage = new Map<string, Set<string>>();
const tagUsage = new Map<string, number>();
// Generate tag usage per asset
allAssets.forEach((assetMetadata) => {
const appliedTags = new Set<string>();
assetUsage.set(assetMetadata.asset.name, appliedTags);
if (assetMetadata.regions.length > 0) {
assetMetadata.regions.forEach((region) => {
tags.forEach((tag) => {
let tagInstances = tagUsage.get(tag.name) || 0;
if (region.tags.filter((tagName) => tagName === tag.name).length > 0) {
appliedTags.add(tag.name);
tagUsage.set(tag.name, tagInstances += 1);
}
});
});
}
});
if (testSplit > 0 && testSplit <= 1) {
const tags = this.project.tags;
const testAssets: string[] = splitTestAsset(allAssets, tags, testSplit);
await tags.forEachAsync(async (tag) => {
const tagInstances = tagUsage.get(tag.name) || 0;
if (!exportUnassignedTags && tagInstances === 0) {
return;
}
const testArray = [];
const trainArray = [];
assetUsage.forEach((tags, assetName) => {
let assetString = "";
if (tags.has(tag.name)) {
assetString = `${assetName} 1`;
} else {
assetString = `${assetName} -1`;
}
if (testAssets.find((am) => am === assetName)) {
testArray.push(assetString);
} else {
trainArray.push(assetString);
}
});
const testImageSetFileName = `${imageSetsMainFolderName}/${tag.name}_val.txt`;
await this.storageProvider.writeText(testImageSetFileName, testArray.join(os.EOL));
const trainImageSetFileName = `${imageSetsMainFolderName}/${tag.name}_train.txt`;
await this.storageProvider.writeText(trainImageSetFileName, trainArray.join(os.EOL));
});
} else {
// Save ImageSets
await tags.forEachAsync(async (tag) => {
const tagInstances = tagUsage.get(tag.name) || 0;
if (!exportUnassignedTags && tagInstances === 0) {
return;
}
const assetList = [];
assetUsage.forEach((tags, assetName) => {
if (tags.has(tag.name)) {
assetList.push(`${assetName} 1`);
} else {
assetList.push(`${assetName} -1`);
}
});
const imageSetFileName = `${imageSetsMainFolderName}/${tag.name}.txt`;
await this.storageProvider.writeText(imageSetFileName, assetList.join(os.EOL));
});
}
}
} | the_stack |
type AnyCallback = (...args: never[]) => void;
type NonCallbackKeys<T> = {
[K in keyof T]: T[K] extends AnyCallback ? never : K;
}[keyof T];
type OmitCallbacks<
T,
AdditionalKeys extends keyof T = never,
RemoveKeys extends keyof T = never
> = Pick<T, Exclude<NonCallbackKeys<T> | AdditionalKeys, RemoveKeys>>;
export type BenchmarkCallback = (
psdFileData: ArrayBuffer
) => BenchmarkMeasurements | Promise<BenchmarkMeasurements>;
export type BenchmarkTaskSetup = Readonly<{
libraryName: string;
benchmarkCallback: BenchmarkCallback;
}>;
type AppStateProperties = OmitCallbacks<AppState>;
// TODO: There needs to be an extra type of task: LoadPsdFileTask
export class AppState {
readonly tasks: readonly Task[];
readonly benchmarkResults: readonly BenchmarkResult[];
readonly currentTaskTrialMeasurements: readonly BenchmarkMeasurements[];
readonly options: BenchmarkOptions;
readonly psdFileName: string | null;
readonly psdFileData: ArrayBuffer | null;
readonly error: string | null;
readonly defaultPsdFileUrl: URL;
readonly defaultPsdFileData: ArrayBuffer | null;
constructor({
tasks,
benchmarkResults,
currentTaskTrialMeasurements,
options,
psdFileData,
psdFileName,
error,
defaultPsdFileUrl,
defaultPsdFileData,
}: AppStateProperties) {
this.tasks = Object.freeze([...tasks]);
this.benchmarkResults = Object.freeze([...benchmarkResults]);
this.currentTaskTrialMeasurements = Object.freeze([
...currentTaskTrialMeasurements,
]);
this.options = options;
this.psdFileName = psdFileName;
this.psdFileData = psdFileData;
this.error = error;
this.defaultPsdFileUrl = defaultPsdFileUrl;
this.defaultPsdFileData = defaultPsdFileData;
Object.freeze(this);
}
#update(properties: Partial<AppStateProperties>) {
const {
tasks = this.tasks,
benchmarkResults = this.benchmarkResults,
currentTaskTrialMeasurements = this.currentTaskTrialMeasurements,
options = this.options,
psdFileData = this.psdFileData,
psdFileName = this.psdFileName,
error = this.error,
defaultPsdFileUrl = this.defaultPsdFileUrl,
defaultPsdFileData = this.defaultPsdFileData,
} = properties;
return new AppState({
tasks,
benchmarkResults,
currentTaskTrialMeasurements,
options,
psdFileData,
psdFileName,
error,
defaultPsdFileUrl,
defaultPsdFileData,
});
}
isRunning() {
return this.error === null && this.tasks.length > 0;
}
isComplete() {
return this.error === null && this.tasks.length === 0;
}
getCompletedSubtaskCount() {
return (
(this.psdFileData !== null ? 1 : 0) +
this.currentTaskTrialMeasurements.length +
this.benchmarkResults.length * this.options.trialCount
);
}
getRemainingSubtaskCount() {
let subtaskCount = 0;
for (const task of this.tasks) {
subtaskCount +=
task.taskType === "BenchmarkTask" ? task.remainingTrialCount : 1;
}
return subtaskCount;
}
getTotalSubtaskCount() {
return this.getRemainingSubtaskCount() + this.getCompletedSubtaskCount();
}
getProgress() {
return this.getCompletedSubtaskCount() / this.getTotalSubtaskCount();
}
getCurrentTask() {
const currentTask = this.tasks[0];
if (!currentTask) {
throw new Error("Task queue is empty");
}
return currentTask;
}
/** Start a new run */
start(setups: readonly BenchmarkTaskSetup[], psdFile: File) {
const tasks = [
new LoadFileTask(psdFile),
...setups.map(
(setup) =>
new BenchmarkTask({
libraryName: setup.libraryName,
benchmarkCallback: setup.benchmarkCallback,
remainingTrialCount: this.options.trialCount,
})
),
];
return this.#update({
tasks,
currentTaskTrialMeasurements: [],
benchmarkResults: [],
psdFileName: psdFile.name,
psdFileData: null,
error: null,
});
}
startWithDefaultPsdFile(setups: readonly BenchmarkTaskSetup[]) {
if (!this.defaultPsdFileData) {
throw new Error("Default PSD file has not been loaded yet");
}
return this.#update({
tasks: setups.map(
(setup) =>
new BenchmarkTask({
libraryName: setup.libraryName,
benchmarkCallback: setup.benchmarkCallback,
remainingTrialCount: this.options.trialCount,
})
),
currentTaskTrialMeasurements: [],
benchmarkResults: [],
psdFileName: this.defaultPsdFileUrl.pathname,
psdFileData: this.defaultPsdFileData,
error: null,
});
}
async runNextSubtask() {
if (!this.isRunning()) {
throw new Error("Cannot run next trial because the app has halted");
}
const [currentTask, ...nextTasks] = this.tasks;
if (currentTask.taskType === "LoadFileTask") {
const psdFileData = await currentTask.file.arrayBuffer();
return this.#update({tasks: nextTasks, psdFileData});
}
// Handle BenchmarkTask
if (!this.psdFileData) {
throw new Error("Cannot run benchmark, PSD file data is not ready");
}
const [trialMeasurement, updatedTask] = await currentTask.runTrial(
this.psdFileData
);
const updatedTrialMeasurements = [
...this.currentTaskTrialMeasurements,
trialMeasurement,
];
if (updatedTask) {
// There are remaining trials in the current (updated) task
const updatedTasksToRun = [updatedTask, ...nextTasks];
return this.#update({
tasks: updatedTasksToRun,
currentTaskTrialMeasurements: updatedTrialMeasurements,
});
} else {
// Current task has finished. Evict it from the queue and combine results
const updatedTaskResults = [
...this.benchmarkResults,
combineTrialMeasurements(
currentTask.libraryName,
updatedTrialMeasurements
),
];
return this.#update({
tasks: nextTasks,
currentTaskTrialMeasurements: [],
benchmarkResults: updatedTaskResults,
});
}
}
updateOptions(newOptions: Partial<BenchmarkOptionsProperties>) {
if (this.isRunning()) {
throw new Error(`Cannot change options while running`);
}
const {
trialCount = this.options.trialCount,
shouldApplyOpacity = this.options.shouldApplyOpacity,
preferDefaultPsd = this.options.preferDefaultPsd,
} = newOptions;
return this.#update({
options: new BenchmarkOptions({
trialCount,
shouldApplyOpacity,
preferDefaultPsd,
}),
});
}
setError(error: unknown) {
return this.#update({
error: error === null ? error : String(error),
});
}
async loadDefaultPsdFile() {
if (this.defaultPsdFileData) {
throw new Error(`${this.defaultPsdFileUrl} has already been loaded`);
}
// eslint-disable-next-line compat/compat
const response = await fetch(String(this.defaultPsdFileUrl));
return this.#update({
defaultPsdFileData: await response.arrayBuffer(),
});
}
}
export const initialAppState = new AppState({
tasks: [],
benchmarkResults: [],
currentTaskTrialMeasurements: [],
options: {trialCount: 3, shouldApplyOpacity: false, preferDefaultPsd: true},
psdFileName: null,
psdFileData: null,
error: null,
// Webpack will resolve this as a resource asset
// eslint-disable-next-line compat/compat
defaultPsdFileUrl: new URL("../../node/example.psd", import.meta.url),
defaultPsdFileData: null,
});
export type Task = LoadFileTask | BenchmarkTask;
class LoadFileTask {
readonly taskType = "LoadFileTask";
readonly file: File;
constructor(file: File) {
this.file = file;
Object.freeze(this);
}
}
type BenchmarkTaskProperties = OmitCallbacks<
BenchmarkTask,
"benchmarkCallback",
"taskType"
>;
class BenchmarkTask {
readonly taskType = "BenchmarkTask";
readonly libraryName: string;
readonly benchmarkCallback: BenchmarkCallback;
readonly remainingTrialCount: number;
constructor({
libraryName,
benchmarkCallback,
remainingTrialCount,
}: BenchmarkTaskProperties) {
if (
!(Number.isSafeInteger(remainingTrialCount) && remainingTrialCount > 0)
) {
throw new Error(
`remainingTrialCount must be a positive safe integer (got ${remainingTrialCount})`
);
}
this.libraryName = libraryName;
this.benchmarkCallback = benchmarkCallback;
this.remainingTrialCount = remainingTrialCount;
Object.freeze(this);
}
/**
* Run a trial and return a tuple of `[trialMeasurement, updatedTask]`.
* `updatedTask` may be `null` if this is the last trial for this task.
*/
async runTrial(psdFileData: ArrayBuffer) {
const trialMeasurement = await this.benchmarkCallback(psdFileData);
const updatedTask =
this.remainingTrialCount === 1
? null
: new BenchmarkTask({
libraryName: this.libraryName,
benchmarkCallback: this.benchmarkCallback,
remainingTrialCount: this.remainingTrialCount - 1,
});
return [trialMeasurement, updatedTask] as const;
}
}
export class BenchmarkResult {
readonly libraryName: string;
readonly measurements: BenchmarkMeasurements;
constructor({libraryName, measurements}: OmitCallbacks<BenchmarkResult>) {
this.libraryName = libraryName;
this.measurements = measurements;
}
}
export class BenchmarkMeasurements {
readonly parseTime: number;
readonly imageDecodeTime: number;
readonly layerDecodeTime: number;
constructor({
parseTime,
imageDecodeTime,
layerDecodeTime,
}: OmitCallbacks<BenchmarkMeasurements>) {
if (!(parseTime >= 0)) {
throw new Error(
`parseTime must be a nonnegative number (got ${parseTime})`
);
}
if (!(imageDecodeTime >= 0)) {
throw new Error(
`imageDecodeTime must be a nonnegative number (got ${imageDecodeTime})`
);
}
if (!(layerDecodeTime >= 0)) {
throw new Error(
`layerDecodeTime must be a nonnegative number (got ${layerDecodeTime})`
);
}
this.parseTime = parseTime;
this.imageDecodeTime = imageDecodeTime;
this.layerDecodeTime = layerDecodeTime;
Object.freeze(this);
}
}
function combineTrialMeasurements(
libraryName: string,
trialMeasurements: readonly BenchmarkMeasurements[]
) {
if (!(trialMeasurements.length > 0)) {
throw new Error(`trialMeasurements is empty`);
}
let totalParseTime = 0;
let totalImageDecodeTime = 0;
let totalLayerDecodeTime = 0;
for (const result of trialMeasurements) {
totalParseTime += result.parseTime;
totalImageDecodeTime += result.imageDecodeTime;
totalLayerDecodeTime += result.layerDecodeTime;
}
// Compute average of all measurements
return new BenchmarkResult({
libraryName,
measurements: new BenchmarkMeasurements({
parseTime: totalParseTime / trialMeasurements.length,
imageDecodeTime: totalImageDecodeTime / trialMeasurements.length,
layerDecodeTime: totalLayerDecodeTime / trialMeasurements.length,
}),
});
}
export class BenchmarkOptions {
readonly trialCount: number;
/** Whether to apply opacity when decoding image data */
readonly shouldApplyOpacity: boolean;
readonly preferDefaultPsd: boolean;
constructor({
trialCount,
shouldApplyOpacity,
preferDefaultPsd,
}: BenchmarkOptionsProperties) {
if (!(Number.isSafeInteger(trialCount) && trialCount > 0)) {
throw new Error(
`trialCount must be a positive safe integer (got ${trialCount})`
);
}
this.trialCount = trialCount;
this.shouldApplyOpacity = shouldApplyOpacity;
this.preferDefaultPsd = preferDefaultPsd;
Object.freeze(this);
}
}
export type BenchmarkOptionsProperties = OmitCallbacks<BenchmarkOptions>; | the_stack |
import React from "react";
import rpcService from "../../../app/service/rpc_service";
import { User } from "../../../app/auth/auth_service";
import SidebarNodeComponent from "./code_sidebar_node";
import { Subscription } from "rxjs";
import * as monaco from "monaco-editor";
import { Octokit } from "octokit";
import DiffMatchPatch from "diff-match-patch";
import { createPullRequest } from "octokit-plugin-create-pull-request";
const MyOctokit = Octokit.plugin(createPullRequest);
interface Props {
user: User;
hash: string;
path: string;
search: URLSearchParams;
}
interface State {
owner: string;
repo: string;
repoResponse: any;
treeShaToExpanded: Map<string, boolean>;
treeShaToChildrenMap: Map<string, any[]>;
treeShaToPathMap: Map<string, string>;
fullPathToModelMap: Map<string, any>;
originalFileContents: string;
currentFilePath: string;
changes: Map<string, string>;
pathToIncludeChanges: Map<string, boolean>;
requestingReview: boolean;
}
const dmp = new DiffMatchPatch.diff_match_patch();
// TODO(siggisim): Implement build and test
// TODO(siggisim): Add links to the code editor from anywhere we reference a repo
// TODO(siggisim): Add branch / workspace selection
// TODO(siggisim): Add currently selected file name
// TODO(siggisim): Add some form of search
export default class CodeComponent extends React.Component<Props> {
props: Props;
state: State = {
owner: "",
repo: "",
repoResponse: undefined,
treeShaToExpanded: new Map<string, boolean>(),
treeShaToChildrenMap: new Map<string, any[]>(),
treeShaToPathMap: new Map<string, string>(),
fullPathToModelMap: new Map<string, any>(),
originalFileContents: "",
currentFilePath: "",
changes: new Map<string, string>(),
pathToIncludeChanges: new Map<string, boolean>(),
requestingReview: false,
};
editor: any;
codeViewer = React.createRef<HTMLDivElement>();
octokit: any;
subscription: Subscription;
componentWillMount() {
document.title = `Code | BuildBuddy`;
this.octokit = new MyOctokit({
auth: this.props.user.selectedGroup.githubToken,
});
this.fetchCode();
this.subscription = rpcService.events.subscribe({
next: (name) => name === "refresh" && this.fetchCode(),
});
}
handleWindowResize() {
this.editor?.layout();
}
componentDidMount() {
window.addEventListener("resize", () => this.handleWindowResize());
// TODO(siggisim): select default file based on url
this.editor = monaco.editor.create(this.codeViewer.current, {
value: ["// Welcome to BuildBuddy Code!", "", "// Click on a file to the left to get start editing."].join("\n"),
theme: "vs",
});
this.editor.onDidChangeModelContent(() => {
this.handleContentChanged();
});
}
handleContentChanged() {
if (this.state.originalFileContents === this.editor.getValue()) {
this.state.changes.delete(this.state.currentFilePath);
this.state.pathToIncludeChanges.delete(this.state.currentFilePath);
} else if (this.state.currentFilePath) {
if (!this.state.changes.get(this.state.currentFilePath)) {
this.state.pathToIncludeChanges.set(this.state.currentFilePath, true);
}
this.state.changes.set(this.state.currentFilePath, this.editor.getValue());
}
this.setState({ changes: this.state.changes });
console.log(this.state.changes);
// TODO(siggisim): serialize these changes to localStorage or to server and pull them back out.
}
componentWillUnmount() {
window.removeEventListener("resize", () => this.handleWindowResize());
this.subscription?.unsubscribe();
this.editor?.dispose();
}
componentDidUpdate(prevProps: Props) {
if (
this.props.hash !== prevProps.hash ||
this.props.search != prevProps.search ||
this.props.path != this.props.path
) {
this.fetchCode();
}
}
fetchCode() {
let groups = this.props.path?.match(/\/code\/(?<owner>.*)\/(?<repo>.*)/)?.groups;
if (!groups?.owner || !groups.repo) {
this.handleRepoClicked();
return;
}
this.setState({ owner: groups?.owner || "buildbuddy-io", repo: groups?.repo || "buildbuddy" }, () => {
this.octokit.request(`/repos/${this.state.owner}/${this.state.repo}/git/trees/master`).then((response: any) => {
console.log(response);
this.setState({ repoResponse: response });
});
});
}
// TODO(siggisim): Support deleting files
// TODO(siggisim): Support moving files around
// TODO(siggisim): Support renaming files
// TODO(siggisim): Support right click file context menus
// TODO(siggisim): Support tabs
// TODO(siggisim): Remove the use of all `any` types
handleFileClicked(node: any, fullPath: string) {
if (node.type === "tree") {
if (this.state.treeShaToExpanded.get(node.sha)) {
this.state.treeShaToExpanded.set(node.sha, false);
this.setState({ treeShaToExpanded: this.state.treeShaToExpanded });
return;
}
this.octokit
.request(`/repos/${this.state.owner}/${this.state.repo}/git/trees/${node.sha}`)
.then((response: any) => {
this.state.treeShaToExpanded.set(node.sha, true);
this.state.treeShaToChildrenMap.set(node.sha, response.data.tree);
this.setState({
treeShaToChildrenMap: this.state.treeShaToChildrenMap,
treeShaToPathMap: this.state.treeShaToPathMap,
});
console.log(response);
});
return;
}
this.octokit.rest.git
.getBlob({
owner: this.state.owner,
repo: this.state.repo,
file_sha: node.sha,
})
.then((response: any) => {
console.log(response);
let fileContents = atob(response.data.content);
this.setState({ currentFilePath: fullPath, originalFileContents: fileContents, changes: this.state.changes });
let model = this.state.fullPathToModelMap.get(fullPath);
if (!model) {
model = monaco.editor.createModel(fileContents, undefined, monaco.Uri.file(fullPath));
this.state.fullPathToModelMap.set(fullPath, model);
}
this.editor.setModel(model);
});
}
// TODO(siggisim): Make the build button work
handleBuildClicked() {
console.log("original:");
console.log(this.state.originalFileContents);
console.log("new:");
console.log(this.editor.getValue());
console.log("patch:");
if (this.state.originalFileContents && this.editor.getValue()) {
console.log(dmp.patch_toText(dmp.patch_make(this.state.originalFileContents, this.editor.getValue())));
}
alert(dmp.patch_toText(dmp.patch_make(this.state.originalFileContents, this.editor.getValue())));
alert("Coming soon!");
}
// TODO(siggisim): Implement a test button
handleTestClicked() {
this.handleBuildClicked();
}
async handleReviewClicked() {
this.setState({ requestingReview: true });
let filteredEntries = Array.from(this.state.changes.entries()).filter(
([key, value]) => this.state.pathToIncludeChanges.get(key) // Only include checked changes
);
let filenames = filteredEntries.map(([key, value]) => key).join(", ");
let response = await this.octokit.createPullRequest({
owner: this.state.owner,
repo: this.state.repo,
title: `Quick fix of ${filenames}`,
body: `Quick fix of ${filenames} using BuildBuddy Code`,
head: `quick-fix-${Math.floor(Math.random() * 10000)}`,
changes: [
{
files: Object.fromEntries(
filteredEntries.map(([key, value]) => [key, { content: btoa(value), encoding: "base64" }]) // Convert to base64 for github to support utf-8
),
commit: `Quick fix of ${this.state.currentFilePath} using BuildBuddy Code`,
},
],
});
this.setState({ requestingReview: false });
window.open(response.data.html_url, "_blank");
console.log(response);
}
handleChangeClicked(fullPath: string) {
this.setState({ currentFilePath: fullPath });
this.editor.setModel(this.state.fullPathToModelMap.get(fullPath));
}
// TODO(siggisim): Enable users to revert individual changes
handleCheckboxClicked(fullPath: string) {
this.state.pathToIncludeChanges.set(fullPath, !this.state.pathToIncludeChanges.get(fullPath));
this.setState({ pathToIncludeChanges: this.state.pathToIncludeChanges });
}
// TODO(siggisim): Implement delete
handleDeleteClicked(fullPath: string) {}
handleNewFileClicked() {
let fileName = prompt("File name:");
if (fileName) {
let fileContents = "// Your code here";
let model = this.state.fullPathToModelMap.get(fileName);
if (!model) {
model = monaco.editor.createModel(fileContents, undefined, monaco.Uri.file(fileName));
this.state.fullPathToModelMap.set(fileName, model);
}
this.setState({ currentFilePath: fileName, originalFileContents: "", changes: this.state.changes }, () => {
this.editor.setModel(model);
this.handleContentChanged();
});
}
}
handleRepoClicked() {
let regex = /(?<owner>.*)\/(?<repo>.*)/;
const groups = prompt("Enter a github repo to edit (i.e. buildbuddy-io/buildbuddy):").match(regex)?.groups;
if (!groups?.owner || !groups?.repo) {
alert("Repo not found!");
this.handleRepoClicked();
}
let path = `/code/${groups?.owner}/${groups?.repo}`;
if (!this.state.owner || !this.state.repo) {
window.history.pushState({ path: path }, "", path);
} else {
window.location.href = path;
}
}
handleGitHubClicked() {
const params = new URLSearchParams({
group_id: this.props.user?.selectedGroup?.id,
redirect_url: window.location.href,
});
window.location.href = `/auth/github/link/?${params}`;
}
// TODO(siggisim): Make the menu look nice
// TODO(siggisim): Make sidebar look nice
// TODO(siggisim): Make the diff view look nicer
render() {
setTimeout(() => {
this.editor?.layout();
}, 0);
// TODO(siggisim): Make menu less cluttered
return (
<div className="code-editor">
<div className="code-menu">
<div className="code-menu-logo">
<a href="/">
<img alt="BuildBuddy Code" src="/image/logo_dark.svg" className="logo" /> Code{" "}
<img src="/image/code.svg" className="code-logo" />
</a>
</div>
<div className="code-menu-actions">
{!this.props.user.selectedGroup.githubToken && (
<button onClick={this.handleGitHubClicked.bind(this)}>🔗 Link GitHub</button>
)}
<button onClick={this.handleRepoClicked.bind(this)}>👩💻 Repo</button>
<button onClick={this.handleNewFileClicked.bind(this)}>🌱 File</button>
{/* <button onClick={this.handleDeleteClicked.bind(this)}>❌ Delete</button> */}
<button onClick={this.handleBuildClicked.bind(this)}>🏗️ Build</button>
<button onClick={this.handleTestClicked.bind(this)}>🧪 Test</button>
</div>
</div>
<div className="code-main">
<div className="code-sidebar">
{this.state.repoResponse &&
this.state.repoResponse.data.tree.map((node: any) => (
<SidebarNodeComponent
node={node}
treeShaToExpanded={this.state.treeShaToExpanded}
treeShaToChildrenMap={this.state.treeShaToChildrenMap}
handleFileClicked={this.handleFileClicked.bind(this)}
fullPath={node.path}
/>
))}
</div>
<div className="code-container">
<div className="code-viewer-container">
<div className="code-viewer" ref={this.codeViewer} />
</div>
{this.state.changes.size > 0 && (
<div className="code-diff-viewer">
<div className="code-diff-viewer-title">
Changes{" "}
<button
disabled={this.state.requestingReview}
className="request-review-button"
onClick={this.handleReviewClicked.bind(this)}>
{this.state.requestingReview ? "⌛ Requesting..." : "✋ Request Review"}
</button>
</div>
{Array.from(this.state.changes.keys()).map((fullPath) => (
<div className="code-diff-viewer-item" onClick={() => this.handleChangeClicked(fullPath)}>
<input
checked={this.state.pathToIncludeChanges.get(fullPath)}
onChange={(event) => this.handleCheckboxClicked(fullPath)}
type="checkbox"
/>{" "}
{fullPath}
</div>
))}
</div>
)}
</div>
</div>
</div>
);
}
}
// @ts-ignore
self.MonacoEnvironment = {
getWorkerUrl: function (workerId: string, label: string) {
// TODO(siggisim): add language support i.e.
//https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.25.2/min/vs/basic-languages/go/go.min.js
return `data:text/javascript;charset=utf-8,${encodeURIComponent(`
self.MonacoEnvironment = {
baseUrl: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.25.2/min/'
};
importScripts('https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.25.2/min/vs/base/worker/workerMain.js');`)}`;
},
}; | the_stack |
import { any, array, binary, BinaryShape, boolean, EnumShape, integer, LiteralShape, never, NeverShape, nothing, NothingShape, number, ShapeGuards, ShapeVisitor, timestamp, Value } from '@punchcard/shape';
import { AnyShape, ArrayShape, BoolShape, IntegerShape, MapShape, NumberShape, SetShape, Shape, StringShape, TimestampShape, TypeShape } from '@punchcard/shape';
import { string } from '@punchcard/shape';
import { FunctionArgs, FunctionShape } from '@punchcard/shape/lib/function';
import { IsInstance } from '@punchcard/shape/lib/is-instance';
import { UnionShape } from '@punchcard/shape/lib/union';
import { VExpression } from './expression';
import { ElseBranch, forLoop, IfBranch, stash } from './statement';
import { $util } from './util';
import { VTL, vtl } from './vtl';
const VObjectType = Symbol.for('VObjectType');
const VObjectExpr = Symbol.for('VObjectExpr');
function weakMap(): WeakMap<any, {
type: Shape;
expr: VExpression;
}> {
if (!(global as any)[VObjectType]) {
(global as any)[VObjectType] = new WeakMap();
}
return (global as any)[VObjectType];
}
export class VObject<T extends Shape = Shape> {
constructor(type: T, expr: VExpression) {
weakMap().set(this, {
type,
expr
});
}
public get [VObjectType](): T {
return weakMap().get(this)!.type as T;
}
public get [VObjectExpr](): VExpression {
return weakMap().get(this)!.expr;
}
public hashCode(): VInteger {
return new VInteger(VExpression.call(this, 'hashCode', []));
}
public as<T extends Shape>(t: T): VObject.Of<T> {
return VObject.fromExpr(t, this[VObjectExpr]);
}
public notEquals(other: this | Value.Of<T>): VBool {
return new VBool(VExpression.concat(
this, ' != ', VObject.isObject(other) ? other : VExpression.json(other)
));
}
public equals(other: this | Value.Of<T>): VBool {
return new VBool(VExpression.concat(
this, ' == ', VObject.isObject(other) ? other : VExpression.json(other)
));
}
}
export namespace VObject {
export function *of<T extends Shape>(type: T, value: VObject.Like<T>): VTL<VObject.Of<T>> {
if (VExpression.isExpression(value)) {
return VObject.fromExpr(type, value);
}
if (ShapeGuards.isAnyShape(type)) {
// TODO: support any
throw new Error(`unsupported VTL type: any`);
}
if (VObject.isObject(value)) {
return value;
} else if (ShapeGuards.isArrayShape(type) || ShapeGuards.isSetShape(type)) {
const arr: VObject = yield* vtl(type)`[]`;
for (const item of (value as Shape[])) {
yield* vtl`${arr}.add(${yield* of(type.Items, item)}`;
}
return arr as VObject.Of<T>;
} else if (ShapeGuards.isRecordShape(type)) {
const record: VObject = yield* vtl(type)`{}`;
if (type.FQN !== undefined) {
yield* vtl`$util.qr(${record}.put("__typename", "${type.FQN!}"))`;
}
for (const [fieldName, fieldType] of Object.entries(type.Members)) {
const fieldValue = (value as any)[fieldName];
if (fieldValue === undefined) {
console.log(fieldName, fieldValue, value);
}
yield* vtl`$util.qr(${record}.put("${fieldName}", ${yield* of(fieldType, fieldValue)}))`;
}
return record as VObject.Of<T>;
} else if (ShapeGuards.isMapShape(type)) {
const fieldType = type.Items;
const map: VObject = yield* vtl(type)`{}`;
for (const [fieldName, fieldValue] of Object.entries(value)) {
yield* vtl`$util.qr(${map}.put("${fieldName}", ${yield* of(fieldType, fieldValue)}))`;
}
return map as VObject.Of<T>;
} else if (ShapeGuards.isUnionShape(type)) {
const itemType = type.Items.find(item => isLike(item, value));
if (itemType) {
// write to VTL using the item's type
const itemValue = yield* of(itemType, value);
// return an instance of the union
return VObject.fromExpr(type as T, VObject.getExpr(itemValue)) as VObject.Of<T>;
}
console.log(type);
console.log(value, typeof value);
throw new Error(`value did not match item in the UnionShape: ${type.Items.map(i => i.Kind).join(',')}`);
}
// stringify primitives
try {
const str =
ShapeGuards.isLiteralShape(type) ? JSON.stringify(type.Value) :
ShapeGuards.isNumberShape(type) ? (value as number).toString(10) :
ShapeGuards.isTimestampShape(type) ? (value as Date).toISOString() :
(value as any).toString();
return yield* vtl(type)`${str}`;
} catch (err) {
console.error(err);
console.log(value);
throw err;
}
}
export function isLike<T extends Shape>(shape: T, value: any): value is VObject.Like<T> {
if (VObject.isObject(value)) {
}
return (
ShapeGuards.isBoolShape(shape) ? typeof value === 'boolean' :
ShapeGuards.isNumberShape(shape) ? typeof value === 'number' :
ShapeGuards.isStringShape(shape) ? typeof value === 'string' :
ShapeGuards.isEnumShape(shape) ? typeof value === 'string' && IsInstance.of(shape)(value) :
ShapeGuards.isNothingShape(shape) ? typeof value === 'undefined' :
ShapeGuards.isUnionShape(shape) ? shape.Items.find(item => isLike(item, value)) !== undefined :
ShapeGuards.isMapShape(shape) ?
typeof value === 'object' &&
Object.values(value).map(field => isLike(shape.Items, field)).reduce((a, b) => a && b, true) :
ShapeGuards.isCollectionShape(shape) ?
Array.isArray(value) &&
Object.values(value).map(field => isLike(shape.Items, field)).reduce((a, b) => a && b, true) :
ShapeGuards.isRecordShape(shape) ?
typeof value === 'object' &&
Object.entries(shape.Members).map(([name, field]) => isLike(field, value[name])).reduce((a, b) => a && b, false) :
false
);
}
export function fromExpr<T extends Shape>(type: T, expr: VExpression): VObject.Of<T> {
const shape: Shape = VObject.isObject(type) ? getType(type) : type as Shape;
return shape.visit(Visitor.defaultInstance as any, expr) as any;
}
const _global = Symbol.for('VObject');
function _weakMap(): WeakMap<VObject, {
type: Shape;
expr: VExpression
}> {
const g = global as any;
if (g[_global] === undefined) {
g[_global] = new WeakMap();
}
return g[_global];
}
export function assertIsVObject(a: any): asserts a is VObject {
if (!_weakMap().has(a)) {
const err = new Error(`no entry in global weakmap for VObject`);
console.error('object is not a VObject', a, err);
throw err;
}
}
export function getType<T extends VObject>(t: T): TypeOf<T> {
return t[VObjectType] as TypeOf<T>;
}
export function getExpr<T extends VObject>(t: T): VExpression {
return t[VObjectExpr];
}
export function NewType<T extends Shape>(type: T): new(expr: VExpression) => VObject<T> {
return class extends VObject<T> {
constructor(expr: VExpression) {
super(type, expr);
}
};
}
export type TypeOf<T extends VObject> = T extends VObject<infer S> ? S : never;
export function isObject(a: any): a is VObject {
return a && a[VObjectExpr] !== undefined;
}
export function isList(a: any): a is VList {
return VObject.isObject(a) && ShapeGuards.isArrayShape(a[VObjectType]);
}
// export type ShapeOf<T extends VObject> = T extends VObject<infer I> ? I : never;
export type Of<T extends Shape> =
T extends TypeShape ? VRecord<T> & {
[field in keyof T['Members']]: Of<T['Members'][field]>;
} :
T extends ArrayShape<infer I> ? VList<Of<I>> :
T extends SetShape<infer I> ? VList<Of<I>> :
T extends MapShape<infer I> ? VMap<Of<I>> : // maps are not supported in GraphQL
T extends BoolShape ? VBool :
T extends AnyShape ? VAny :
T extends IntegerShape ? VInteger :
T extends NumberShape ? VFloat :
T extends StringShape ? VString :
T extends TimestampShape ? VTimestamp :
T extends UnionShape<infer U> ? VUnion<Of<U[Extract<keyof U, number>]>> :
T extends NothingShape ? VNothing :
T extends EnumShape ? VEnum<T> :
VObject<T>
;
/**
* Object that is "like" a VObject for some Shape.
*
* Like meaning that is either an expression, or a collection
* of expressions that share the structure of the target type.
*/
export type Like<T extends Shape> = VObject.Of<T> | Value.Of<T> | (
T extends TypeShape<infer M> ? {
[m in keyof M]: Like<M[m]>;
} :
T extends ArrayShape<infer I> ? Like<I>[] :
T extends SetShape<infer I> ? Like<I>[] :
T extends MapShape<infer I> ? {
[key: string]: Like<I>;
} :
T extends UnionShape<infer I> ? VUnion<VObject.Of<I[Extract<keyof I, number>]>> | {
[i in Extract<keyof I, number>]: Like<I[i]>;
}[Extract<keyof I, number>] :
VObject.Of<T> | Value.Of<T>
);
}
export const IDTrait = {
graphqlType: 'ID'
} as const;
export const ID = string.apply(IDTrait);
export class VAny extends VObject.NewType(any) {}
const VNumeric = <N extends NumberShape>(type: N) => class extends VObject.NewType(type) {
// public multiply(value: VInteger): VTL<> {
// }
public *minus(value: VObject.Like<N>): VTL<this> {
return (yield* stash(VObject.fromExpr(type, VExpression.concat(
this, ' - ', VObject.isObject(value) ? value : value.toString(10)
)))) as any as this;
}
public toString(): VString {
return new VString(VExpression.concat(
'"', this, '"',
));
}
};
export class VInteger extends VNumeric<IntegerShape>(integer) {}
export class VFloat extends VNumeric<NumberShape>(number) {}
export class VNothing extends VObject.NewType(nothing) {}
export class VNever extends VObject.NewType(never) {}
export class VBinary extends VObject.NewType(binary) {}
export class VBool extends VObject.NewType(boolean) {
public static not(a: VBool): VBool {
return new VBool(VExpression.concat('!', a));
}
public static and(...bs: VBool[]): VBool {
return VBool.operator('&&', bs);
}
public static or(...bs: VBool[]): VBool {
return VBool.operator('||', bs);
}
private static operator(op: '&&' | '||', xs: VBool[]): VBool {
return new VBool(VExpression.concat(
'(',
...xs
.map((x, i) => i === 0 ? [x] : [op, x])
.reduce((a, b) => a.concat(b)),
')'
));
}
public not(): VBool {
return VBool.not(this);
}
public and(x: VBool, ...xs: VBool[]): VBool {
return VBool.and(this, x, ...xs);
}
public or(x: VBool, ...xs: VBool[]): VBool {
return VBool.or(this, x, ...xs);
}
}
function cleanArgs(...args: any[]): any[] {
return args.filter(a => a !== undefined);
}
export interface VString {
/**
* Returns a hash code for this string. The hash code for a String object is computed as:
* ```java
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* ```
* using int arithmetic, where s[i] is the ith character of the string, n is the length
* of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)
*/
hashCode(): VInteger;
}
export class VStringLike<T extends StringShape | EnumShape> extends VObject<T> {
/**
* Compares two strings lexicographically. The comparison is based on the Unicode value
* of each character in the strings. The character sequence represented by this String
* object is compared lexicographically to the character sequence represented by the
* argument string. The result is a negative integer if this String object lexicographically
* precedes the argument string. The result is a positive integer if this String object
* lexicographically follows the argument string. The result is zero if the strings are
* equal; compareTo returns `0` exactly when the `equals(Object)` method would return `true`.
*
* This is the definition of lexicographic ordering. If two strings are different, then
* either they have different characters at some index that is a valid index for both
* strings, or their lengths are different, or both. If they have different characters
* at one or more index positions, let k be the smallest such index; then the string
* whose character at position k has the smaller value, as determined by using the `<`
* operator, lexicographically precedes the other string. In this case, `compareTo`
* returns the difference of the two character values at position k in the two string
* -- that is, the value:
*
* ```java
* this.charAt(k)-anotherString.charAt(k)
* ```
* If there is no index position at which they differ, then the shorter string lexicographically
* precedes the longer string. In this case, compareTo returns the difference of the lengths of
* the strings -- that is, the value:
* ```java
* this.length()-anotherString.length()
* ```
* @param anotherString the String to be compared.
* @returns the value `0` if the argument string is equal to this string; a value less
* than `0` if this string is lexicographically less than the string argument;
* and a value greater than 0 if this string is lexicographically greater
* than the string argument.
*/
public compareTo(anotherString: string | VString): VBool {
return new VBool(VExpression.call(this, 'compareTo', [anotherString]));
}
/**
* Compares two strings lexicographically, ignoring case differences. This method returns
* an integer whose sign is that of calling compareTo with normalized versions of the
* strings where case differences have been eliminated by calling
* `Character.toLowerCase(Character.toUpperCase(character))`on each character.
*
* Note that this method does not take locale into account, and will result in an
* unsatisfactory ordering for certain locales. The `java.text` package provides collators
* to allow locale-sensitive ordering.
*
* @param anotherString the String to be compared.
* @returns a negative integer, zero, or a positive integer as the specified String
* is greater than, equal to, or less than this String, ignoring case considerations.
*/
public compareToIgnoreCase(anotherString: string | VString): VBool {
return new VBool(VExpression.call(this, 'compareToIgnoreCase', [anotherString]));
}
/**
* Concatenates the specified string to the end of this string.
* If the length of the argument string is 0, then this String object is returned.
* Otherwise, a new String object is created, representing a character sequence
* that is the concatenation of the character sequence represented by this String
* object and the character sequence represented by the argument string.
*
* Examples:
* ```
* "cares".concat("s") // returns "caress"
* "to".concat("get").concat("her") // returns "together"
* ```
* @param str the String that is concatenated to the end of this String.
* @returns a string that represents the concatenation of this object's characters
* followed by the string argument's characters.
*/
public concat(str: string | VString): VString {
return new VString(VExpression.call(this, 'concat', [str]));
}
/**
* Tests if this string ends with the specified suffix.
* @param suffix the suffix.
* @returns true if the character sequence represented by the argument is a suffix
* of the character sequence represented by this object; false otherwise.
* Note that the result will be true if the argument is the empty string
* or is equal to this String object as determined by the `equals(Object)`
* method.
*/
public endsWith(suffix: string | VString): VBool {
return new VBool(VExpression.call(this, 'endsWith', [suffix]));
}
/**
* Compares this String to another String, ignoring case considerations. Two strings
* are considered equal ignoring case if they are of the same length and corresponding
* characters in the two strings are equal ignoring case.
*
* Two characters `c1` and `c2` are considered the same ignoring case if at least one of
* the following is true:
*
* - The two characters are the same (as compared by the `==` operator)
* - Applying the method `Character.toUpperCase(char)` to each character produces the same result
* - Applying the method `Character.toLowerCase(char)` to each character produces the same result
*
* @param anotherString The String to compare this String against
* @returns `true` if the argument is not `null` and it represents an equivalent String ignoring case; `false` otherwise
*/
public equalsIgnoreCase(anotherString: string | VString): VBool {
return new VBool(VExpression.call(this, 'equalsIgnoreCase', [anotherString]));
}
/**
* Returns the index within this string of the first occurrence of the specified
* substring, starting at the specified index. The integer returned is the
* smallest value k for which:
*
* ```java
* k >= Math.min(fromIndex, this.length()) && this.startsWith(str, k)
* ```
*
* If no such value of k exists, then -1 is returned.
* @param str the substring for which to search.
* @param fromIndex the index from which to start the search.
* @returns the index within this string of the first occurrence of the specified
* substring, starting at the specified index.
*/
public indexOf(str: string | VString, fromIndex?: number | VInteger): VInteger {
return new VInteger(VExpression.call(this, 'indexOf', cleanArgs(str, fromIndex)));
}
/**
* Returns `true` if, and only if, `length()` is `0`.
*/
public isEmpty(): VBool {
return new VBool(VExpression.concat(this, '.isEmpty()'));
}
/**
* Returns the index within this string of the last occurrence of the specified character,
* searching backward starting at the specified index.
*
* ```java
* k >= Math.min(fromIndex, this.length()) && this.startsWith(str, k)
* ```
*
* If no such value of k exists, then -1 is returned.
* @param str the substring to search for
* @param fromIndex the index to start the search from.
*/
public lastIndexOf(str: string | VString, fromIndex?: number | VInteger): VInteger {
return new VInteger(VExpression.call(
this, 'substring', cleanArgs(str, fromIndex)));
}
/**
* Returns the length of this string.
*/
public length(): VInteger {
return new VInteger(VExpression.concat(this, '.length()'));
}
/**
* Tells whether or not this string matches the given regular expression.
*
* An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression
* @param regex the regular expression to which this string is to be matched
* @returns `true` if, and only if, this string matches the given regular expression
*/
public matches(regex: string | RegExp | VString): VBool {
return new VBool(VExpression.call(
this, 'matches', [
typeof regex !== 'string' && !VObject.isObject(regex) ? (regex as RegExp).source : regex
]));
}
/**
* Splits this string around matches of the given regular expression.
*
* The array returned by this method contains each substring of this string that is
* terminated by another substring that matches the given expression or is terminated
* by the end of the string. The substrings in the array are in the order in which
* they occur in this string. If the expression does not match any part of the input
* then the resulting array has just one element, namely this string.
*
* The limit parameter controls the number of times the pattern is applied and therefore
* affects the length of the resulting array. If the limit n is greater than zero then
* the pattern will be applied at most n - 1 times, the array's length will be no greater
* than n, and the array's last entry will contain all input beyond the last matched
* delimiter. If n is non-positive then the pattern will be applied as many times as
* possible and the array can have any length. If n is zero then the pattern will be
* applied as many times as possible, the array can have any length, and trailing empty
* strings will be discarded.
*
* The string `"boo:and:foo"`, for example, yields the following results with these parameters:
* ```
* Regex Limit Result
* : 2 { "boo", "and:foo" }
* : 5 { "boo", "and", "foo" }
* : -2 { "boo", "and", "foo" }
* o 5 { "b", "", ":and:f", "", "" }
* o -2 { "b", "", ":and:f", "", "" }
* o 0 { "b", "", ":and:f" }
* ```
*
* @param regex the delimiting regular expression
* @param limit the result threshold, as described above
* @returns the array of strings computed by splitting this string around matches of the given regular expression
*/
public split(regex: string | RegExp | VString, limit?: number | VInteger): VList<VString> {
return new VList(string, VExpression.call(
this, 'split', cleanArgs(
typeof regex !== 'string' && !VObject.isObject(regex) ? (regex as RegExp).source : regex,
limit
)));
}
/**
* Returns a new string that is a substring of this string. The substring begins
* at the specified beginIndex and extends to the character at index endIndex - 1.
* Thus the length of the substring is endIndex-beginIndex.
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @returns the specified substring.
*/
public substring(beginIndex: VObject.Like<IntegerShape>, endIndex?: VObject.Like<IntegerShape>): VString {
return new VString(VExpression.call(
this, 'substring', cleanArgs(beginIndex, endIndex)));
}
/**
* Tests if the substring of this string beginning at the specified index starts with the specified prefix.
*
* @param prefix the prefix.
* @param toffset true if the character sequence represented by the argument is a prefix of the
* character sequence represented by this string; false otherwise. Note also
* that true will be returned if the argument is an empty string or is equal to
* this String object as determined by the equals(Object) method.
* @returns true if the character sequence represented by the argument is a prefix of the substring
* of this object starting at index toffset; false otherwise. The result is false if toffset
* is negative or greater than the length of this String object; otherwise the result is the
* same as the result of the expression
*/
public startsWith(prefix: string | VString, toffset?: number | VInteger): VBool {
return new VBool(VExpression.call(
this, 'startsWith', [
prefix,
...(toffset === undefined ? [] : [])
]
));
}
/**
* Converts all of the characters in this String to lower case using the rules of the default locale.
*/
public toLowerCase(): VString {
return new VString(VExpression.concat(this, '.toLowerCase()'));
}
/**
* Converts all of the characters in this String to upper case using the rules of the default locale.
*/
public toUpperCase(): VString {
return new VString(VExpression.concat(this, '.toUpperCase()'));
}
/**
* Returns a copy of the string, with leading and trailing whitespace omitted.
*/
public trim(): VString {
return new VString(VExpression.concat(this, '.trim()'));
}
}
export class VString extends VStringLike<StringShape> {
constructor(expr: VExpression) {
super(string, expr);
}
}
export class VEnum<E extends EnumShape> extends VStringLike<E> {}
export class VTimestamp extends VObject.NewType(timestamp) {}
export class VList<T extends VObject = VObject> extends VObject<ArrayShape<VObject.TypeOf<T>>> {
constructor(shape: VObject.TypeOf<T>, expression: VExpression) {
super(array(shape), expression);
}
public size(): VInteger {
return new VInteger(VExpression.concat(this, '.size()'));
}
public isEmpty(): VBool {
return new VBool(VExpression.concat(this, '.isEmpty()'));
}
public get(index: number | VInteger): T {
return VObject.fromExpr(VObject.getType(this).Items, VExpression.concat(this, '.get(', index, ')')) as any;
}
public *set(index: number | VInteger, value: VObject.Like<VObject.TypeOf<T>>): VTL<void> {
yield* vtl`$util.qr(${this}.set(${index}, ${yield* VObject.of(VObject.getType(this).Items, value)}))`;
}
public push(value: VObject.Like<VObject.TypeOf<T>>) {
return this.add(value);
}
public *add(value: VObject.Like<VObject.TypeOf<T>>): VTL<void> {
yield* vtl`$util.qr(${this}.add(${yield* VObject.of(VObject.getType(this).Items, value)}))`;
}
public *forEach(f: (item: T, index: VInteger) => VTL<void>): VTL<void> {
yield* forLoop(this, f as any);
}
}
export class VMap<T extends VObject = VObject> extends VObject<MapShape<VObject.TypeOf<T>>> {
constructor(shape: MapShape<VObject.TypeOf<T>>, expression: VExpression) {
super(shape, expression);
}
public values(): VList<T> {
return new VList(VObject.getType(this).Items, VExpression.concat(this, '.values()'));
}
public get(key: string | VString): T {
return VObject.fromExpr(VObject.getType(this).Items, VExpression.concat(
this, '.get("', key, '")'
)) as any as T;
}
public *put(key: string | VString, value: T): VTL<void> {
yield* vtl(nothing)`$util.qr(${this}.put(${key}, ${value}))`;
}
}
export class VRecord<T extends TypeShape = TypeShape> extends VObject<T> {
constructor(type: T, expr: VExpression) {
super(type, expr);
for (const [name, shape] of Object.entries(type.Members) as [string, Shape][]) {
(this as any)[name] = VObject.fromExpr(shape, VExpression.concat(expr, '.', name.startsWith('_') ? `get("${name}")` : name));
}
}
}
export namespace VRecord {
export type GetMembers<R extends VRecord> = R extends VRecord<infer M> ? M : any;
export interface Members {
[m: string]: VObject;
}
export type Class<T extends VRecord = any> = (new(members: VRecord.GetMembers<T>) => T);
}
export class VUnion<U extends VObject> extends VObject<UnionShape<VObject.TypeOf<U>[]>> {
public *assertIs<T extends VUnion.UnionCase<U>>(item: T, msg?: string | VString): VTL<VObject.Of<T>, any> {
return yield* this.match(item, function*(i) {
return i;
}).otherwise(function*() {
throw $util.error(msg || `Item must be of type: ${item.Kind}`);
}) as any as VTL<VObject.Of<T>, any>;
}
public match<T, M extends VUnion.UnionCase<U>>(
match: M,
then: VUnion.CaseBlock<M, T>
): VUnion.Match<U, T | undefined, M> {
return new VUnion.Match(undefined, this, match, then);
}
}
export namespace VUnion {
export type CaseBlock<I extends Shape, T> = (i: VObject.Of<I>) => Generator<any, T>;
export type OtherwiseBlock<T> = () => Generator<any, T>;
export type UnionCase<U extends VObject> = VObject.TypeOf<U>;
export class Match<
U extends VObject = VObject,
Returns = any,
Excludes = UnionCase<U>
> {
constructor(
public readonly parent: Match<U, any, any> | undefined,
public readonly value: VObject<Shape>,
public readonly matchType: VUnion.UnionCase<U>,
public readonly block: VUnion.CaseBlock<any, Returns>
) {}
public [Symbol.iterator](): Generator<any, Returns, unknown> {
return parseMatch(this as any as Match);
}
public match<
M extends Exclude<
VObject.TypeOf<U>,
Excludes
>,
T
>(
match: M,
then: CaseBlock<M, T>
): Match<
U,
T | Returns | undefined,
M | Excludes
> {
return new Match(this, this.value, match as any, then);
}
public otherwise<T>(
block: OtherwiseBlock<T>
): VTL<
| T
| Exclude<Returns, undefined> extends never ?
Returns :
Exclude<Returns, undefined>
> {
return new Otherwise(this, block as any) as any;
}
}
export class Otherwise<Returns = any> {
constructor(
public readonly parent: Match<any, Returns, any>,
public readonly block: VUnion.OtherwiseBlock<Returns>
) {}
public [Symbol.iterator](): Generator<any, Returns, unknown> {
return parseMatch(this.parent, new ElseBranch(this.block));
}
}
function parseMatch(m: Match, elseIf?: IfBranch | ElseBranch): Generator<any, any> {
const assertCondition = toCondition(m);
const assertedValue = VObject.fromExpr(m.matchType, VObject.getExpr(m.value));
return (function*() {
const branch = new IfBranch(assertCondition, () => m.block(assertedValue), elseIf);
if (m.parent) {
yield* parseMatch(m.parent, branch);
} else {
return yield branch;
}
})();
}
function toCondition(m: Match): VBool {
const shape = m.matchType;
const type = $util.typeOf(m.value);
const s =
ShapeGuards.isTimestampShape(shape) ? 'String' :
ShapeGuards.isStringShape(shape) ? 'String' :
ShapeGuards.isNumberShape(shape) ? 'Number' :
ShapeGuards.isNothingShape(shape) ? 'Null' :
ShapeGuards.isArrayShape(shape) ? 'List' :
ShapeGuards.isSetShape(shape) ? 'List' :
ShapeGuards.isBoolShape(shape) ? 'Boolean' :
ShapeGuards.isRecordShape(shape) ? 'Map' :
ShapeGuards.isMapShape(shape) ? 'Map' :
undefined
;
if (s === undefined) {
throw new Error(`cannot match on type: ${shape.Kind}`);
}
return type.equals(s as string);
}
}
export class Visitor implements ShapeVisitor<VObject, VExpression> {
public static defaultInstance = new Visitor();
public enumShape(shape: EnumShape<any, any>, expr: VExpression): VEnum<EnumShape> {
return new VEnum(shape, expr);
}
public unionShape(shape: UnionShape<Shape[]>, expr: VExpression): VUnion<VObject<Shape>> {
return new VUnion(shape, expr);
}
public literalShape(shape: LiteralShape<Shape, any>, expr: VExpression): VObject<Shape> {
return shape.Type.visit(this, expr);
}
public functionShape(shape: FunctionShape<FunctionArgs, Shape>): VObject<Shape> {
throw new Error("Method not implemented.");
}
public neverShape(shape: NeverShape, expr: VExpression): VObject<Shape> {
return new VNever(expr);
}
public arrayShape(shape: ArrayShape<any>, expr: VExpression): VList {
return new VList(shape.Items, expr);
}
public binaryShape(shape: BinaryShape, expr: VExpression): VBinary {
return new VBinary(expr);
}
public boolShape(shape: BoolShape, expr: VExpression): VBool {
return new VBool(expr);
}
public recordShape(shape: TypeShape<any>, expr: VExpression): VRecord {
return new VRecord(shape, expr);
}
public anyShape(shape: AnyShape, expr: VExpression): VAny {
return new VAny(expr);
}
public integerShape(shape: IntegerShape, expr: VExpression): VInteger {
return new VInteger(expr);
}
public mapShape(shape: MapShape<Shape>, expr: VExpression): VMap<VObject> {
return new VMap(shape, expr);
}
public nothingShape(shape: NothingShape, expr: VExpression): VNothing {
return new VNothing(expr);
}
public numberShape(shape: NumberShape, expr: VExpression): VFloat {
return new VFloat(expr);
}
public setShape(shape: SetShape<Shape>, expr: VExpression): VList<VObject> {
return new VList(shape, expr);
}
public stringShape(shape: StringShape, expr: VExpression): VString {
return new VString(expr);
}
public timestampShape(shape: TimestampShape, expr: VExpression): VTimestamp {
return new VTimestamp(expr);
}
} | the_stack |
import { tree } from 'antlr4';
// This class defines a complete generic visitor for a parse tree produced by SqlBaseParser.
export const SqlBaseVisitor = function() {
tree.ParseTreeVisitor.call(this);
return this;
} as any;
SqlBaseVisitor.prototype = Object.create(tree.ParseTreeVisitor.prototype);
SqlBaseVisitor.prototype.constructor = SqlBaseVisitor;
// Visit a parse tree produced by SqlBaseParser#multiStatement.
SqlBaseVisitor.prototype.visitMultiStatement = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#singleStatement.
SqlBaseVisitor.prototype.visitSingleStatement = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#singleExpression.
SqlBaseVisitor.prototype.visitSingleExpression = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#statementDefault.
SqlBaseVisitor.prototype.visitStatementDefault = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#use.
SqlBaseVisitor.prototype.visitUse = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#createSchema.
SqlBaseVisitor.prototype.visitCreateSchema = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#dropSchema.
SqlBaseVisitor.prototype.visitDropSchema = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#renameSchema.
SqlBaseVisitor.prototype.visitRenameSchema = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#createTableAsSelect.
SqlBaseVisitor.prototype.visitCreateTableAsSelect = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#createTable.
SqlBaseVisitor.prototype.visitCreateTable = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#dropTable.
SqlBaseVisitor.prototype.visitDropTable = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#insertInto.
SqlBaseVisitor.prototype.visitInsertInto = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#delete.
SqlBaseVisitor.prototype.visitDelete = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#renameTable.
SqlBaseVisitor.prototype.visitRenameTable = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#renameColumn.
SqlBaseVisitor.prototype.visitRenameColumn = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#addColumn.
SqlBaseVisitor.prototype.visitAddColumn = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#createView.
SqlBaseVisitor.prototype.visitCreateView = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#dropView.
SqlBaseVisitor.prototype.visitDropView = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#call.
SqlBaseVisitor.prototype.visitCall = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#grant.
SqlBaseVisitor.prototype.visitGrant = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#revoke.
SqlBaseVisitor.prototype.visitRevoke = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#explain.
SqlBaseVisitor.prototype.visitExplain = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#showCreateTable.
SqlBaseVisitor.prototype.visitShowCreateTable = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#showCreateView.
SqlBaseVisitor.prototype.visitShowCreateView = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#showTables.
SqlBaseVisitor.prototype.visitShowTables = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#showSchemas.
SqlBaseVisitor.prototype.visitShowSchemas = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#showCatalogs.
SqlBaseVisitor.prototype.visitShowCatalogs = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#showColumns.
SqlBaseVisitor.prototype.visitShowColumns = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#showFunctions.
SqlBaseVisitor.prototype.visitShowFunctions = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#showSession.
SqlBaseVisitor.prototype.visitShowSession = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#setSession.
SqlBaseVisitor.prototype.visitSetSession = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#resetSession.
SqlBaseVisitor.prototype.visitResetSession = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#startTransaction.
SqlBaseVisitor.prototype.visitStartTransaction = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#commit.
SqlBaseVisitor.prototype.visitCommit = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#rollback.
SqlBaseVisitor.prototype.visitRollback = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#showPartitions.
SqlBaseVisitor.prototype.visitShowPartitions = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#prepare.
SqlBaseVisitor.prototype.visitPrepare = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#deallocate.
SqlBaseVisitor.prototype.visitDeallocate = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#execute.
SqlBaseVisitor.prototype.visitExecute = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#describeInput.
SqlBaseVisitor.prototype.visitDescribeInput = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#describeOutput.
SqlBaseVisitor.prototype.visitDescribeOutput = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#query.
SqlBaseVisitor.prototype.visitQuery = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#presto_with.
SqlBaseVisitor.prototype.visitPresto_with = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#tableElement.
SqlBaseVisitor.prototype.visitTableElement = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#columnDefinition.
SqlBaseVisitor.prototype.visitColumnDefinition = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#likeClause.
SqlBaseVisitor.prototype.visitLikeClause = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#tableProperties.
SqlBaseVisitor.prototype.visitTableProperties = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#tableProperty.
SqlBaseVisitor.prototype.visitTableProperty = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#queryNoWith.
SqlBaseVisitor.prototype.visitQueryNoWith = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#queryTermDefault.
SqlBaseVisitor.prototype.visitQueryTermDefault = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#setOperation.
SqlBaseVisitor.prototype.visitSetOperation = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#queryPrimaryDefault.
SqlBaseVisitor.prototype.visitQueryPrimaryDefault = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#table.
SqlBaseVisitor.prototype.visitTable = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#inlineTable.
SqlBaseVisitor.prototype.visitInlineTable = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#subquery.
SqlBaseVisitor.prototype.visitSubquery = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#sortItem.
SqlBaseVisitor.prototype.visitSortItem = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#querySpecification.
SqlBaseVisitor.prototype.visitQuerySpecification = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#groupBy.
SqlBaseVisitor.prototype.visitGroupBy = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#singleGroupingSet.
SqlBaseVisitor.prototype.visitSingleGroupingSet = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#rollup.
SqlBaseVisitor.prototype.visitRollup = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#cube.
SqlBaseVisitor.prototype.visitCube = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#multipleGroupingSets.
SqlBaseVisitor.prototype.visitMultipleGroupingSets = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#groupingExpressions.
SqlBaseVisitor.prototype.visitGroupingExpressions = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#groupingSet.
SqlBaseVisitor.prototype.visitGroupingSet = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#namedQuery.
SqlBaseVisitor.prototype.visitNamedQuery = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#setQuantifier.
SqlBaseVisitor.prototype.visitSetQuantifier = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#selectSingle.
SqlBaseVisitor.prototype.visitSelectSingle = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#selectAll.
SqlBaseVisitor.prototype.visitSelectAll = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#relationDefault.
SqlBaseVisitor.prototype.visitRelationDefault = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#joinRelation.
SqlBaseVisitor.prototype.visitJoinRelation = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#joinType.
SqlBaseVisitor.prototype.visitJoinType = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#joinCriteria.
SqlBaseVisitor.prototype.visitJoinCriteria = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#sampledRelation.
SqlBaseVisitor.prototype.visitSampledRelation = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#sampleType.
SqlBaseVisitor.prototype.visitSampleType = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#aliasedRelation.
SqlBaseVisitor.prototype.visitAliasedRelation = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#columnAliases.
SqlBaseVisitor.prototype.visitColumnAliases = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#tableName.
SqlBaseVisitor.prototype.visitTableName = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#subqueryRelation.
SqlBaseVisitor.prototype.visitSubqueryRelation = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#unnest.
SqlBaseVisitor.prototype.visitUnnest = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#parenthesizedRelation.
SqlBaseVisitor.prototype.visitParenthesizedRelation = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#expression.
SqlBaseVisitor.prototype.visitExpression = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#logicalNot.
SqlBaseVisitor.prototype.visitLogicalNot = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#booleanDefault.
SqlBaseVisitor.prototype.visitBooleanDefault = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#logicalBinary.
SqlBaseVisitor.prototype.visitLogicalBinary = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#predicated.
SqlBaseVisitor.prototype.visitPredicated = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#comparison.
SqlBaseVisitor.prototype.visitComparison = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#quantifiedComparison.
SqlBaseVisitor.prototype.visitQuantifiedComparison = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#between.
SqlBaseVisitor.prototype.visitBetween = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#inList.
SqlBaseVisitor.prototype.visitInList = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#inSubquery.
SqlBaseVisitor.prototype.visitInSubquery = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#like.
SqlBaseVisitor.prototype.visitLike = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#nullPredicate.
SqlBaseVisitor.prototype.visitNullPredicate = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#distinctFrom.
SqlBaseVisitor.prototype.visitDistinctFrom = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#valueExpressionDefault.
SqlBaseVisitor.prototype.visitValueExpressionDefault = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#concatenation.
SqlBaseVisitor.prototype.visitConcatenation = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#arithmeticBinary.
SqlBaseVisitor.prototype.visitArithmeticBinary = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#arithmeticUnary.
SqlBaseVisitor.prototype.visitArithmeticUnary = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#atTimeZone.
SqlBaseVisitor.prototype.visitAtTimeZone = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#dereference.
SqlBaseVisitor.prototype.visitDereference = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#typeConstructor.
SqlBaseVisitor.prototype.visitTypeConstructor = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#specialDateTimeFunction.
SqlBaseVisitor.prototype.visitSpecialDateTimeFunction = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#substring.
SqlBaseVisitor.prototype.visitSubstring = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#cast.
SqlBaseVisitor.prototype.visitCast = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#lambda.
SqlBaseVisitor.prototype.visitLambda = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#parameter.
SqlBaseVisitor.prototype.visitParameter = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#normalize.
SqlBaseVisitor.prototype.visitNormalize = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#intervalLiteral.
SqlBaseVisitor.prototype.visitIntervalLiteral = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#numericLiteral.
SqlBaseVisitor.prototype.visitNumericLiteral = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#booleanLiteral.
SqlBaseVisitor.prototype.visitBooleanLiteral = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#implicitRowConstructor.
SqlBaseVisitor.prototype.visitImplicitRowConstructor = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#simpleCase.
SqlBaseVisitor.prototype.visitSimpleCase = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#columnReference.
SqlBaseVisitor.prototype.visitColumnReference = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#nullLiteral.
SqlBaseVisitor.prototype.visitNullLiteral = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#rowConstructor.
SqlBaseVisitor.prototype.visitRowConstructor = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#subscript.
SqlBaseVisitor.prototype.visitSubscript = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#subqueryExpression.
SqlBaseVisitor.prototype.visitSubqueryExpression = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#binaryLiteral.
SqlBaseVisitor.prototype.visitBinaryLiteral = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#extract.
SqlBaseVisitor.prototype.visitExtract = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#stringLiteral.
SqlBaseVisitor.prototype.visitStringLiteral = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#arrayConstructor.
SqlBaseVisitor.prototype.visitArrayConstructor = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#functionCall.
SqlBaseVisitor.prototype.visitFunctionCall = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#exists.
SqlBaseVisitor.prototype.visitExists = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#position.
SqlBaseVisitor.prototype.visitPosition = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#searchedCase.
SqlBaseVisitor.prototype.visitSearchedCase = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#timeZoneInterval.
SqlBaseVisitor.prototype.visitTimeZoneInterval = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#timeZoneString.
SqlBaseVisitor.prototype.visitTimeZoneString = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#comparisonOperator.
SqlBaseVisitor.prototype.visitComparisonOperator = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#comparisonQuantifier.
SqlBaseVisitor.prototype.visitComparisonQuantifier = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#booleanValue.
SqlBaseVisitor.prototype.visitBooleanValue = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#interval.
SqlBaseVisitor.prototype.visitInterval = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#intervalField.
SqlBaseVisitor.prototype.visitIntervalField = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#type.
SqlBaseVisitor.prototype.visitType = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#typeParameter.
SqlBaseVisitor.prototype.visitTypeParameter = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#baseType.
SqlBaseVisitor.prototype.visitBaseType = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#whenClause.
SqlBaseVisitor.prototype.visitWhenClause = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#filter.
SqlBaseVisitor.prototype.visitFilter = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#over.
SqlBaseVisitor.prototype.visitOver = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#windowFrame.
SqlBaseVisitor.prototype.visitWindowFrame = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#unboundedFrame.
SqlBaseVisitor.prototype.visitUnboundedFrame = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#currentRowBound.
SqlBaseVisitor.prototype.visitCurrentRowBound = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#boundedFrame.
SqlBaseVisitor.prototype.visitBoundedFrame = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#explainFormat.
SqlBaseVisitor.prototype.visitExplainFormat = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#explainType.
SqlBaseVisitor.prototype.visitExplainType = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#isolationLevel.
SqlBaseVisitor.prototype.visitIsolationLevel = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#transactionAccessMode.
SqlBaseVisitor.prototype.visitTransactionAccessMode = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#readUncommitted.
SqlBaseVisitor.prototype.visitReadUncommitted = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#readCommitted.
SqlBaseVisitor.prototype.visitReadCommitted = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#repeatableRead.
SqlBaseVisitor.prototype.visitRepeatableRead = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#serializable.
SqlBaseVisitor.prototype.visitSerializable = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#positionalArgument.
SqlBaseVisitor.prototype.visitPositionalArgument = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#namedArgument.
SqlBaseVisitor.prototype.visitNamedArgument = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#privilege.
SqlBaseVisitor.prototype.visitPrivilege = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#qualifiedName.
SqlBaseVisitor.prototype.visitQualifiedName = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#unquotedIdentifier.
SqlBaseVisitor.prototype.visitUnquotedIdentifier = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#quotedIdentifierAlternative.
SqlBaseVisitor.prototype.visitQuotedIdentifierAlternative = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#backQuotedIdentifier.
SqlBaseVisitor.prototype.visitBackQuotedIdentifier = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#digitIdentifier.
SqlBaseVisitor.prototype.visitDigitIdentifier = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#quotedIdentifier.
SqlBaseVisitor.prototype.visitQuotedIdentifier = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#decimalLiteral.
SqlBaseVisitor.prototype.visitDecimalLiteral = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#integerLiteral.
SqlBaseVisitor.prototype.visitIntegerLiteral = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#nonReserved.
SqlBaseVisitor.prototype.visitNonReserved = function(ctx) {
return this.visitChildren(ctx);
};
// Visit a parse tree produced by SqlBaseParser#normalForm.
SqlBaseVisitor.prototype.visitNormalForm = function(ctx) {
return this.visitChildren(ctx);
}; | the_stack |
import { extname } from '../../../common/path';
import { FetchDataType } from '../../../common/fetchdatatype';
import { decodeAudioData } from '../../../common/audio';
import MdlxModel from '../../../parsers/mdlx/model';
import { isMdx, isMdl } from '../../../parsers/mdlx/isformat';
import { MappedData, MappedDataRow } from '../../../utils/mappeddata';
import ModelViewer, { DebugRenderMode } from '../../viewer';
import Shader from '../../gl/shader';
import { PathSolver, SolverParams } from '../../handlerresource';
import { Resource } from '../../resource';
import GenericResource from '../../genericresource';
import Texture from '../../texture';
import Model from './model';
import MdxTexture from './texture';
import sdVert from './shaders/sd.vert';
import sdFrag from './shaders/sd.frag';
import hdVert from './shaders/hd.vert';
import hdFrag from './shaders/hd.frag';
import particlesVert from './shaders/particles.vert';
import particlesFrag from './shaders/particles.frag';
import { SkinningType } from './batch';
import { WrapMode } from '../../../parsers/mdlx/texture';
export interface EventObjectData {
row: MappedDataRow;
resources: Resource[];
}
export interface MdxHandlerObject {
pathSolver?: PathSolver;
reforged: boolean;
sdShader: Shader;
sdExtendedShader: Shader;
hdShader: Shader;
hdExtendedShader: Shader;
hdSkinShader: Shader;
particlesShader: Shader;
sdDebugShaders: Shader[][];
hdDebugShaders: Shader[][];
rectBuffer: WebGLBuffer;
teamColors: MdxTexture[];
teamGlows: MdxTexture[];
eventObjectTables: {[key: string]: GenericResource[] };
// lutTexture: MdxTexture | null;
// envDiffuseTexture: MdxTexture | null;
// envSpecularTexture: MdxTexture | null;
}
const mappedDataCallback = (data: FetchDataType): MappedData => new MappedData(<string>data);
const decodedDataCallback = (data: FetchDataType): Promise<AudioBuffer | undefined> => decodeAudioData(<ArrayBuffer>data);
export default {
load(viewer: ModelViewer, pathSolver?: PathSolver, reforged = false): void {
const gl = viewer.gl;
const webgl = viewer.webgl;
// Bone textures.
if (!webgl.ensureExtension('OES_texture_float')) {
throw new Error('MDX: No float texture support!');
}
// Geometry emitters.
if (!webgl.ensureExtension('ANGLE_instanced_arrays')) {
throw new Error('MDX: No instanced rendering support!');
}
// Shaders. Lots of them.
const sdExtendedVert = '#define EXTENDED_BONES\n' + sdVert;
const sdDiffuse = '#define ONLY_DIFFUSE\n' + sdFrag;
const sdTexcoords = '#define ONLY_TEXCOORDS\n' + sdFrag;
const sdNormals = '#define ONLY_NORMALS\n' + sdFrag;
const hdExtendedVert = '#define EXTENDED_BONES\n' + hdVert;
const hdSkinVert = '#define SKIN\n' + hdVert;
const hdDiffuse = '#define ONLY_DIFFUSE\n' + hdFrag;
const hdNormalMap = '#define ONLY_NORMAL_MAP\n' + hdFrag;
const hdOcclusion = '#define ONLY_OCCLUSION\n' + hdFrag;
const hdRoughness = '#define ONLY_ROUGHNESS\n' + hdFrag;
const hdMetallic = '#define ONLY_METALLIC\n' + hdFrag;
const hdTCFactor = '#define ONLY_TC_FACTOR\n' + hdFrag;
const hdEmissive = '#define ONLY_EMISSIVE\n' + hdFrag;
const hdTexCoords = '#define ONLY_TEXCOORDS\n' + hdFrag;
const hdNormals = '#define ONLY_NORMALS\n' + hdFrag;
const hdTangents = '#define ONLY_TANGENTS\n' + hdFrag;
const sdShader = webgl.createShader(sdVert, sdFrag);
const sdExtendedShader = webgl.createShader(sdExtendedVert, sdFrag);
const hdShader = webgl.createShader(hdVert, hdFrag);
const hdExtendedShader = webgl.createShader(hdExtendedVert, hdFrag);
const hdSkinShader = webgl.createShader(hdSkinVert, hdFrag);
const particlesShader = webgl.createShader(particlesVert, particlesFrag);
const sdDebugShaders: Shader[][] = [];
const hdDebugShaders: Shader[][] = [];
let shaders: Shader[] = [];
shaders[DebugRenderMode.Diffuse] = webgl.createShader(sdVert, sdDiffuse);
shaders[DebugRenderMode.TexCoords] = webgl.createShader(sdVert, sdTexcoords);
shaders[DebugRenderMode.Normals] = webgl.createShader(sdVert, sdNormals);
sdDebugShaders[SkinningType.VertexGroups] = shaders;
shaders = [];
shaders[DebugRenderMode.Diffuse] = webgl.createShader(sdExtendedVert, sdDiffuse);
shaders[DebugRenderMode.TexCoords] = webgl.createShader(sdExtendedVert, sdTexcoords);
shaders[DebugRenderMode.Normals] = webgl.createShader(sdExtendedVert, sdNormals);
sdDebugShaders[SkinningType.ExtendedVertexGroups] = shaders;
shaders = [];
shaders[DebugRenderMode.Diffuse] = webgl.createShader(hdVert, hdDiffuse);
shaders[DebugRenderMode.NormalMap] = webgl.createShader(hdVert, hdNormalMap);
shaders[DebugRenderMode.Occlusion] = webgl.createShader(hdVert, hdOcclusion);
shaders[DebugRenderMode.Roughness] = webgl.createShader(hdVert, hdRoughness);
shaders[DebugRenderMode.Metallic] = webgl.createShader(hdVert, hdMetallic);
shaders[DebugRenderMode.TCFactor] = webgl.createShader(hdVert, hdTCFactor);
shaders[DebugRenderMode.Emissive] = webgl.createShader(hdVert, hdEmissive);
shaders[DebugRenderMode.TexCoords] = webgl.createShader(hdVert, hdTexCoords);
shaders[DebugRenderMode.Normals] = webgl.createShader(hdVert, hdNormals);
shaders[DebugRenderMode.Tangents] = webgl.createShader('#define ONLY_TANGENTS\n' + hdVert, hdTangents);
hdDebugShaders[SkinningType.VertexGroups] = shaders;
shaders = [];
shaders[DebugRenderMode.Diffuse] = webgl.createShader(hdExtendedVert, hdDiffuse);
shaders[DebugRenderMode.NormalMap] = webgl.createShader(hdExtendedVert, hdNormalMap);
shaders[DebugRenderMode.Occlusion] = webgl.createShader(hdExtendedVert, hdOcclusion);
shaders[DebugRenderMode.Roughness] = webgl.createShader(hdExtendedVert, hdRoughness);
shaders[DebugRenderMode.Metallic] = webgl.createShader(hdExtendedVert, hdMetallic);
shaders[DebugRenderMode.TCFactor] = webgl.createShader(hdExtendedVert, hdTCFactor);
shaders[DebugRenderMode.Emissive] = webgl.createShader(hdExtendedVert, hdEmissive);
shaders[DebugRenderMode.TexCoords] = webgl.createShader(hdExtendedVert, hdTexCoords);
shaders[DebugRenderMode.Normals] = webgl.createShader(hdExtendedVert, hdNormals);
shaders[DebugRenderMode.Tangents] = webgl.createShader('#define ONLY_TANGENTS\n' + hdExtendedVert, hdTangents);
hdDebugShaders[SkinningType.ExtendedVertexGroups] = shaders;
shaders = [];
shaders[DebugRenderMode.Diffuse] = webgl.createShader(hdSkinVert, hdDiffuse);
shaders[DebugRenderMode.NormalMap] = webgl.createShader(hdSkinVert, hdNormalMap);
shaders[DebugRenderMode.Occlusion] = webgl.createShader(hdSkinVert, hdOcclusion);
shaders[DebugRenderMode.Roughness] = webgl.createShader(hdSkinVert, hdRoughness);
shaders[DebugRenderMode.Metallic] = webgl.createShader(hdSkinVert, hdMetallic);
shaders[DebugRenderMode.TCFactor] = webgl.createShader(hdSkinVert, hdTCFactor);
shaders[DebugRenderMode.Emissive] = webgl.createShader(hdSkinVert, hdEmissive);
shaders[DebugRenderMode.TexCoords] = webgl.createShader(hdSkinVert, hdTexCoords);
shaders[DebugRenderMode.Normals] = webgl.createShader(hdSkinVert, hdNormals);
shaders[DebugRenderMode.Tangents] = webgl.createShader('#define ONLY_TANGENTS\n' + hdSkinVert, hdTangents);
hdDebugShaders[SkinningType.Skin] = shaders;
const rectBuffer = <WebGLBuffer>gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, rectBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Uint8Array([0, 1, 2, 0, 2, 3]), gl.STATIC_DRAW);
const handlerData: MdxHandlerObject = {
pathSolver,
reforged,
// Shaders.
sdShader,
sdExtendedShader,
hdShader,
hdExtendedShader,
hdSkinShader,
particlesShader,
sdDebugShaders,
hdDebugShaders,
// Geometry emitters buffer.
rectBuffer,
// Team color/glow textures - loaded when the first model that uses team textures is loaded.
teamColors: [],
teamGlows: [],
eventObjectTables: {},
// lutTexture: null,
// envDiffuseTexture: null,
// envSpecularTexture: null,
};
viewer.sharedCache.set('mdx', handlerData);
},
isValidSource(object: unknown): boolean {
if (object instanceof MdlxModel) {
return true;
}
return isMdx(object) || isMdl(object);
},
resource: Model,
// async loadEnv(viewer: ModelViewer) {
// const mdxHandler = <MdxHandlerObject>viewer.sharedCache.get('mdx');
// if (!mdxHandler.lutTexture) {
// mdxHandler.lutTexture = new MdxTexture(0, WrapMode.WrapBoth);
// mdxHandler.envDiffuseTexture = new MdxTexture(0, WrapMode.WrapBoth);
// mdxHandler.envSpecularTexture = new MdxTexture(0, WrapMode.WrapBoth);
// const [lutTexture, diffuseTexture, specularTexture] = await Promise.all([
// viewer.load('env/lut.png'),
// viewer.load('env/diffuse-sRGB.png'),
// viewer.load('env/specular-sRGB.png'),
// ]);
// mdxHandler.lutTexture.texture = <Texture>lutTexture;
// mdxHandler.envDiffuseTexture.texture = <Texture>diffuseTexture;
// mdxHandler.envSpecularTexture.texture = <Texture>specularTexture;
// }
// },
loadTeamTextures(viewer: ModelViewer): void {
const { pathSolver, reforged, teamColors, teamGlows } = <MdxHandlerObject>viewer.sharedCache.get('mdx');
if (teamColors.length === 0) {
const teams = reforged ? 28 : 16;
const ext = reforged ? 'dds' : 'blp';
const params = reforged ? { reforged: true } : undefined;
for (let i = 0; i < teams; i++) {
const id = `${i}`.padStart(2, '0');
const end = `${id}.${ext}`;
const teamColor = new MdxTexture(1, WrapMode.WrapBoth);
const teamGlow = new MdxTexture(2, WrapMode.WrapBoth);
viewer.load(`ReplaceableTextures\\TeamColor\\TeamColor${end}`, pathSolver, params)
.then((texture) => teamColor.texture = <Texture>texture);
viewer.load(`ReplaceableTextures\\TeamGlow\\TeamGlow${end}`, pathSolver, params)
.then((texture) => teamGlow.texture = <Texture>texture);
teamColors[i] = teamColor;
teamGlows[i] = teamGlow;
}
}
},
getEventObjectSoundFile(file: string, reforged: boolean, isHd: boolean, tables: GenericResource[]): string | undefined {
if (!reforged || extname(file) === '.flac') {
return file;
}
for (let i = 1, l = tables.length; i < l; i++) {
const raceRow = (<MappedData>tables[i].data).getRow(file);
if (raceRow) {
const flags = <string>raceRow['Flags'];
const filePath = <string>raceRow['Filepath'];
if (flags === 'SD_ONLY') {
if (!isHd) {
return filePath;
}
} else if (flags === 'HD_ONLY') {
if (isHd) {
return filePath;
}
} else {
return filePath;
}
}
}
return;
},
async getEventObjectData(viewer: ModelViewer, type: string, id: string, isHd: boolean): Promise<EventObjectData | undefined> {
// Units\Critters\BlackStagMale\BlackStagMale.mdx has an event object named "Point01".
if (type !== 'SPN' && type !== 'SPL' && type !== 'UBR' && type !== 'SND') {
return;
}
const { pathSolver, reforged, eventObjectTables } = <MdxHandlerObject>viewer.sharedCache.get('mdx');
const params: SolverParams = reforged ? { reforged: true } : {};
const safePathSolver: PathSolver = (src: unknown, params?: SolverParams): unknown => {
if (pathSolver) {
return pathSolver(src, params);
}
return src;
};
if (!eventObjectTables[type]) {
const paths = [];
if (type === 'SPN') {
paths.push('Splats\\SpawnData.slk');
} else if (type === 'SPL') {
paths.push('Splats\\SplatData.slk');
} else if (type === 'UBR') {
paths.push('Splats\\UberSplatData.slk');
} else if (type === 'SND') {
paths.push('UI\\SoundInfo\\AnimSounds.slk');
// Reforged changed the data layout.
if (reforged) {
paths.push(
'UI\\SoundInfo\\DialogueHumanBase.slk',
'UI\\SoundInfo\\DialogueOrcBase.slk',
'UI\\SoundInfo\\DialogueUndeadBase.slk',
'UI\\SoundInfo\\DialogueNightElfBase.slk',
'UI\\SoundInfo\\DialogueNagaBase.slk',
'UI\\SoundInfo\\DialogueDemonBase.slk',
'UI\\SoundInfo\\DialogueCreepsBase.slk');
} else {
paths.push('UI\\SoundInfo\\AnimLookups.slk');
}
}
const promises = paths.map((path) => viewer.loadGeneric(<string>safePathSolver(path, params), 'text', mappedDataCallback));
const resources = await Promise.all(promises);
for (const resource of resources) {
if (!resource) {
return;
}
}
eventObjectTables[type] = <GenericResource[]>resources;
}
const tables = eventObjectTables[type];
const mappedData = <MappedData>tables[0].data;
let row: MappedDataRow | undefined;
const promises = [];
if (type === 'SND') {
// How to get the sound row?
// TFT has AnimLookups.slk, which stores a ID->Label. Give it the event object ID, get back the label to look for in AnimSounds.slk.
// Reforged removed AnimLookups.slk, and instead has the ID under a new column in AnimSounds.slk called AnimationEventCode.
// In addition, Reforged can have SD/HD flags per sound, to determine whether it should load in SD or HD modes.
// When a sound has both modes, the path to it in AnimSounds.slk won't be an actual file path (ending with .flac) but rather a label.
// This label can be queried in other sound SLKs such as DialogueHumanBase.slk, which contains the full path and the mentioned flags.
if (reforged) {
row = mappedData.findRow('AnimationEventCode', id);
} else {
const lookupRow = (<MappedData>tables[1].data).getRow(id);
if (lookupRow) {
row = mappedData.getRow(<string>lookupRow['SoundLabel']);
}
}
if (row) {
for (const fileName of (<string>row['FileNames']).split(',')) {
const file = this.getEventObjectSoundFile(fileName, reforged, isHd, tables);
if (file) {
promises.push(viewer.loadGeneric(<string>safePathSolver(file, params), 'arrayBuffer', decodedDataCallback));
}
}
}
} else {
// Model and texture event objects are simpler than sounds - just get the right model or texture file.
row = mappedData.getRow(id);
if (row) {
if (type === 'SPN') {
promises.push(viewer.load((<string>row['Model']).replace('.mdl', '.mdx'), safePathSolver, params));
} else if (type === 'SPL' || type === 'UBR') {
promises.push(viewer.load(`ReplaceableTextures\\Splats\\${row['file']}${reforged ? '.dds' : '.blp'}`, safePathSolver, params));
}
}
}
if (row && promises.length) {
const resources = await Promise.all(promises);
// Make sure the resources actually loaded properly.
const filtered = <Resource[]>resources.filter((resource) => resource);
if (filtered.length) {
return { row, resources: filtered };
}
}
return;
},
getBatchShader(viewer: ModelViewer, skinningType: SkinningType, isHd: boolean): Shader {
const mdxCache = <MdxHandlerObject>viewer.sharedCache.get('mdx');
const debugRenderMode = viewer.debugRenderMode;
if (isHd) {
if (debugRenderMode !== DebugRenderMode.None) {
const shaders = mdxCache.hdDebugShaders[skinningType];
if (shaders) {
const shader = shaders[debugRenderMode];
if (shader) {
return shader;
}
}
}
if (skinningType === SkinningType.Skin) {
return mdxCache.hdSkinShader;
} else if (skinningType === SkinningType.VertexGroups) {
return mdxCache.hdShader;
} else {
return mdxCache.hdExtendedShader;
}
} else {
if (debugRenderMode !== DebugRenderMode.None) {
const shaders = mdxCache.sdDebugShaders[skinningType];
if (shaders) {
const shader = shaders[debugRenderMode];
if (shader) {
return shader;
}
}
}
if (skinningType === SkinningType.VertexGroups) {
return mdxCache.sdShader;
} else {
return mdxCache.sdExtendedShader;
}
}
}
}; | the_stack |
import { createCheckBox } from '@syncfusion/ej2-buttons';
import { IMulitSelect } from './interface';
import { Input, InputObject } from '@syncfusion/ej2-inputs';
import { EventHandler, select, removeClass, addClass, detach, compile, L10n } from '@syncfusion/ej2-base';
import { Browser, attributes, isNullOrUndefined, KeyboardEventArgs, append, closest, prepend } from '@syncfusion/ej2-base';
import { dropDownBaseClasses } from '../drop-down-base/drop-down-base';
import { MultiSelectModel } from '../multi-select';
const ICON: string = 'e-icons';
const CHECKBOXFRAME: string = 'e-frame';
const CHECK: string = 'e-check';
const CHECKBOXWRAP: string = 'e-checkbox-wrapper';
const INDETERMINATE: string = 'e-stop';
const checkAllParent: string = 'e-selectall-parent';
const searchBackIcon: string = 'e-input-group-icon e-back-icon e-icons';
const filterBarClearIcon: string = 'e-input-group-icon e-clear-icon e-icons';
const filterInput: string = 'e-input-filter';
const filterParent: string = 'e-filter-parent';
const mobileFilter: string = 'e-ddl-device-filter';
const clearIcon: string = 'e-clear-icon';
const popupFullScreen: string = 'e-popup-full-page';
const device: string = 'e-ddl-device';
const FOCUS: string = 'e-input-focus';
/**
* The Multiselect enable CheckBoxSelection call this inject module.
*/
export class CheckBoxSelection {
private parent: IMulitSelect;
private checkAllParent: HTMLElement;
private selectAllSpan: HTMLElement;
public filterInput: HTMLInputElement;
private filterInputObj: InputObject;
private backIconElement: Element;
private clearIconElement: Element;
private checkWrapper: HTMLElement;
public list: HTMLElement;
private activeLi: HTMLElement[] = [];
private activeEle: HTMLElement[] = [];
public constructor(parent?: IMulitSelect) {
this.parent = parent;
this.removeEventListener();
this.addEventListener();
}
public getModuleName(): string {
return 'CheckBoxSelection';
}
public addEventListener(): void {
if (this.parent.isDestroyed) {
return;
}
this.parent.on('updatelist', this.listSelection, this);
this.parent.on('listoption', this.listOption, this);
this.parent.on('selectAll', this.setSelectAll, this);
this.parent.on('checkSelectAll', this.checkSelectAll, this);
this.parent.on('searchBox', this.setSearchBox, this);
this.parent.on('blur', this.onBlurHandler, this);
this.parent.on('targetElement', this.targetElement, this);
this.parent.on('deviceSearchBox', this.setDeviceSearchBox, this);
this.parent.on('inputFocus', this.getFocus, this);
this.parent.on('reOrder', this.setReorder, this);
this.parent.on('activeList', this.getActiveList, this);
this.parent.on('selectAllText', this.setLocale, this);
this.parent.on('filterBarPlaceholder', this.setPlaceholder, this);
EventHandler.add(document, 'mousedown', this.onDocumentClick, this);
this.parent.on('addItem', this.checboxCreate, this);
this.parent.on('popupFullScreen', this.setPopupFullScreen, this);
}
public removeEventListener(): void {
if (this.parent.isDestroyed) {
return;
}
this.parent.off('updatelist', this.listSelection);
this.parent.off('listoption', this.listOption);
this.parent.off('selectAll', this.setSelectAll);
this.parent.off('checkSelectAll', this.checkSelectAll);
this.parent.off('searchBox', this.setSearchBox);
this.parent.off('blur', this.onBlurHandler);
this.parent.off('targetElement', this.targetElement);
this.parent.off('deviceSearchBox', this.setDeviceSearchBox);
this.parent.off('inputFocus', this.getFocus);
this.parent.off('reOrder', this.setReorder);
this.parent.off('activeList', this.getActiveList);
this.parent.off('selectAllText', this.setLocale);
this.parent.off('filterBarPlaceholder', this.setPlaceholder);
this.parent.off('addItem', this.checboxCreate);
this.parent.off('popupFullScreen', this.setPopupFullScreen);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public listOption(args: { [key: string]: Object }): void {
if (isNullOrUndefined(this.parent.listCurrentOptions.itemCreated)) {
this.parent.listCurrentOptions.itemCreated = (e: { [key: string]: HTMLElement }) => {
this.checboxCreate(e);
};
} else {
const itemCreated: Function = <Function>this.parent.listCurrentOptions.itemCreated;
this.parent.listCurrentOptions.itemCreated = (e: { [key: string]: HTMLElement }) => {
this.checboxCreate(e);
itemCreated.apply(this, [e]);
};
}
}
private setPlaceholder(props: MultiSelectModel): void {
Input.setPlaceholder(props.filterBarPlaceholder, this.filterInput as HTMLInputElement);
}
private checboxCreate(e: { [key: string]: HTMLElement } | HTMLElement): { [key: string]: HTMLElement } | HTMLElement {
let item: { [key: string]: HTMLElement } | HTMLElement;
if (!isNullOrUndefined((e as { [key: string]: HTMLElement }).item)) {
item = (e as { [key: string]: HTMLElement }).item;
} else {
item = e;
}
if (this.parent.enableGroupCheckBox || ((item as HTMLElement).className !== 'e-list-group-item '
&& (item as HTMLElement).className !== 'e-list-group-item')) {
const checkboxEle: HTMLElement | Element | string = createCheckBox(this.parent.createElement, true);
const icon: Element = select('div.' + ICON, (item as HTMLElement));
(item as HTMLElement).insertBefore(checkboxEle, (item as HTMLElement).childNodes[isNullOrUndefined(icon) ? 0 : 1]);
select('.' + CHECKBOXFRAME, checkboxEle);
if (this.parent.enableGroupCheckBox ) {
this.parent.popupWrapper.classList.add('e-multiselect-group');
}
return item;
} else {
return item;
}
}
private setSelectAll(): void {
if (this.parent.showSelectAll) {
if (isNullOrUndefined(this.checkAllParent)) {
this.checkAllParent = this.parent.createElement('div', {
className: checkAllParent
});
this.selectAllSpan = this.parent.createElement('span', {
className: 'e-all-text'
});
this.selectAllSpan.textContent = '';
this.checkAllParent.appendChild(this.selectAllSpan);
this.setLocale();
this.checboxCreate(this.checkAllParent as { [key: string]: HTMLElement } | HTMLElement);
if (this.parent.headerTemplate) {
if (!isNullOrUndefined(this.parent.filterParent)) {
append([this.checkAllParent], this.parent.filterParent);
} else {
append([this.checkAllParent], this.parent.popupWrapper);
}
}
if (!this.parent.headerTemplate) {
if (!isNullOrUndefined(this.parent.filterParent)) {
this.parent.filterParent.parentNode.insertBefore(this.checkAllParent, this.parent.filterParent.nextSibling);
} else {
prepend([this.checkAllParent], this.parent.popupWrapper);
}
}
EventHandler.add(this.checkAllParent, 'mousedown', this.clickHandler, this);
}
if (this.parent.list.classList.contains('e-nodata') || (this.parent.listData && this.parent.listData.length <= 1 &&
!(this.parent.isDynamicDataChange)) || (this.parent.isDynamicDataChange &&
this.parent.listData && this.parent.listData.length <= 1)) {
this.checkAllParent.style.display = 'none';
} else {
this.checkAllParent.style.display = 'block';
}
this.parent.selectAllHeight = this.checkAllParent.getBoundingClientRect().height;
} else if (!isNullOrUndefined(this.checkAllParent)) {
this.checkAllParent.parentElement.removeChild(this.checkAllParent);
this.checkAllParent = null;
}
}
public destroy(): void {
this.removeEventListener();
EventHandler.remove(document, 'mousedown', this.onDocumentClick);
}
public listSelection(args: IUpdateListArgs): void {
let target: EventTarget;
if (!isNullOrUndefined(args.e)) {
const frameElm: Element = args.li.querySelector('.e-checkbox-wrapper .e-frame');
target = !isNullOrUndefined(args.e.target) ?
((args.e.target as HTMLElement).classList.contains('e-frame')
&& (!this.parent.showSelectAll
|| ( this.checkAllParent && !this.checkAllParent.contains(args.e.target as Element)))) ?
args.e.target : args.li.querySelector('.e-checkbox-wrapper').childNodes[1]
: args.li.querySelector('.e-checkbox-wrapper').childNodes[1];
} else {
const checkboxWrapper: Element = args.li.querySelector('.e-checkbox-wrapper');
target = checkboxWrapper ? checkboxWrapper.childNodes[1] : args.li.lastElementChild.childNodes[1];
}
if (this.parent.itemTemplate || this.parent.enableGroupCheckBox ) {
target = args.li.firstElementChild.childNodes[1];
}
if (!isNullOrUndefined(target)) {
this.checkWrapper = closest((target as HTMLElement), '.' + CHECKBOXWRAP) as HTMLElement;
}
if (!isNullOrUndefined(this.checkWrapper)) {
const checkElement: Element = select('.' + CHECKBOXFRAME, this.checkWrapper);
const selectAll: boolean = false;
this.validateCheckNode(this.checkWrapper, checkElement.classList.contains(CHECK), args.li, args.e, selectAll);
}
}
private validateCheckNode(
checkWrap: HTMLElement | Element,
isCheck: boolean, li?: HTMLElement | Element,
e?: KeyboardEventArgs | MouseEvent, selectAll?: boolean): void {
this.changeState(checkWrap, isCheck ? 'uncheck' : 'check', e, true, selectAll);
}
private clickHandler(e: MouseEvent): void {
let target: EventTarget;
if ((e.currentTarget as HTMLElement).classList.contains(this.checkAllParent.className)) {
target = (e.currentTarget as HTMLElement).firstElementChild.lastElementChild;
} else {
target = <Element>e.currentTarget;
}
this.checkWrapper = closest((target as HTMLElement), '.' + CHECKBOXWRAP) as HTMLElement;
const selectAll: boolean = true;
if (!isNullOrUndefined(this.checkWrapper)) {
const checkElement: Element = select('.' + CHECKBOXFRAME, this.checkWrapper);
this.validateCheckNode(this.checkWrapper, checkElement.classList.contains(CHECK), null, e, selectAll);
}
e.preventDefault();
}
private changeState(
wrapper: HTMLElement | Element, state: string, e?: MouseEvent | KeyboardEventArgs, isPrevent?: boolean, selectAll?: boolean): void {
let ariaState: string;
const frameSpan: Element = wrapper.getElementsByClassName(CHECKBOXFRAME)[0];
if (state === 'check' && !frameSpan.classList.contains(CHECK)) {
frameSpan.classList.remove(INDETERMINATE);
frameSpan.classList.add(CHECK);
ariaState = 'true';
if (selectAll) {
this.parent.selectAllItems(true, e as MouseEvent);
this.setLocale(true);
}
} else if (state === 'uncheck' && (frameSpan.classList.contains(CHECK) || frameSpan.classList.contains(INDETERMINATE))) {
removeClass([frameSpan], [CHECK, INDETERMINATE]);
ariaState = 'false';
if (selectAll) {
this.parent.selectAllItems(false, e as MouseEvent);
this.setLocale();
}
} else if (state === 'indeterminate' && !(frameSpan.classList.contains(INDETERMINATE))) {
removeClass([frameSpan], [CHECK]);
frameSpan.classList.add(INDETERMINATE);
ariaState = 'false';
if (selectAll) {
this.parent.selectAllItems(false, e as MouseEvent);
this.setLocale();
}
}
ariaState = state === 'check' ? 'true' : state === 'uncheck' ? 'false' : ariaState;
if (!isNullOrUndefined(ariaState)) {
wrapper.setAttribute('aria-checked', ariaState);
}
}
protected setSearchBox(args: IUpdateListArgs): InputObject | void {
if (isNullOrUndefined(this.parent.filterParent)) {
this.parent.filterParent = this.parent.createElement('span', {
className: filterParent
});
this.filterInput = <HTMLInputElement>this.parent.createElement('input', {
attrs: { type: 'text' },
className: filterInput
});
this.parent.element.parentNode.insertBefore(this.filterInput, this.parent.element);
let backIcon: boolean = false;
if (Browser.isDevice) {
backIcon = true;
this.parent.mobFilter = false;
}
this.filterInputObj = Input.createInput(
{
element: this.filterInput,
buttons: backIcon ? [searchBackIcon, filterBarClearIcon] : [filterBarClearIcon],
properties: { placeholder: this.parent.filterBarPlaceholder }
},
this.parent.createElement
);
if (!isNullOrUndefined(this.parent.cssClass)) {
if (this.parent.cssClass.split(' ').indexOf('e-outline') !== -1) {
addClass([this.filterInputObj.container], 'e-outline');
} else if (this.parent.cssClass.split(' ').indexOf('e-filled') !== -1) {
addClass([this.filterInputObj.container], 'e-filled');
}
}
append([this.filterInputObj.container], this.parent.filterParent);
prepend([this.parent.filterParent], args.popupElement);
attributes(this.filterInput, {
'aria-disabled': 'false',
'aria-owns': this.parent.element.id + '_options',
'role': 'listbox',
'aria-activedescendant': null,
'autocomplete': 'off',
'autocorrect': 'off',
'autocapitalize': 'off',
'spellcheck': 'false'
});
this.clearIconElement = this.filterInput.parentElement.querySelector('.' + clearIcon);
if (!Browser.isDevice && this.clearIconElement) {
EventHandler.add(this.clearIconElement, 'mousedown', this.clearText, this);
(this.clearIconElement as HTMLElement).style.visibility = 'hidden';
}
EventHandler.add(this.filterInput, 'input', this.parent.onInput, this.parent);
EventHandler.add(this.filterInput, 'keyup', this.parent.keyUp, this.parent);
EventHandler.add(this.filterInput, 'keydown', this.parent.onKeyDown, this.parent);
EventHandler.add(this.filterInput, 'blur', this.onBlurHandler, this);
EventHandler.add(this.filterInput, 'paste', this.parent.pasteHandler, this.parent);
this.parent.searchBoxHeight = (this.filterInputObj.container.parentElement).getBoundingClientRect().height;
return this.filterInputObj;
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
private clickOnBackIcon(e: EventHandler): void {
this.parent.hidePopup();
removeClass([document.body, this.parent.popupObj.element], popupFullScreen);
this.parent.inputElement.focus();
}
private clearText(e: MouseEvent): void {
(this.parent.targetInputElement as HTMLInputElement).value = '';
if (this.parent.allowFiltering && (this.parent.targetInputElement as HTMLInputElement).value === '') {
this.parent.search(null);
}
this.parent.refreshPopup();
this.parent.refreshListItems(null);
(this.clearIconElement as HTMLElement).style.visibility = 'hidden';
this.filterInput.focus();
this.setReorder(e);
e.preventDefault();
}
private setDeviceSearchBox(): void {
this.parent.popupObj.element.classList.add(device);
this.parent.popupObj.element.classList.add(mobileFilter);
this.parent.popupObj.position = { X: 0, Y: 0 };
this.parent.popupObj.dataBind();
this.setSearchBoxPosition();
this.backIconElement = this.filterInputObj.container.querySelector('.e-back-icon');
this.clearIconElement = this.filterInputObj.container.querySelector('.' + clearIcon);
(this.clearIconElement as HTMLElement).style.visibility = 'hidden';
EventHandler.add(this.backIconElement, 'click', this.clickOnBackIcon, this);
EventHandler.add(this.clearIconElement, 'click', this.clearText, this);
}
private setSearchBoxPosition(): void {
const searchBoxHeight: number = this.filterInput.parentElement.getBoundingClientRect().height;
let selectAllHeight: number = 0;
if (this.checkAllParent) {
selectAllHeight = this.checkAllParent.getBoundingClientRect().height;
}
this.parent.popupObj.element.style.maxHeight = '100%';
this.parent.popupObj.element.style.width = '100%';
this.parent.list.style.maxHeight = (window.innerHeight - searchBoxHeight - selectAllHeight) + 'px';
this.parent.list.style.height = (window.innerHeight - searchBoxHeight - selectAllHeight) + 'px';
const clearElement: Element = this.filterInput.parentElement.querySelector('.' + clearIcon);
detach(this.filterInput);
clearElement.parentElement.insertBefore(this.filterInput, clearElement);
}
protected setPopupFullScreen(): void {
attributes(this.parent.popupObj.element, { style: 'left:0px;right:0px;top:0px;bottom:0px;' });
addClass([document.body, this.parent.popupObj.element], popupFullScreen);
this.parent.popupObj.element.style.maxHeight = '100%';
this.parent.popupObj.element.style.width = '100%';
}
protected targetElement(): string {
if (!isNullOrUndefined(this.clearIconElement)) {
this.parent.targetInputElement = this.filterInput;
(this.clearIconElement as HTMLElement).style.visibility = this.parent.targetInputElement.value === '' ? 'hidden' : 'visible';
}
return (this.parent.targetInputElement as HTMLInputElement).value;
}
private onBlurHandler(e: MouseEvent): void {
if (!this.parent.element.classList.contains('e-listbox')) {
let target: HTMLElement;
if (this.parent.keyAction) {
return;
}
if (Browser.isIE) {
target = !isNullOrUndefined(e) && <HTMLElement>e.target;
}
if (!Browser.isIE) {
target = !isNullOrUndefined(e) && <HTMLElement>e.relatedTarget;
}
// eslint-disable-next-line max-len
if (this.parent.popupObj && document.body.contains(this.parent.popupObj.element) && this.parent.popupObj.element.contains(target)
&& !Browser.isIE && this.filterInput) {
this.filterInput.focus();
return;
}
if (this.parent.scrollFocusStatus && this.filterInput) {
e.preventDefault();
this.filterInput.focus();
this.parent.scrollFocusStatus = false;
return;
}
if (this.parent.popupObj && document.body.contains(this.parent.popupObj.element)
&& !this.parent.popupObj.element.classList.contains('e-popup-close')) {
this.parent.inputFocus = false;
this.parent.updateValueState(e, this.parent.value, this.parent.tempValues);
this.parent.dispatchEvent(this.parent.hiddenElement as HTMLElement, 'change');
}
if (this.parent.popupObj && document.body.contains(this.parent.popupObj.element) &&
!this.parent.popupObj.element.classList.contains('e-popup-close')) {
this.parent.inputFocus = false;
this.parent.overAllWrapper.classList.remove(FOCUS);
this.parent.trigger('blur');
this.parent.focused = true;
}
if (this.parent.popupObj && document.body.contains(this.parent.popupObj.element) &&
!this.parent.popupObj.element.classList.contains('e-popup-close') && !Browser.isDevice) {
this.parent.hidePopup();
}
}
}
protected onDocumentClick(e: MouseEvent): void {
if (this.parent.getLocaleName() !== 'listbox') {
const target: HTMLElement = <HTMLElement>e.target;
if (!isNullOrUndefined(this.parent.popupObj) && closest(target, '[id="' + this.parent.popupObj.element.id + '"]')) {
if (!(this.filterInput && this.filterInput.value !== '')) {
e.preventDefault();
}
}
if (!(!isNullOrUndefined(this.parent.popupObj) && closest(target, '[id="' + this.parent.popupObj.element.id + '"]')) &&
!this.parent.overAllWrapper.contains(e.target as Node)) {
if (this.parent.overAllWrapper.classList.contains(dropDownBaseClasses.focus) || this.parent.isPopupOpen()) {
this.parent.inputFocus = false;
this.parent.scrollFocusStatus = false;
this.parent.hidePopup();
this.parent.onBlurHandler(e, true);
this.parent.focused = true;
}
} else {
this.parent.scrollFocusStatus = (Browser.isIE || Browser.info.name === 'edge') &&
(document.activeElement === this.filterInput);
}
if (!this.parent.overAllWrapper.contains(e.target as Node) && this.parent.overAllWrapper.classList.contains('e-input-focus') &&
!this.parent.isPopupOpen()) {
if (Browser.isIE) {
this.parent.onBlurHandler();
} else {
this.parent.onBlurHandler(e);
}
}
if (this.filterInput === target) {
this.filterInput.focus();
}
}
}
private getFocus(e: IUpdateListArgs): void {
this.parent.overAllWrapper.classList.remove(FOCUS);
if (this.parent.keyAction && e.value !== 'clear' && e.value !== 'focus') {
this.parent.keyAction = false;
return;
}
if (e.value === 'focus') {
this.filterInput.focus();
this.parent.removeFocus();
EventHandler.remove(this.parent.list, 'keydown', this.parent.onKeyDown);
}
if (e.value === 'clear') {
this.filterInput.value = '';
(this.clearIconElement as HTMLElement).style.visibility = 'hidden';
}
}
private checkSelectAll(e: IUpdateListArgs): void {
if (e.value === 'check' && this.checkAllParent.getAttribute('aria-checked') !== 'true') {
this.changeState(this.checkAllParent, e.value, null, null, false);
this.setLocale(true);
}
if (e.value === 'uncheck') {
this.changeState(this.checkAllParent, e.value, null, null, false);
this.setLocale();
}
if (e.value === 'indeterminate') {
this.changeState(this.checkAllParent, e.value, null, null, false);
this.setLocale();
}
}
private setLocale(unSelect?: boolean): void {
if (this.parent.selectAllText !== 'Select All' || this.parent.unSelectAllText !== 'Unselect All') {
const template: string = unSelect ? this.parent.unSelectAllText : this.parent.selectAllText;
this.selectAllSpan.textContent = '';
const compiledString: Function = compile(template);
const templateName: string = unSelect ? 'unSelectAllText' : 'selectAllText';
for (const item of compiledString({}, this.parent, templateName, null, !this.parent.isStringTemplate)) {
this.selectAllSpan.textContent = item.textContent;
}
} else {
const l10nLocale: Object = { selectAllText: 'Select All', unSelectAllText: 'Unselect All' };
let l10n: L10n = new L10n(this.parent.getLocaleName(), {}, this.parent.locale);
if (l10n.getConstant('selectAllText') === '') {
l10n = new L10n('dropdowns', l10nLocale, this.parent.locale);
}
this.selectAllSpan.textContent = unSelect ? l10n.getConstant('unSelectAllText') : l10n.getConstant('selectAllText');
}
}
private getActiveList(args: IUpdateListArgs): void {
if (args.li.classList.contains('e-active')) {
this.activeLi.push(args.li.cloneNode(true) as HTMLElement);
} else {
this.activeLi.splice(args.index, 1);
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
private setReorder(args: IUpdateListArgs | MouseEvent): void {
if (this.parent.enableSelectionOrder && !isNullOrUndefined(this.parent.value)) {
const activeLiCount: number = this.parent.ulElement.querySelectorAll('li.e-active').length;
let remLi: NodeListOf<Element>;
const ulEle: HTMLElement = this.parent.createElement('ul', {
className: 'e-list-parent e-ul e-reorder'
});
if (activeLiCount > 0) {
append(this.parent.ulElement.querySelectorAll('li.e-active'), ulEle);
remLi = this.parent.ulElement.querySelectorAll('li.e-active');
addClass(remLi, 'e-reorder-hide');
prepend([ulEle], this.parent.list);
}
this.parent.focusAtFirstListItem();
}
}
}
export interface ItemCreatedArgs {
curData: { [key: string]: Object }
item: HTMLElement
text: string
}
export interface IUpdateListArgs {
module: string
enable: boolean
li: HTMLElement
e: MouseEvent | KeyboardEventArgs
popupElement: HTMLElement
value: string
index: number
} | the_stack |
import { collection, Model, ICollection } from '..'
describe('collection', () => {
it('can be created', () => {
const c = collection<{}>()
expect(c).toBeDefined()
expect(c.items).toBeDefined()
})
describe('#set', () => {
it('adds and reuses object', () => {
const c = collection<Model>({
create: input => new Model(input),
update: (existing, input) => existing.set(input)
})
const result = c.set({ id: 1 })
const result2 = c.set({ id: 1, top: 'kek' })
expect(result).toBeInstanceOf(Model)
expect(result2).toBeInstanceOf(Model)
expect(result).toBe(result2)
})
it('returns undefined when passed undefined', () => {
const c = collection<Model>()
expect(c.set()).toBe(undefined)
})
it('defaults to "id" for id attribute', () => {
const c = collection<Model>({ idAttribute: '' })
c.set({ id: 1 })
expect(c.get(1)).toBeDefined()
})
it('supports adding multiple', () => {
const c = collection<{ id: number }>()
const a = c.set([{ id: 1 }, { id: 2 }])
const m1 = a![0]
const m2 = a![1]
expect(m1.id).toBe(1)
expect(m2.id).toBe(2)
})
describe('circular reference parsing', () => {
it('only adds one', () => {
const c1 = collection<any>({
create: data => parseParent(data),
update: (existing, data) => Object.assign(existing, parseParent(data))
})
const c2 = collection<any>({
create: data => parseChild(data),
update: (existing, data) => Object.assign(existing, parseChild(data))
})
const data = {
id: 'p1',
prop1: 'hello',
child: {
id: 'c1',
parent: {
id: 'p1',
prop2: 'world'
}
}
}
const parent = c1.set(data)
const child = c2.get('c1')
expect(c1.length).toBe(1)
expect(c2.length).toBe(1)
expect(parent.prop1).toBe('hello')
expect(parent.prop2).toBe('world')
expect(parent.child).toBe(child)
expect(child.parent).toBe(parent)
function parseParent({ child, ...data }: any) {
child = c2.set(child)
return {
...data,
child
}
}
function parseChild({ parent, ...data }: any) {
parent = c1.set(parent)
return {
...data,
parent
}
}
})
})
})
describe('#create', () => {
it('acts like #set if an id is present', () => {
const c = collection<{ id: number }>()
const o1 = c.set({ id: 1 })
const o2 = c.create({ id: 1 })
expect(o1).toBe(o2)
})
it('adds the model even if it does not have an id', () => {
const c = collection<{ id: number; hello?: string }>()
const o1 = c.set({ id: 1 })
const o2 = c.create({ hello: 'world' })
expect(o2.hello).toBe('world')
expect(o2).not.toBe(o1)
})
it('adds multiple', () => {
const c = collection<{ id: number; hello?: string }>()
c.set({ id: 1 })
const [o2, o3] = c.create([
{ hello: 'world' },
{ id: 3, hello: 'libx' }
] as any[])
expect(o2.hello).toBe('world')
expect(o3.id).toBe(3)
})
})
describe('#add', () => {
it('adds a single or multiple models', () => {
const c = collection<{ id: number }>()
c.add({ id: 1 })
expect(c.length).toBe(1)
c.add([{ id: 2 }, { id: 3 }])
expect(c.length).toBe(3)
})
it('does not add duplicate instances', () => {
const c = collection<{ id: number }>()
const item1 = { id: 1 }
c.add(item1)
expect(c.length).toBe(1)
expect(item1).toBe(c.get(1))
c.add(item1)
expect(c.length).toBe(1)
c.add([item1, { id: 2 }])
expect(c.length).toBe(2)
})
})
describe('#get', () => {
it('returns objects based on default resolution strategy (id lookup)', () => {
const c = collection<{ id: number }>()
const setted = c.set({ id: 1 })
const getted = c.get('1')
expect(getted).toBe(setted)
})
it('returns undefined when not found', () => {
const c = collection<{ id: number }>()
c.set([{ id: 1 }])
c.add({} as any)
expect(c.get(2)).toBe(undefined)
})
it('returns undefined when passed undefined or null', () => {
const c = collection<Model>()
expect(c.get(undefined)).toBe(undefined)
expect(c.get(null)).toBe(undefined)
})
it('can get multiple items', () => {
const c = collection<{ id: number }>()
c.set({ id: 1 })
c.set({ id: 2 })
const result = c.get([1, 2, 3] as any[])
expect(result.length).toBe(3)
expect(result[0]!.id).toBe(1)
expect(result[1]!.id).toBe(2)
expect(result[2]).toBe(undefined)
})
it('supports overriding how ID resolution is done on both ends', () => {
interface IData {
_id: string
}
interface IModel {
identifier: number
top?: string
}
const c = collection<IModel>({
create: (data: IData) => ({ identifier: parseInt(data._id, 10) }),
getDataId: (input: IData) => input._id,
getModelId: (input: IModel) => input.identifier
})
const result = c.set({ _id: '1' })
const result2 = c.set({ _id: '1', top: 'kek' })
expect(result!.identifier).toBe(1)
expect(result2!.identifier).toBe(1)
expect(result).toBe(result2)
expect(result!.top).toBe('kek')
expect(result2!.top).toBe('kek')
})
it('throws when an invalid ID is returned from the data', () => {
let c = collection<{ id: number }>({
getDataId: () => null
})
expect(() => c.set({ id: 2 })).toThrow(/null.*ID/i)
c = collection<{ id: number }>({
getDataId: () => undefined
})
expect(c.set({ id: 2 })).toBeUndefined()
})
it('clears the ID cache', () => {
const c = collection<{ id: number }>({ idAttribute: null! })
c.set({ id: 1 })
c.set({ id: 2 })
const got = c.get(1)
expect(got!.id).toBe(1)
c.remove('1')
expect(c.get('1')).toBeUndefined()
expect(c.get('2')).not.toBeUndefined()
})
})
describe('#move', () => {
it('works', () => {
type Value = { id: number }
const c: ICollection<Value> = collection<Value>()
c.set([{ id: 1 }, { id: 2 }, { id: 3 }])
c.move(1, 1)
c.move(0, 2)
expect(c.items[0].id).toBe(2)
expect(c.items[1].id).toBe(3)
expect(c.items[2].id).toBe(1)
c.move(2, 0)
expect(c.items[0].id).toBe(1)
expect(c.items[1].id).toBe(2)
expect(c.items[2].id).toBe(3)
})
it('checks indexes', () => {
type Value = { id: number }
const c: ICollection<Value> = collection<Value>()
c.set([{ id: 1 }, { id: 2 }, { id: 3 }])
expect(() => c.move(-1, 2)).toThrowErrorMatchingSnapshot()
expect(() => c.move(0, 3)).toThrowErrorMatchingSnapshot()
})
})
describe('lodash functions', () => {
type Value = { id: number; name: string; gender: 'male' | 'female' }
let c: ICollection<Value>
beforeEach(() => {
c = collection<Value>()
c.set([
{
id: 1,
name: 'Jeff',
gender: 'male'
},
{
id: 2,
name: 'Amanda',
gender: 'female'
},
{
id: 3,
name: 'Will',
gender: 'male'
}
])
})
it('#map', () => {
const mapped = c.map(x => x.name)
expect(mapped).toEqual(['Jeff', 'Amanda', 'Will'])
})
it('#filter', () => {
const male = c.filter(x => x.gender === 'male')
expect(male.length).toBe(2)
expect(male[0].id).toBe(1)
expect(male[1].id).toBe(3)
})
it('#find', () => {
const jeff = c.find(x => x.name === 'Jeff')
expect(jeff).toBeDefined()
expect(jeff!.id).toBe(1)
})
it('#slice', () => {
expect(c.slice(0, 1).length).toBe(1)
})
it('#orderBy', () => {
let ordered = c.orderBy(['name'], ['asc'])
expect(ordered[0].name).toBe('Amanda')
expect(ordered[1].name).toBe('Jeff')
expect(ordered[2].name).toBe('Will')
ordered = c.orderBy(['name'], ['desc'])
expect(ordered[0].name).toBe('Will')
expect(ordered[1].name).toBe('Jeff')
expect(ordered[2].name).toBe('Amanda')
})
it('#forEach', () => {
const touchedValues: Array<Value> = []
const touchedIndexes: Array<number> = []
c.forEach((item, index) => {
touchedValues.push(item)
touchedIndexes.push(index)
})
expect(touchedValues).toEqual(c.slice())
expect(touchedIndexes).toEqual(c.map((x, i) => i))
})
it('#at', () => {
expect(c.at(0)).toBe(c.items[0])
expect(c.at(1)).toBe(c.items[1])
})
})
describe('#clear', () => {
it('clears the collection', () => {
const c = collection<{ id: number }>()
c.set([{ id: 1 }, { id: 2 }])
expect(c.length).toBe(2)
c.clear()
expect(c.length).toBe(0)
})
})
describe('#remove', () => {
let c: ICollection<{ id: number }>
beforeEach(() => {
c = collection<{ id: number }>()
c.set([
{
id: 1
},
{
id: 2
}
])
})
it('removes by id', () => {
expect(c.length).toBe(2)
c.remove('1')
expect(c.length).toBe(1)
expect(c.get(2)).toEqual({ id: 2 })
})
it('removes with a model reference', () => {
expect(c.length).toBe(2)
c.remove(c.get(1)!)
expect(c.length).toBe(1)
expect(c.get(2)).toEqual({ id: 2 })
})
it('returns self even when not removing anything', () => {
expect(c.remove('1234')).toBe(c)
})
})
// describe('bench', () => {
// it('does not crumble', function () {
// this.timeout(100000)
// const c = collection<{ id: number, hello: string }, {}>()
// for (let i = 1; i <= 500000; i++) {
// c.add({ id: i, hello: 'world' })
// }
// console.time('Lets do this')
// c.get(1000)
// console.timeEnd('Lets do this')
// })
// })
}) | the_stack |
import { InanoSQLPlugin, InanoSQLInstance, deleteRowFilter, configTableFilter, adapterWriteFilter, willConnectFilter, InanoSQLIndex, InanoSQLQuery, IWhereCondition, addRowFilter, updateRowFilter, customQueryFilter, configTableSystemFilter, addRowEventFilter } from "@nano-sql/core/lib/interfaces";
import { allAsync, getFnValue, crowDistance, resolvePath, objectsEqual, deg2rad, adapterFilters, deepGet, buildQuery, noop, hash, _nanoSQLQueue, maybeAssign, chainAsync } from "@nano-sql/core/lib/utilities";
import * as metaphone from "metaphone";
import * as stemmer from "stemmer";
export interface FuzzySearchTokenizer {
(tableName: string, tableId: string, path: string[], value: string): {
w: string; // tokenized output
i: number; // location of word in string
o: string; // original string
}[]
}
export const stopWords = [
"a", "about", "after", "all", "also", "am", "an", "and", "andor", "another", "any",
"are", "as", "at", "be", "because", "been", "before", "being", "between",
"both", "but", "by", "came", "can", "come", "could", "did", "do", "each",
"for", "from", "get", "got", "had", "has", "have", "he", "her", "here",
"him", "himself", "his", "how", "i", "if", "in", "into", "is", "it", "like",
"make", "many", "me", "might", "more", "most", "much", "must", "my", "never",
"now", "of", "on", "only", "or", "other", "our", "out", "over", "said", "same",
"see", "should", "since", "some", "still", "such", "take", "than", "that", "the",
"their", "them", "then", "there", "these", "they", "this", "those", "through",
"to", "too", "under", "up", "very", "was", "way", "we", "well", "were", "what",
"where", "which", "while", "who", "with", "would", "you", "your"
];
export const defaultTokenizer = (type: "english" | "english-meta" | "english-stem", stpWrds: string[], decimalPoints: number = 4): FuzzySearchTokenizer => {
return (tableName, tableId, path, value) => {
const isStopWord = (word: string): boolean => {
return !word || word === null ? true : // is this word falsey? (ie no length, undefined, etc);
String(word).length === 1 ? true : // is this word 1 length long?
stpWrds.indexOf(word) !== -1; // does word match something in the stop word list?
};
// Step 1, Clean up and normalize the text
const words: string[] = String(value || "")
// everything to lowercase
.toLowerCase()
// normalize fractions and numbers (1/4 => 0.2500, 1,000,235 => 100235.0000)
.replace(/(\d+)\/(\d+)|(?:\d+(?:,\d+)*|\d+)(?:\.\d+)?/gmi, (all, top, bottom) => top || bottom ? (parseInt(top) / parseInt(bottom)).toFixed(decimalPoints) : (parseFloat(all.replace(/\,/gmi, ""))).toFixed(decimalPoints))
// replace dashes, underscores, anything like parantheses, slashes, newlines and tabs with a single whitespace
.replace(/\-|\_|\[|\]|\(|\)|\{|\}|\r?\n|\r|\t/gmi, " ")
// remove anything but letters, numbers and decimals inside numbers with nothing.
.replace(/[^\w\s]|(\d\.)/gmi, "$1")
// remove white spaces larger than 1 with 1 white space.
.replace(/\s+/g, " ")
.split(" ");
// Step 2, tokenize!
switch (type) {
case "english": return words.map((w, i) => ({ // 220 words/ms
i: i,
w: isNaN(w as any) ? (isStopWord(w) ? "" : metaphone(stemmer(w))) : w,
o: isStopWord(w) ? "" : stemmer(w)
})).filter(f => f.w);
case "english-stem": return words.map((w, i) => ({ // 560 words/ms
i: i,
w: isNaN(w as any) ? (isStopWord(w) ? "" : stemmer(w)) : w,
o: isStopWord(w) ? "" : stemmer(w)
})).filter(f => f.w);
case "english-meta": return words.map((w, i) => ({ // 270 words/ms
i: i,
w: isNaN(w as any) ? (isStopWord(w) ? "" : metaphone(w)) : w,
o: isStopWord(w) ? "" : stemmer(w)
})).filter(f => f.w);
}
// no tokenization: 2,684 words/ms
return words.map((w, i) => ({ w, i, o: w }));
}
}
export interface IFuzzyIndex {
indexId: string;
tableName: string;
tableId: string;
path: string[];
tokenizer: FuzzySearchTokenizer;
}
export interface IFuzzyTokenData {
wrd: string,
ids: { id: any, i: number[] }[]
}
let searchIndexes: {
[tableId: string]: IFuzzyIndex[]
} = {};
let indexLocks: {
[tableId: string]: {
[token: string]: boolean;
}
} = {};
const addRowToFuzzy = (newRow: any, tableId: string, pkPath: string[], nSQL: InanoSQLInstance, query: InanoSQLQuery, complete: (err?: any) => void) => {
const newRowData = newRow;
const newRowPK = deepGet(pkPath, newRowData);
const filters = adapterFilters(query.databaseID, nSQL, query);
allAsync(searchIndexes[tableId], (item: IFuzzyIndex, i, next, err) => {
const phrase = deepGet(item.path, newRowData);
if (typeof phrase !== "string" || !phrase) { // nothing to index
next();
return;
}
const phraseHash = hash(phrase);
const tokens = item.tokenizer(item.tableName, item.tableId, item.path, phrase);
const mergedTokens: { [token: string]: number[] } = tokens.reduce((prev, cur) => {
if (!prev[cur.w]) {
prev[cur.w] = [];
}
prev[cur.w].push(cur.i);
return prev;
}, {});
const tokenArray = tokens.map(s => s.i + ":" + s.o);
const indexTableNameWords = "_" + tableId + "_fuzzy_words_" + item.path.join(".");
// write cache of row index data
filters.write(indexTableNameWords, newRowPK, {
id: newRowPK,
hash: phraseHash,
tokens: tokenArray
}, () => {
// write words to index
const indexTable = "_" + tableId + "_fuzzy_" + item.path.join(".");
const indexTableId = nSQL.getDB(query.databaseID)._tableIds[indexTable];
allAsync(Object.keys(mergedTokens), (word: string, k, nextToken, errToken) => {
const writeToken = () => {
filters.read(indexTable, word, (tokenRow?: { wrd: string, ids: any[] }) => {
const useRow = maybeAssign(tokenRow) || {
wrd: word,
ids: [] as any[]
}
useRow.ids.push({ id: newRowPK, i: mergedTokens[word] });
filters.write(indexTable, word, useRow, () => {
delete indexLocks[tableId][word];
nextToken();
}, (err) => {
delete indexLocks[tableId][word];
errToken(err);
})
}, (err) => {
delete indexLocks[tableId][word];
errToken(err);
});
};
const checkTokenLock = () => {
if (indexLocks[tableId][word]) {
setTimeout(() => {
checkTokenLock();
}, 2);
} else {
indexLocks[tableId][word] = true;
writeToken();
}
}
checkTokenLock();
}).then(next).catch(err);
}, err);
}).then(() => {
complete();
}).catch(complete);
}
const rmRowFromFuzzy = (newRowData: any, pkPath: string[], databaseID: string, nSQL: InanoSQLInstance, query: InanoSQLQuery, tableId: string, complete: (err?: any) => void) => {
const newRowPK = deepGet(pkPath, newRowData);
const filters = adapterFilters(databaseID, nSQL, query);
allAsync(searchIndexes[tableId], (item: IFuzzyIndex, i, next, err) => {
const indexTableNameWords = "_" + tableId + "_fuzzy_words_" + item.path.join(".");
const indexTableNameWordsId = nSQL.getDB(databaseID)._tableIds[indexTableNameWords];
// remove row data cache
filters.delete(indexTableNameWords, newRowPK, () => {
const phrase = deepGet(item.path, newRowData);
if (typeof phrase !== "string" || !phrase) { // nothing to delete
next();
return;
}
const indexTable = "_" + tableId + "_fuzzy_" + item.path.join(".");
const indexTableId = nSQL.getDB(databaseID)._tableIds[indexTable];
const tokens = item.tokenizer(item.tableName, item.tableId, item.path, phrase);
const mergedTokens: { [token: string]: number[] } = tokens.reduce((prev, cur) => {
if (!prev[cur.w]) {
prev[cur.w] = [];
}
prev[cur.w].push(cur.i);
return prev;
}, {});
allAsync(Object.keys(mergedTokens), (word: string, k, nextToken, errToken) => {
const writeToken = () => {
filters.read(indexTable, word, (tokenRow?: { wrd: string, ids: { id: any, i: number[] }[] }) => {
const useRow = maybeAssign(tokenRow) || {
wrd: word,
ids: [] as { id: any, i: number[] }[]
}
let idx = -1;
let i = useRow.ids.length;
while (i-- && idx === -1) {
if (useRow.ids[i].id === newRowPK) {
idx === i;
}
}
if (idx !== -1) {
useRow.ids.splice(idx, 1);
if (!useRow.ids.length) { // no rows left for this token
filters.delete(indexTable, word, () => {
delete indexLocks[tableId][word];
nextToken();
}, (err) => {
delete indexLocks[tableId][word];
errToken(err);
})
} else { // write other row data back
filters.write(indexTable, word, useRow, () => {
delete indexLocks[tableId][word];
nextToken();
}, (err) => {
delete indexLocks[tableId][word];
errToken(err);
})
}
} else {
delete indexLocks[tableId][word];
nextToken();
}
}, (err) => {
delete indexLocks[tableId][word];
errToken(err);
});
};
const checkTokenLock = () => {
if (indexLocks[tableId][word]) {
setTimeout(() => {
checkTokenLock();
}, 2);
} else {
indexLocks[tableId][word] = true;
writeToken();
}
}
checkTokenLock();
}).then(next).catch(err);
}, err);
}).then(() => {
complete();
}).catch(complete);
}
export const FuzzyUserSanitize = (str: string) => {
return String(str).replace(/\'|\,/gmi, "");
}
export const FuzzySearch = (): InanoSQLPlugin => {
let nSQL: InanoSQLInstance;
return {
name: "Fuzzy Search",
version: 2.02,
filters: [
{
name: "willConnect",
priority: 1000,
call: (inputArgs: willConnectFilter, complete: (args: willConnectFilter) => void, cancel: (info: any) => void) => {
nSQL = inputArgs.res;
complete(inputArgs);
nSQL.functions["SEARCH"] = {
type: "S",
call: (query, row, prev, gpsCol: string, lat: string, lon: string) => {
// no standard usage
return {
result: 0
};
},
checkIndex: (query, fnArgs, where) => {
const tableId = nSQL.getDB(query.databaseID)._tableIds[query.table as string];
// no indexes on this table
if (!searchIndexes[tableId] || !searchIndexes[tableId].length) {
return false;
}
// search all fuzzy indexes
if (fnArgs[0] === "*") {
return {
index: "*",
parsedFn: { name: "SEARCH", args: fnArgs },
comp: where[1],
value: where[2],
col: String(-1)
};
}
const indexPath = resolvePath(fnArgs[0]);
const indexJoined = indexPath.join(".");
let idx = -1;
let i = searchIndexes[tableId].length;
while (i-- && idx === -1) {
if (searchIndexes[tableId][i].path.join(".") == indexJoined) {
idx = i;
}
}
// no matching index found
if (idx === -1) {
return false;
}
return {
index: searchIndexes[tableId][idx].indexId,
parsedFn: { name: "SEARCH", args: fnArgs },
comp: where[1],
value: where[2],
col: String(idx)
};
},
queryIndex: (query: InanoSQLQuery, where: IWhereCondition, onlyPKs: boolean, onRow: (row, i) => void, complete: () => void, error: (err) => void) => {
const filters = adapterFilters(query.databaseID, nSQL, query);
const getRows = (PKs: any[]) => {
PKs = PKs.filter((v, i, s) => s.indexOf(v) === i);
if (!PKs.length) {
complete();
return;
}
if (onlyPKs) {
let kk = 0;
while (kk < PKs.length) {
onRow(PKs[kk], kk);
kk++;
}
complete();
}
chainAsync(PKs, (rowKey: any, i, next, err) => {
let counter = 0;
filters.read(query.table as string, rowKey, (row) => {
if (!row) {
next();
return;
}
onRow(row, counter);
counter++;
next();
}, err);
}).then(() => {
complete();
}).catch(error);
}
const tableId = nSQL.getDB(query.databaseID)._tableIds[query.table as string];
let searchTheseIndexes = (parseInt(where.col as any) !== -1 ? [where.index] : searchIndexes[tableId].map(s => s.indexId)) as string[];
let secondaryIndexPKS: any[] = [];
const getNextSearchTerm = (searchIdx: number, indexNum: number) => {
// search done
if (!searchTheseIndexes[indexNum]) {
getRows(secondaryIndexPKS);
return;
}
// out of search terms for this index
// move to next index
if (!(where.parsedFn as any).args[searchIdx]) {
getNextSearchTerm(1, indexNum + 1);
return;
}
// strip trailing and leading quotes from search term
const searchValue = (where.parsedFn as any).args[searchIdx];
const quoteRegex = /^[\"|\'](.*)[\"|\']$/gmi;
const hasQuotes = quoteRegex.exec(searchValue);
const useSeachValue = hasQuotes ? hasQuotes[1] : searchValue;
const useIndex = searchIndexes[tableId][indexNum];
if (!useIndex) {
error("Erro getting fuzzy index!");
return;
}
const phraseTokens = useIndex.tokenizer(useIndex.tableName, useIndex.tableId, useIndex.path, useSeachValue);
// blank search term, cya!
if (!phraseTokens.length) {
complete();
return;
}
const mergedTokens: { [token: string]: number[] } = phraseTokens.reduce((prev, cur) => {
if (!prev[cur.w]) {
prev[cur.w] = [];
}
prev[cur.w].push(cur.i);
return prev;
}, {});
const tokenLocs: {
[token: string]: IFuzzyTokenData;
} = {};
const wordLocs: {
[rowID: string]: {
rowKey: any;
words: { [word: string]: number[]; }
}
} = {};
// get exact matches from secondary index
filters.readIndexKey(query.table as string, searchTheseIndexes[indexNum], useSeachValue, (pk) => {
secondaryIndexPKS.push(pk);
}, () => {
// now do tokenization and search
allAsync(Object.keys(mergedTokens), (word: string, i, nextWord, errWord) => {
const indexTable = "_" + tableId + "_fuzzy_" + useIndex.path.join(".");
const indexTableId = nSQL.getDB(query.databaseID)._tableIds[indexTable];
filters.read(indexTable, word, (tokenRow?: IFuzzyTokenData) => {
const useRow = tokenRow || {
wrd: word,
ids: []
};
useRow.ids.forEach((rowData) => {
if (!wordLocs[String(rowData.id)]) {
wordLocs[String(rowData.id)] = {
rowKey: rowData.id,
words: {}
};
}
wordLocs[String(rowData.id)].words[useRow.wrd] = rowData.i;
});
tokenLocs[word] = useRow;
nextWord();
}, errWord);
}).then(() => {
if (phraseTokens.length <= 1) { // single word search (easy and quick)
if ((where.comp === "=" || where.comp.indexOf("=") !== -1) && where.comp !== "!=" && where.value === 0) {
// doing exact match
Object.keys(tokenLocs).forEach((word) => {
secondaryIndexPKS = secondaryIndexPKS.concat(tokenLocs[word].ids.map(r => r.id));
});
getNextSearchTerm(searchIdx + 1, indexNum);
} else {
if (secondaryIndexPKS.length) {
getNextSearchTerm(searchIdx + 1, indexNum);
} else {
// no matches
getNextSearchTerm(searchIdx + 1, indexNum);
}
}
} else { // phrase search (oh boy)
const phraseWords = phraseTokens.map(s => s.w);
const phraseLocs = phraseTokens.map(s => s.i);
let rowSlots: {
rowKey: any,
wordSlots: number[][];
}[] = [];
Object.keys(wordLocs).forEach((rowID) => {
const rowData = wordLocs[rowID];
const newSlot: {
rowKey: any,
wordSlots: number[][];
} = {
rowKey: rowData.rowKey,
wordSlots: []
};
phraseWords.forEach((phraseWord, jj) => {
newSlot.wordSlots[jj] = rowData.words[phraseWord] || [];
});
rowSlots.push(newSlot);
});
rowSlots.forEach((slot) => {
// best score === 0;
let score = 100000;
/*
slot.wordSlots contains an array of phrase matches, in order of the search phrase, found in this row.
each wordSlot contains all the locations for the word match in the target row
we're going to scroll through every possible combination of matched phrases to find the best matches
*/
const recursiveMatch = (...positions: number[]) => {
let baseScore = 0;
// checkLocs contains the phrase locations we are testing
const checkLocs = slot.wordSlots.map((s, i) => {
if (!slot.wordSlots[i].length) {
baseScore += 1;
}
return slot.wordSlots[i][positions[i]];
});
let firstPoint;
let phrasePoint;
for (let i = 0; i < checkLocs.length; i++) {
if (checkLocs[i] === undefined) {
baseScore++;
} else {
if (firstPoint === undefined) {
firstPoint = checkLocs[i];
phrasePoint = phraseLocs[i];
} else {
const diff = Math.abs((checkLocs[i] - firstPoint) - 1);
const phraseDiff = Math.abs((phraseLocs[i] - phrasePoint) - 1);
baseScore += Math.abs(diff - phraseDiff);
firstPoint = checkLocs[i];
phrasePoint = phraseLocs[i];
}
}
}
// set up score
score = Math.min(score, baseScore);
// setup next loop
// start jumping to the next item on the last phrase, then the next phrase...
let nextAdjustPos = slot.wordSlots.length - 1;
let nextIndex = positions[nextAdjustPos] + 1;
while (nextAdjustPos >= 0 && !slot.wordSlots[nextAdjustPos][nextIndex]) {
nextAdjustPos--;
nextIndex = positions[nextAdjustPos] + 1;
}
const newPos = positions.slice();
newPos[nextAdjustPos] = nextIndex;
// if this is undefined we've ran out of comparisons
if (newPos[nextAdjustPos]) {
recursiveMatch(...newPos);
}
}
// start at position 0, 0, 0, 0, 0...
recursiveMatch(...slot.wordSlots.map(s => 0));
switch (where.comp) {
case "=":
if (score === where.value) {
secondaryIndexPKS.push(slot.rowKey);
}
break;
case ">=":
if (score >= where.value) {
secondaryIndexPKS.push(slot.rowKey);
}
break;
case "<=":
if (score <= where.value) {
secondaryIndexPKS.push(slot.rowKey);
}
break;
case "<":
if (score < where.value) {
secondaryIndexPKS.push(slot.rowKey);
}
break;
case ">":
if (score > where.value) {
secondaryIndexPKS.push(slot.rowKey);
}
break;
case "!=":
if (score !== where.value) {
secondaryIndexPKS.push(slot.rowKey);
}
break;
}
});
getNextSearchTerm(searchIdx + 1, indexNum);
}
});
}, error);
}
getNextSearchTerm(1, 0);
}
}
}
},
{ // grab the search index values from the existing index definitions
name: "configTableSystem",
priority: 1000,
call: (inputArgs: configTableSystemFilter, complete: (args: configTableSystemFilter) => void, cancel: (info: any) => void) => {
const tableId = inputArgs.res.id;
const tableName = inputArgs.res.name;
const pkKey = "id:" + inputArgs.res.pkType;
if (inputArgs.res.name.indexOf("_") === 0) {
complete(inputArgs);
return;
}
const indexes = inputArgs.res.indexes || {};
searchIndexes[tableId] = [];
indexLocks[tableId] = {};
Object.keys(indexes).forEach((indexId) => {
if (indexes[indexId].props.search) {
if (typeof indexes[indexId].props.search === "boolean") {
searchIndexes[tableId].push({
indexId: indexId,
tableName: tableName,
tableId: tableId,
path: indexes[indexId].path,
tokenizer: defaultTokenizer("english", stopWords)
})
} else {
searchIndexes[tableId].push({
indexId: indexId,
tableName: tableName,
tableId: tableId,
path: indexes[indexId].path,
tokenizer: indexes[indexId].props.search.tokenizer || defaultTokenizer("english", stopWords)
})
}
}
});
allAsync(searchIndexes[tableId], (item: IFuzzyIndex, i, next, err) => {
const indexTableName = "_" + tableId + "_fuzzy_" + item.path.join(".");
// store the data for each token
nSQL.triggerQuery(inputArgs.query.databaseID, {
...buildQuery(inputArgs.query.databaseID, nSQL, "", "create table"),
actionArgs: {
name: indexTableName,
_internal: true,
model: {
"wrd:string": { pk: true },
"ids:any[]": {
notNull: true,
model: {
[pkKey]: {},
"i:int[]": {}
}
}
}
}
}, noop, () => {
// store the locations of each token for every row
// allows us to diff updates
const indexTableNameWords = "_" + tableId + "_fuzzy_words_" + item.path.join(".");
nSQL.triggerQuery(inputArgs.query.databaseID, {
...buildQuery(inputArgs.query.databaseID, nSQL, "", "create table"),
actionArgs: {
name: indexTableNameWords,
_internal: true,
model: {
[pkKey]: { pk: true },
"hash:string": {},
"tokens:any": {},
}
}
}, noop, () => {
const indexTableFullNameWords = "_" + tableId + "_fuzzy_full_words_" + item.path.join(".");
nSQL.triggerQuery(inputArgs.query.databaseID, {
...buildQuery(inputArgs.query.databaseID, nSQL, "", "create table"),
actionArgs: {
name: indexTableFullNameWords,
_internal: true,
model: {
"wrd:string": { pk: true },
"ids:any[]": {
notNull: true,
model: {
[pkKey]: {},
"i:int[]": {}
}
}
}
}
}, noop, next, err);
}, err);
}, err);
}).then(() => {
complete(inputArgs);
}).catch((err) => {
cancel(err);
})
}
},
{
name: "addRowEvent",
priority: 1000,
call: (inputArgs: addRowEventFilter, complete: (args: addRowEventFilter) => void, cancel: (info: any) => void) => {
const tableId = nSQL.getDB(inputArgs.query.databaseID)._tableIds[inputArgs.query.table as string];
const pkPath = nSQL.getDB(inputArgs.query.databaseID)._tables[inputArgs.query.table as string].pkCol;
if (!searchIndexes[tableId] || !searchIndexes[tableId].length) { // no indexes for this table
complete(inputArgs);
} else { // add new row
addRowToFuzzy(inputArgs.res.result, tableId, pkPath, nSQL, inputArgs.query, (err) => {
if (err) {
cancel(err);
} else {
complete(inputArgs);
}
});
}
}
},
{
name: "updateRow",
priority: 1000,
call: (inputArgs: updateRowFilter, complete: (args: updateRowFilter) => void, cancel: (info: any) => void) => {
const tableId = nSQL.getDB(inputArgs.query.databaseID)._tableIds[inputArgs.query.table as string];
const pkPath = nSQL.getDB(inputArgs.query.databaseID)._tables[inputArgs.query.table as string].pkCol;
if (!searchIndexes[tableId] || !searchIndexes[tableId].length) { // no indexes for this table
complete(inputArgs);
} else { // update row data
const newRowData = inputArgs.res as any;
const newRowPK = deepGet(pkPath, newRowData);
const filters = adapterFilters(inputArgs.query.databaseID, nSQL, inputArgs.query);
allAsync(searchIndexes[tableId], (item: IFuzzyIndex, i, next, err) => {
const indexTableNameWords = "_" + tableId + "_fuzzy_words_" + item.path.join(".");
const indexTableNameWordsId = nSQL.getDB(inputArgs.query.databaseID)._tableIds[indexTableNameWords];
// read row cache
filters.read(indexTableNameWords, newRowPK, (row: { id: any, hash: string, tokens: string[] }) => {
const useRow = maybeAssign(row) || { id: newRowPK, hash: "", tokens: [] as string[] };
const phrase = deepGet(item.path, newRowData);
// new and old are both empty
if (!useRow.hash && (!phrase || typeof phrase !== "string")) {
next();
return;
}
const phraseHash = hash(String(phrase));
if (phraseHash === useRow.hash) { // no changes in index data
next();
return;
}
const indexTable = "_" + tableId + "_fuzzy_" + item.path.join(".");
const indexTableId = nSQL.getDB(inputArgs.query.databaseID)._tableIds[indexTable];
const tokens = item.tokenizer(item.tableName, item.tableId, item.path, phrase);
const tokenArray = tokens.map(s => s.i + ":" + s.o);
const deleteTokens = useRow.tokens.filter(t => tokenArray.indexOf(t) === -1);
const addTokens = tokenArray.filter(t => useRow.tokens.indexOf(t) === -1);
// adjust tokens
allAsync([deleteTokens, addTokens], (arr: string[], kk, nextArr, errArr) => {
const cleanedTokens = arr.map(s => {
const sp = s.split(":");
const thisPos: string = sp.shift() as any; // shift off index
return { w: sp.join(":"), i: parseInt(thisPos) };
});
const mergedTokens: { [token: string]: number[] } = cleanedTokens.reduce((prev, cur) => {
if (!prev[cur.w]) {
prev[cur.w] = [];
}
prev[cur.w].push(cur.i);
return prev;
}, {});
allAsync(Object.keys(mergedTokens), (word: string, k, nextToken, errToken) => {
const writeToken = () => {
filters.read(indexTable, word, (tokenRow?: IFuzzyTokenData) => {
const useRow: IFuzzyTokenData = maybeAssign(tokenRow) || {
wrd: word,
ids: []
}
let idx = -1;
let i = 0;
while (i < useRow.ids.length && idx === -1) {
if (useRow.ids[i].id === newRowPK) {
idx = i;
}
i++;
}
if (idx !== -1) {
if (kk === 0) { // deleting
useRow.ids[idx].i = useRow.ids[idx].i.filter((pos) => {
return mergedTokens[word].indexOf(pos) === -1;
});
} else { // adding
useRow.ids[idx].i = useRow.ids[idx].i.concat(mergedTokens[word]);
}
// remove row from index data if it has no index values left
if (!useRow.ids[idx].i.length) {
useRow.ids.splice(idx, 1);
}
// no row values left for this token
if (!useRow.ids.length) {
filters.delete(indexTable, word, () => {
delete indexLocks[tableId][word];
nextToken();
}, (err) => {
delete indexLocks[tableId][word];
errToken(err);
})
} else {
filters.write(indexTable, word, useRow, () => {
delete indexLocks[tableId][word];
nextToken();
}, (err) => {
delete indexLocks[tableId][word];
errToken(err);
})
}
} else {
if (kk === 1) { // adding
useRow.ids.push({
id: newRowPK,
i: mergedTokens[word]
});
filters.write(indexTable, word, useRow, () => {
delete indexLocks[tableId][word];
nextToken();
}, (err) => {
delete indexLocks[tableId][word];
errToken(err);
});
} else { // deleting
delete indexLocks[tableId][word];
nextToken();
}
}
}, (err) => {
delete indexLocks[tableId][word];
errToken(err);
});
};
const checkTokenLock = () => {
if (indexLocks[tableId][word]) {
setTimeout(() => {
checkTokenLock();
}, 2);
} else {
indexLocks[tableId][word] = true;
writeToken();
}
}
checkTokenLock();
}).then(next).catch(err);
}).then(() => {
// write new cache data
filters.write(indexTableNameWords, newRowPK, {
id: newRowPK,
hash: phraseHash,
tokens: tokenArray
}, next, err);
})
}, err);
}).then(() => {
complete(inputArgs);
}).catch(cancel);
}
}
},
{
name: "deleteRow",
priority: 1000,
call: (inputArgs: deleteRowFilter, complete: (args: deleteRowFilter) => void, cancel: (info: any) => void) => {
const tableId = nSQL.getDB(inputArgs.query.databaseID)._tableIds[inputArgs.query.table as string];
const pkPath = nSQL.getDB(inputArgs.query.databaseID)._tables[inputArgs.query.table as string].pkCol;
if (!searchIndexes[tableId] || !searchIndexes[tableId].length) { // no indexes for this table
complete(inputArgs);
} else { // delete row data
rmRowFromFuzzy(inputArgs.res, pkPath, inputArgs.query.databaseID as string, nSQL, inputArgs.query, tableId, (err) => {
if (err) {
cancel(err);
} else {
complete(inputArgs);
}
})
}
}
},
{
name: "customQuery",
priority: 1000,
call: (inputArgs: customQueryFilter, complete: (args: customQueryFilter) => void, cancel: (info: any) => void) => {
if (String(inputArgs.query.action).trim().toLowerCase() === "rebuild search") { // capture rebuild search
const table = inputArgs.query.table;
if (typeof table !== "string") {
inputArgs.error("Can't rebuild search on this table type!");
} else {
const tableId = nSQL.getDB(inputArgs.query.databaseID)._tableIds[inputArgs.query.table as string];
const pkPath = nSQL.getDB(inputArgs.query.databaseID)._tables[inputArgs.query.table as string].pkCol;
if (!searchIndexes[tableId] || !searchIndexes[tableId].length) { // no indexes for this table
inputArgs.complete();
} else { // rebuild indexes
if (inputArgs.query.where) { // rebuild specific indexes
const rebuildQ = new _nanoSQLQueue((item, i, done, error) => {
rmRowFromFuzzy(item, pkPath, inputArgs.query.databaseID as string, nSQL, inputArgs.query, tableId, (err) => {
if (err) {
error(err);
} else {
addRowToFuzzy(item, tableId, pkPath, nSQL, inputArgs.query, (err2) => {
if (err2) {
error(err2);
} else {
done();
}
});
}
})
}, inputArgs.error, () => {
inputArgs.complete();
})
nSQL.triggerQuery(inputArgs.query.databaseID, {
...buildQuery(inputArgs.query.databaseID, nSQL, inputArgs.query.table, "select"),
where: inputArgs.query.where
}, (row) => {
if (row) {
rebuildQ.newItem(row);
}
}, () => {
rebuildQ.finished();
}, inputArgs.error);
} else { // rebuild all indexes
// do rebuild
allAsync(searchIndexes[tableId], (item: IFuzzyIndex, i, next, err) => {
// remove all existing index data
const indexTableName = "_" + tableId + "_fuzzy_" + item.path.join(".");
const indexTableNameWords = "_" + tableId + "_fuzzy_words_" + item.path.join(".");
nSQL.triggerQuery(inputArgs.query.databaseID, {
...buildQuery(inputArgs.query.databaseID, nSQL, indexTableName, "delete")
}, noop, () => {
nSQL.triggerQuery(inputArgs.query.databaseID, {
...buildQuery(inputArgs.query.databaseID, nSQL, indexTableNameWords, "delete")
}, noop, () => {
// index data removed
next();
}, err);
}, err);
}).then(() => {
// build new index data for every row
return new Promise((res, rej) => {
// add to index
const queue = new _nanoSQLQueue((newRow, i, done, err) => {
addRowToFuzzy(newRow, tableId, pkPath, nSQL, inputArgs.query, (error) => {
if (error) {
err(error);
} else {
inputArgs.onRow(newRow, i);
}
done();
});
}, rej, res);
// select all rows
nSQL.triggerQuery(inputArgs.query.databaseID, {
...buildQuery(inputArgs.query.databaseID, nSQL, inputArgs.query.table, "select")
}, (row) => {
queue.newItem(row);
}, () => {
queue.finished();
}, rej);
})
}).then(() => {
inputArgs.complete();
}).catch(inputArgs.error);
}
}
}
} else { // pass through everything else
complete(inputArgs);
}
}
}
]
}
}
/*
import { nSQL as nanoSQL } from "@nano-sql/core";
nanoSQL().connect({
plugins: [
FuzzySearch()
]
}).then(() => {
return nanoSQL().query("create table", {
name: "testing",
model: {
"id:int": { pk: true, ai: true },
"name:string": {},
"phrase:string": {}
},
indexes: {
"name": {search: true},
"phrase": { search: true }
}
}).exec();
}).then(() => {
console.log("CONNECTED");
return nanoSQL("testing").query("upsert", { name: "bill", phrase: "hello there billy" }).exec();
}).then(() => {
return nanoSQL("testing").query("upsert", { name: "ted", phrase: "hello there" }).exec();
}).then(() => {
return nanoSQL("testing").query("upsert", { name: "rufus", phrase: "I am running" }).exec();
}).then((result) => {
return nanoSQL("testing").query("select").where(["SEARCH(*, 'hello there billy')", ">=", 0]).exec();
}).then((result) => {
console.log(result);
}).catch((err) => {
console.error(err);
})*/
if (typeof window !== "undefined") {
window["@nano-sql/plugin-fuzzy-search"] = {
FuzzySearch,
FuzzyUserSanitize,
defaultTokenizer,
stopWords
}
} | the_stack |
import * as tf from '@tensorflow/tfjs-core';
import * as dataset_util from './dataset_util';
import * as gl_util from './gl_util';
import {RearrangedData} from './interfaces';
import * as knn_util from './knn_util';
// tslint:disable-next-line:no-any
function instanceOfRearrangedData(object: any): object is RearrangedData {
return 'numPoints' in object && 'pointsPerRow' in object &&
'pixelsPerPoint' in object && 'numRows' in object;
}
// Allows for computing distances between data in a non standard format
export interface CustomDataDefinition {
distanceComputationCode: string;
}
// tslint:disable-next-line:no-any
function instanceOfCustomDataDefinition(object: any):
object is CustomDataDefinition {
return 'distanceComputationCode' in object;
}
export class KNNEstimator {
private verbose: boolean;
private backend: tf.webgl.MathBackendWebGL;
private gpgpu: tf.webgl.GPGPUContext;
private _iteration: number;
private numNeighs: number;
private bruteForceKNNProgram: WebGLProgram;
private randomSamplingKNNProgram: WebGLProgram;
private kNNDescentProgram: WebGLProgram;
private copyDistancesProgram: WebGLProgram;
private copyIndicesProgram: WebGLProgram;
private linesVertexIdBuffer: WebGLBuffer;
private dataTexture: WebGLTexture;
private knnTexture0: WebGLTexture;
private knnTexture1: WebGLTexture;
private knnDataShape: RearrangedData;
get knnShape(): RearrangedData { return this.knnDataShape; }
get iteration() { return this._iteration; }
get pointsPerIteration() { return 20; }
constructor(dataTexture: WebGLTexture,
dataFormat: RearrangedData|CustomDataDefinition,
numPoints: number, numDimensions: number, numNeighs: number,
verbose?: boolean) {
if (verbose != null) {
this.verbose = verbose;
} else {
verbose = false;
}
// Saving the GPGPU context
this.backend = tf.ENV.findBackend('webgl') as tf.webgl.MathBackendWebGL;
this.gpgpu = this.backend.getGPGPUContext();
this._iteration = 0;
this.dataTexture = dataTexture;
if (numNeighs > 128) {
throw new Error('kNN size must not be greater than 128');
}
if (numNeighs % 4 !== 0) {
throw new Error('kNN size must be a multiple of 4');
}
this.numNeighs = numNeighs;
// Input Shape
const knnPointsPerRow =
Math.ceil(Math.sqrt(numNeighs * numPoints) / numNeighs);
this.knnDataShape = {
numPoints,
pixelsPerPoint : numNeighs,
pointsPerRow : knnPointsPerRow,
numRows : Math.ceil(numPoints / knnPointsPerRow)
};
this.log('knn-pntsPerRow', this.knnDataShape.pointsPerRow);
this.log('knn-numRows', this.knnDataShape.numRows);
this.log('knn-pixelsPerPoint', this.knnDataShape.pixelsPerPoint);
// Generating the source for computing the distances between points
let distanceComputationSource: string;
if (instanceOfRearrangedData(dataFormat)) {
const rearrangedData = dataFormat as RearrangedData;
distanceComputationSource =
dataset_util.generateDistanceComputationSource(rearrangedData);
} else if (instanceOfCustomDataDefinition(dataFormat)) {
const customDataDefinition = dataFormat as CustomDataDefinition;
distanceComputationSource = customDataDefinition.distanceComputationCode;
}
// Initialize the WebGL custom programs
this.initializeTextures();
this.initilizeCustomWebGLPrograms(distanceComputationSource);
}
// Utility function for printing stuff
// tslint:disable-next-line:no-any
private log(str: string, obj?: any) {
if (this.verbose) {
if (obj != null) {
console.log(`${str}: \t${obj}`);
} else {
console.log(str);
}
}
}
private initializeTextures() {
const initNeigh = new Float32Array(this.knnDataShape.pointsPerRow *
this.knnDataShape.pixelsPerPoint * 2 *
this.knnDataShape.numRows);
const numNeighs = this.knnDataShape.pixelsPerPoint;
for (let i = 0; i < this.knnDataShape.numPoints; ++i) {
for (let n = 0; n < numNeighs; ++n) {
initNeigh[(i * numNeighs + n) * 2] = -1;
initNeigh[(i * numNeighs + n) * 2 + 1] = 10e30;
}
}
this.log('knn-textureWidth', this.knnDataShape.pointsPerRow *
this.knnDataShape.pixelsPerPoint);
this.log('knn-textureHeight', this.knnDataShape.numRows);
this.knnTexture0 = gl_util.createAndConfigureTexture(
this.gpgpu.gl,
this.knnDataShape.pointsPerRow * this.knnDataShape.pixelsPerPoint,
this.knnDataShape.numRows, 2, initNeigh);
this.knnTexture1 = gl_util.createAndConfigureTexture(
this.gpgpu.gl,
this.knnDataShape.pointsPerRow * this.knnDataShape.pixelsPerPoint,
this.knnDataShape.numRows, 2, initNeigh);
}
private initilizeCustomWebGLPrograms(distanceComputationSource: string) {
this.log('knn Create programs/buffers start');
this.copyDistancesProgram = knn_util.createCopyDistancesProgram(this.gpgpu);
this.log('knn Create indices program');
this.copyIndicesProgram = knn_util.createCopyIndicesProgram(this.gpgpu);
this.log('knn Create brute force knn program, numNeighs', this.numNeighs);
this.bruteForceKNNProgram = knn_util.createBruteForceKNNProgram(
this.gpgpu, this.numNeighs, distanceComputationSource);
this.log('knn Create random sampling force knn program');
this.randomSamplingKNNProgram = knn_util.createRandomSamplingKNNProgram(
this.gpgpu, this.numNeighs, distanceComputationSource);
this.log('knn Create descent program');
this.kNNDescentProgram = knn_util.createKNNDescentProgram(
this.gpgpu, this.numNeighs, distanceComputationSource);
const linesVertexId = new Float32Array(this.knnDataShape.numPoints * 2);
{
for (let i = 0; i < this.knnDataShape.numPoints * 2; ++i) {
linesVertexId[i] = i;
}
}
this.log('knn Create static vertex start');
this.linesVertexIdBuffer = tf.webgl.webgl_util.createStaticVertexBuffer(
this.gpgpu.gl, linesVertexId);
this.log('knn Create programs/buffers done');
}
iterateBruteForce() {
if ((this._iteration % 2) === 0) {
this.iterateGPU(this.dataTexture, this._iteration, this.knnTexture0,
this.knnTexture1);
} else {
this.iterateGPU(this.dataTexture, this._iteration, this.knnTexture1,
this.knnTexture0);
}
++this._iteration;
this.gpgpu.gl.finish();
}
iterateRandomSampling() {
if ((this._iteration % 2) === 0) {
this.iterateRandomSamplingGPU(this.dataTexture, this._iteration,
this.knnTexture0, this.knnTexture1);
} else {
this.iterateRandomSamplingGPU(this.dataTexture, this._iteration,
this.knnTexture1, this.knnTexture0);
}
++this._iteration;
this.gpgpu.gl.finish();
}
iterateKNNDescent() {
if ((this._iteration % 2) === 0) {
this.iterateKNNDescentGPU(this.dataTexture, this._iteration,
this.knnTexture0, this.knnTexture1);
} else {
this.iterateKNNDescentGPU(this.dataTexture, this._iteration,
this.knnTexture1, this.knnTexture0);
}
++this._iteration;
this.gpgpu.gl.finish();
}
knn(): WebGLTexture {
if ((this._iteration % 2) === 0) {
return this.knnTexture0;
} else {
return this.knnTexture1;
}
}
distancesTensor(): tf.Tensor {
return tf.tidy(() => {
const distances = tf.zeros([
this.knnDataShape.numRows,
this.knnDataShape.pointsPerRow * this.knnDataShape.pixelsPerPoint
]);
const knnTexture = this.knn();
knn_util.executeCopyDistancesProgram(
this.gpgpu, this.copyDistancesProgram, knnTexture, this.knnDataShape,
this.backend.getTexture(distances.dataId));
return distances
.reshape([
this.knnDataShape.numRows * this.knnDataShape.pointsPerRow,
this.knnDataShape.pixelsPerPoint
])
.slice([ 0, 0 ], [
this.knnDataShape.numPoints, this.knnDataShape.pixelsPerPoint
]);
});
}
indicesTensor(): tf.Tensor {
return tf.tidy(() => {
const indices = tf.zeros([
this.knnDataShape.numRows,
this.knnDataShape.pointsPerRow * this.knnDataShape.pixelsPerPoint
]);
const knnTexture = this.knn();
knn_util.executeCopyIndicesProgram(
this.gpgpu, this.copyIndicesProgram, knnTexture, this.knnDataShape,
this.backend.getTexture(indices.dataId));
return indices
.reshape([
this.knnDataShape.numRows * this.knnDataShape.pointsPerRow,
this.knnDataShape.pixelsPerPoint
])
.slice([ 0, 0 ], [
this.knnDataShape.numPoints, this.knnDataShape.pixelsPerPoint
]);
});
}
/**
* This forces the CPU and GPU to sync (at least I think so...)
*/
forceSync() {
// neither this.gpgpu.gl.flush() or finish() work;
//@ts-ignore
const mat0 = this.downloadTextureToMatrix(this.knnTexture0);
//console.log(`Flush: ${mat0.length/mat0.length}`);
}
private downloadTextureToMatrix(texture: WebGLTexture): Float32Array {
return this.gpgpu.downloadFloat32MatrixFromOutputTexture(texture,
this.knnDataShape.numRows,
this.knnDataShape.pointsPerRow * this.knnDataShape.pixelsPerPoint);
}
private iterateGPU(dataTexture: WebGLTexture, _iteration: number,
startingKNNTexture: WebGLTexture,
targetTexture?: WebGLTexture) {
knn_util.executeKNNProgram(
this.gpgpu, this.bruteForceKNNProgram, dataTexture, startingKNNTexture,
_iteration, this.knnDataShape, this.linesVertexIdBuffer, targetTexture);
}
private iterateRandomSamplingGPU(dataTexture: WebGLTexture,
_iteration: number,
startingKNNTexture: WebGLTexture,
targetTexture?: WebGLTexture) {
knn_util.executeKNNProgram(this.gpgpu, this.randomSamplingKNNProgram,
dataTexture, startingKNNTexture, _iteration,
this.knnDataShape, this.linesVertexIdBuffer,
targetTexture);
}
private iterateKNNDescentGPU(dataTexture: WebGLTexture, _iteration: number,
startingKNNTexture: WebGLTexture,
targetTexture?: WebGLTexture) {
knn_util.executeKNNProgram(
this.gpgpu, this.kNNDescentProgram, dataTexture, startingKNNTexture,
_iteration, this.knnDataShape, this.linesVertexIdBuffer, targetTexture);
}
} | the_stack |
import { GLOBALS, VhaGlobals } from './main-globals'; // TODO -- eliminate dependence on `GLOBALS` in this file!
import * as path from 'path';
const exec = require('child_process').exec;
const ffprobePath = require('node-ffprobe-installer').path.replace('app.asar', 'app.asar.unpacked');
const fs = require('fs');
const hasher = require('crypto').createHash;
import { Stats } from 'fs';
import { FinalObject, ImageElement, ScreenshotSettings, InputSources, ResolutionString, NewImageElement } from '../interfaces/final-object.interface';
import { startFileSystemWatching, resetWatchers } from './main-extract-async';
interface ResolutionMeta {
label: ResolutionString;
bucket: number;
}
export type ImportStage = 'importingMeta' | 'importingScreenshots' | 'done';
/**
* Return an HTML string for a path to a file
* e.g. `C:\Some folder` becomes `C:/Some%20folder`
* @param anyOsPath
*/
export function getHtmlPath(anyOsPath: string): string {
// Windows was misbehaving
// so we normalize the path (just in case) and replace all `\` with `/` in this instance
// because at this point Electron will be showing images following the path provided
// with the `file:///` protocol -- seems to work
const normalizedPath: string = path.normalize(anyOsPath);
const forwardSlashes: string = normalizedPath.replace(/\\/g, '/');
return forwardSlashes.replace(/ /g, '%20');
}
/**
* Label the video according to closest resolution label
* @param width
* @param height
*/
function labelVideo(width: number, height: number): ResolutionMeta {
let label: ResolutionString = '';
let bucket: number = 0.5;
if (width === 3840 && height === 2160) {
label = '4K';
bucket = 3.5;
} else if (width === 1920 && height === 1080) {
label = '1080';
bucket = 2.5;
} else if (width === 1280 && height === 720) {
label = '720';
bucket = 1.5;
} else if (width > 3840) {
label = '4K+';
bucket = 3.5;
} else if (width > 1920) {
label = '1080+';
bucket = 2.5;
} else if (width > 1280) {
label = '720+';
bucket = 1.5;
}
return { label: label, bucket: bucket };
}
/**
* Alphabetizes an array of `ImageElement`
* prioritizing the folder, and then filename
*/
export function alphabetizeFinalArray(imagesArray: ImageElement[]): ImageElement[] {
return imagesArray.sort((x: ImageElement, y: ImageElement): number => {
const folder1: string = x.partialPath.toLowerCase();
const folder2: string = y.partialPath.toLowerCase();
const file1: string = x.fileName.toLowerCase();
const file2: string = y.fileName.toLowerCase();
if (folder1 > folder2) {
return 1;
} else if (folder1 === folder2 && file1 > file2) {
return 1;
} else if (folder1 === folder2 && file1 === file2) {
return 0;
} else if (folder1 === folder2 && file1 < file2) {
return -1;
} else if (folder1 < folder2) {
return -1;
}
});
}
/**
* Generate the file size formatted as ### MB or #.# GB
* THIS CODE DUPLICATES THE CODE IN `file-size.pipe.ts`
* @param fileSize
*/
function getFileSizeDisplay(sizeInBytes: number): string {
if (sizeInBytes) {
const rounded = Math.round(sizeInBytes / 1000000);
return (rounded > 999
? (rounded / 1000).toFixed(1) + ' GB'
: rounded + ' MB');
} else {
return '';
}
}
/**
* Generate duration formatted as X:XX:XX
* @param numOfSec
*/
function getDurationDisplay(numOfSec: number): string {
if (numOfSec === undefined || numOfSec === 0) {
return '';
} else {
const hh = (Math.floor(numOfSec / 3600)).toString();
const mm = (Math.floor(numOfSec / 60) % 60).toString();
const ss = (Math.floor(numOfSec) % 60).toString();
return (hh !== '0' ? hh + ':' : '')
+ (mm.length !== 2 ? '0' + mm : mm)
+ ':'
+ (ss.length !== 2 ? '0' : '') + ss;
}
}
/**
* Count the number of unique folders in the final array
*/
function countFoldersInFinalArray(imagesArray: ImageElement[]): number {
const finalArrayFolderMap: Map<string, number> = new Map;
imagesArray.forEach((element: ImageElement) => {
if (!finalArrayFolderMap.has(element.partialPath)) {
finalArrayFolderMap.set(element.partialPath, 1);
}
});
return finalArrayFolderMap.size;
}
/**
* Mark element as `deleted` (to remove as duplicate) if the previous element is identical
* expect `alphabetizeFinalArray` to run first - so as to only compare adjacent elements
* Unsure how duplicates can creep in to `ImageElement[]`, but at least they will be removed
*
* !!! WARNING - currently does not merge the `tags` arrays (or other stuff)
* !!! so tags and metadata could be lost :(
*
* @param imagesArray
*/
function markDuplicatesAsDeleted(imagesArray: ImageElement[]): ImageElement[] {
let currentElement: ImageElement = NewImageElement();
imagesArray.forEach((element: ImageElement) => {
if (
element.fileName === currentElement.fileName
&& element.partialPath === currentElement.partialPath
&& element.inputSource === currentElement.inputSource
) {
element.deleted = true;
console.log('DUPE FOUND: ' + element.fileName);
}
currentElement = element;
});
return imagesArray;
}
/**
* Write the final object into `vha` file
* -- this correctly alphabetizes all the videos
* -- it adds the correct number of folders in final array
* @param finalObject -- finalObject
* @param pathToFile -- the path with name of `vha` file to write to disk
* @param done -- function to execute when done writing the file
*/
export function writeVhaFileToDisk(finalObject: FinalObject, pathToTheFile: string, done): void {
finalObject.images = finalObject.images.filter(element => !element.deleted);
finalObject.images = stripOutTemporaryFields(finalObject.images);
// remove any videos that have no reference (unsure how this could happen, but just in case)
const allKeys: string[] = Object.keys(finalObject.inputDirs);
finalObject.images = finalObject.images.filter(element => {
return allKeys.includes(element.inputSource.toString());
});
finalObject.images = alphabetizeFinalArray(finalObject.images); // needed for `default` sort to show proper order
finalObject.images = markDuplicatesAsDeleted(finalObject.images); // expects `alphabetizeFinalArray` to run first
finalObject.images = finalObject.images.filter(element => !element.deleted); // remove any marked in above method
finalObject.numOfFolders = countFoldersInFinalArray(finalObject.images);
const json = JSON.stringify(finalObject);
// backup current file
try {
fs.renameSync(pathToTheFile, pathToTheFile + '.bak');
} catch (err) {
console.log('Error backup up file! Moving on...');
console.log(err);
}
// write the file
fs.writeFile(pathToTheFile, json, 'utf8', done);
// TODO ? CATCH ERRORS ?
}
/**
* Strip out all the temporary fields
* @param imagesArray
*/
function stripOutTemporaryFields(imagesArray: ImageElement[]): ImageElement[] {
imagesArray.forEach((element) => {
delete(element.durationDisplay);
delete(element.fileSizeDisplay);
delete(element.index);
delete(element.resBucket);
delete(element.resolution);
delete(element.selected);
});
return imagesArray;
}
/**
* Format .pls file and write to hard drive
* @param savePath -- location to save the temp.pls file
* @param playlist -- array of ImageElements
* @param done -- callback
*/
export function createDotPlsFile(savePath: string, playlist: ImageElement[], sourceFolderMap: InputSources, done): void {
const writeArray: string[] = [];
writeArray.push('[playlist]');
writeArray.push('NumberOfEntries=' + playlist.length);
for (let i = 0; i < playlist.length; i++) {
const fullPath: string = path.join(
sourceFolderMap[playlist[i].inputSource].path,
playlist[i].partialPath,
playlist[i].fileName
);
writeArray.push('File' + (i + 1) + '=' + fullPath );
writeArray.push('Title' + (i + 1) + '=' + playlist[i].cleanName);
}
writeArray.push(''); // empty line at the end requested by VLC Wiki
const singleString: string = writeArray.join('\n');
fs.writeFile(savePath, singleString, 'utf8', done);
}
/**
* Clean up the displayed file name
* (1) remove extension
* (2) replace underscores with spaces "_" => " "
* (3) replace periods with spaces "." => " "
* (4) replace multi-spaces with a single space " " => " "
* @param original {string}
* @return {string}
*/
export function cleanUpFileName(original: string): string {
return original.split('.').slice(0, -1).join('.') // (1)
.split('_').join(' ') // (2)
.split('.').join(' ') // (3)
.split(/\s+/).join(' '); // (4)
}
/**
* Iterates ffprobe output to find stream with the best resolution (just width, for now)
*
* @param metadata the ffProbe metadata object
*/
function getBestStream(metadata) {
try {
return metadata.streams.reduce((a, b) => a.width > b.width ? a : b);
} catch (e) {
// if metadata.streams is an empty array or something else is wrong with it
// return an empty object so later calls to `stream.width` or `stream.height` do not throw exceptions
return {};
}
}
/**
* Return the duration from file by parsing metadata
* @param metadata
*/
function getFileDuration(metadata): number {
if (metadata?.streams?.[0]?.duration) {
return metadata.streams[0].duration;
} else if (metadata?.format?.duration) {
return metadata.format.duration;
} else {
return 0;
}
}
/**
* Return the average frame rate of files
* ===========================================================================================
* TO SWITCH TO AVERAGE FRAME RATE,
* replace both instances of r_frame_rate with avg_frame_rate
* only in this method
* ===========================================================================================
* @param metadata
*/
function getFps(metadata): number {
if (metadata?.streams?.[0]?.r_frame_rate) {
const fps = metadata.streams[0].r_frame_rate;
const fpsParts = fps.split('/');
const evalFps = Number(fpsParts[0]) / Number(fpsParts[1]); // FPS is a fraction like `24000/1001`
return Math.round(evalFps);
} else {
return 0;
}
}
// ===========================================================================================
// Other supporting methods
// ===========================================================================================
/**
* Compute the number of screenshots to extract for a particular video
* @param screenshotSettings
* @param duration - number of seconds in a video
*/
function computeNumberOfScreenshots(screenshotSettings: ScreenshotSettings, duration: number): number {
let total: number;
// fixed or per minute
if (screenshotSettings.fixed) {
total = screenshotSettings.n;
} else {
total = Math.ceil(duration / 60 / screenshotSettings.n);
}
// never fewer than 3 screenshots
if (total < 3) {
total = 3;
}
// never more than would fit in a JPG
const screenWidth: number = screenshotSettings.height * (16 / 9);
if (total * screenWidth > 65535) {
total = Math.floor(65535 / screenWidth);
}
// never more screenshots than seconds in a clip
if (duration < total) {
total = Math.max(2, Math.floor(duration));
}
return total;
}
/**
* Hash a given file using its size
* @param pathToFile -- path to file
* @param stats -- Stats from `fs.stat(pathToFile)`
*/
function hashFileAsync(pathToFile: string, stats: Stats): Promise<string> {
return new Promise((resolve, reject) => {
const sampleSize = 16 * 1024;
const sampleThreshold = 128 * 1024;
const fileSize = stats.size;
let data: Buffer;
if (fileSize < sampleThreshold) {
fs.readFile(pathToFile, (err, data2) => {
if (err) { throw err; }
// append the file size to the data
const buf = Buffer.concat([data2, Buffer.from(fileSize.toString())]);
// make the magic happen!
const hash = hasher('md5').update(buf.toString('hex')).digest('hex');
resolve(hash);
}); // too small, just read the whole file
} else {
data = Buffer.alloc(sampleSize * 3);
fs.open(pathToFile, 'r', (err, fd) => {
fs.read(fd, data, 0, sampleSize, 0, (err2, bytesRead, buffer) => { // read beginning of file
fs.read(fd, data, sampleSize, sampleSize, fileSize / 2, (err3, bytesRead2, buffer2) => {
fs.read(fd, data, sampleSize * 2, sampleSize, fileSize - sampleSize, (err4, bytesRead3, buffer3) => {
fs.close(fd, (err5) => {
// append the file size to the data
const buf = Buffer.concat([data, Buffer.from(fileSize.toString())]);
// make the magic happen!
const hash = hasher('md5').update(buf.toString('hex')).digest('hex');
resolve(hash);
});
});
});
});
});
}
});
}
/**
* Extracts information about a single file using `ffprobe`
* Stores information into the ImageElement and returns it via callback
* @param filePath path to the file
* @param screenshotSettings ScreenshotSettings
* @param callback
*/
export function extractMetadataAsync(
filePath: string,
screenshotSettings: ScreenshotSettings,
): Promise<ImageElement> {
return new Promise((resolve, reject) => {
const ffprobeCommand = '"' + ffprobePath + '" -of json -show_streams -show_format -select_streams V "' + path.normalize(filePath) + '"';
exec(ffprobeCommand, (err, data, stderr) => {
if (err) {
reject();
} else {
const metadata = JSON.parse(data);
const stream = getBestStream(metadata);
const fileDuration = getFileDuration(metadata);
const realFps = getFps(metadata);
const duration = Math.round(fileDuration) || 0;
const origWidth = stream.width || 0; // ffprobe does not detect it on some MKV streams
const origHeight = stream.height || 0;
fs.stat(filePath, (err2, fileStat) => {
if (err2) {
reject();
}
const imageElement = NewImageElement();
imageElement.birthtime = Math.round(fileStat.birthtimeMs);
imageElement.duration = duration;
imageElement.fileSize = fileStat.size;
imageElement.height = origHeight;
imageElement.mtime = Math.round(fileStat.mtimeMs);
imageElement.screens = computeNumberOfScreenshots(screenshotSettings, duration);
imageElement.width = origWidth;
imageElement.fps = realFps;
hashFileAsync(filePath, fileStat).then((hash) => {
imageElement.hash = hash;
resolve(imageElement);
});
});
}
});
});
}
/**
* Sends progress to Angular App
* @param current number
* @param total number
* @param stage ImportStage
*/
export function sendCurrentProgress(current: number, total: number, stage: ImportStage): void {
GLOBALS.angularApp.sender.send('import-progress-update', current, total, stage);
if (stage !== 'done') {
GLOBALS.winRef.setProgressBar(current / total);
} else {
GLOBALS.winRef.setProgressBar(-1);
}
}
/**
* Parse additional extension string
* @param additionalExtension string
*/
export function parseAdditionalExtensions(additionalExtension: string): string[] {
return additionalExtension.split(',').map((token => {
return token.trim();
}));
}
/**
* Send final object to Angular; uses `GLOBALS` as input!
* @param finalObject
* @param globals
*/
export function sendFinalObjectToAngular(finalObject: FinalObject, globals: VhaGlobals): void {
// finalObject.images = alphabetizeFinalArray(finalObject.images); // TODO -- check -- unsure if needed
finalObject.images = insertTemporaryFields(finalObject.images);
globals.angularApp.sender.send(
'final-object-returning',
finalObject,
globals.currentlyOpenVhaFile,
getHtmlPath(globals.selectedOutputFolder)
);
}
/**
* Writes / overwrites:
* unique index for default sort
* video resolution string
* resolution category for resolution filtering
*/
export function insertTemporaryFields(imagesArray: ImageElement[]): ImageElement[] {
imagesArray.forEach((element, index) => {
element = insertTemporaryFieldsSingle(element);
element.index = index; // TODO -- rethink index -- maybe fix here ?
});
return imagesArray;
}
/**
* Insert temporary fields but just for one file
*/
export function insertTemporaryFieldsSingle(element: ImageElement): ImageElement {
// set resolution string & bucket
const resolution: ResolutionMeta = labelVideo(element.width, element.height);
element.durationDisplay = getDurationDisplay(element.duration);
element.fileSizeDisplay = getFileSizeDisplay(element.fileSize);
element.resBucket = resolution.bucket;
element.resolution = resolution.label;
return element;
}
/**
* If .vha2 version 2, create `inputDirs` from `inputDir` and add `inputSource` into every element
* Keep `inputDir` for backwards compatibility - in case user wants to come back to VHA2
* @param finalObject
*/
export function upgradeToVersion3(finalObject: FinalObject): void {
if (finalObject.version === 2) {
console.log('OLD version file -- converting!');
finalObject.inputDirs = {
0: {
path: (finalObject as any).inputDir,
watch: false
}
};
finalObject.version = 3;
finalObject.images.forEach((element: ImageElement) => {
element.inputSource = 0;
element.screens = computeNumberOfScreenshots(finalObject.screenshotSettings, element.duration);
// update number of screens to account for too-many or too-few cases
// as they were not handlede prior to version 3 release
});
}
}
/**
* Only called when creating a new hub OR opening a hub
* Notify Angular that a folder is 'connected'
* If user wants continuous watching, watching directories with `chokidar`
* @param inputDirs
* @param currentImages -- if creating a new VHA file, this will be [] empty (and `watch` = false)
*/
export function setUpDirectoryWatchers(inputDirs: InputSources, currentImages: ImageElement[]): void {
console.log('---------------------------------');
console.log(' SETTING UP FILE SYSTEM WATCHERS' );
console.log('---------------------------------');
resetWatchers(currentImages);
Object.keys(inputDirs).forEach((key: string) => {
const pathToDir: string = inputDirs[key].path;
const shouldWatch: boolean = inputDirs[key].watch;
console.log(key, 'watch =', shouldWatch, ':', pathToDir);
// check if directory connected
fs.access(pathToDir, fs.constants.W_OK, (err: any) => {
if (!err) {
GLOBALS.angularApp.sender.send('directory-now-connected', parseInt(key, 10), pathToDir);
if (shouldWatch || currentImages.length === 0) {
// Temp logging
if (currentImages.length === 0) {
console.log('FIRST SCAN');
} else {
console.log('PERSISTENT WATCHING !!!');
}
startFileSystemWatching(pathToDir, parseInt(key, 10), shouldWatch);
}
}
});
});
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [apprunner](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsapprunner.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Apprunner extends PolicyStatement {
public servicePrefix = 'apprunner';
/**
* Statement provider for service [apprunner](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsapprunner.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 associate your own domain name with the AWS App Runner subdomain URL of your App Runner service
*
* Access Level: Write
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_AssociateCustomDomain.html
*/
public toAssociateCustomDomain() {
return this.to('AssociateCustomDomain');
}
/**
* Grants permission to create an AWS App Runner automatic scaling configuration resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_CreateAutoScalingConfiguration.html
*/
public toCreateAutoScalingConfiguration() {
return this.to('CreateAutoScalingConfiguration');
}
/**
* Grants permission to create an AWS App Runner connection resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_CreateConnection.html
*/
public toCreateConnection() {
return this.to('CreateConnection');
}
/**
* Grants permission to create an AWS App Runner service
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifConnectionArn()
* - .ifAutoScalingConfigurationArn()
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_CreateService.html
*/
public toCreateService() {
return this.to('CreateService');
}
/**
* Grants permission to delete an AWS App Runner automatic scaling configuration resource
*
* Access Level: Write
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_DeleteAutoScalingConfiguration.html
*/
public toDeleteAutoScalingConfiguration() {
return this.to('DeleteAutoScalingConfiguration');
}
/**
* Grants permission to delete an AWS App Runner connection
*
* Access Level: Write
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_DeleteConnection.html
*/
public toDeleteConnection() {
return this.to('DeleteConnection');
}
/**
* Grants permission to delete an AWS App Runner service
*
* Access Level: Write
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_DeleteService.html
*/
public toDeleteService() {
return this.to('DeleteService');
}
/**
* Grants permission to retrieve descriptions of an AWS App Runner automatic scaling configuration resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_DescribeAutoScalingConfiguration.html
*/
public toDescribeAutoScalingConfiguration() {
return this.to('DescribeAutoScalingConfiguration');
}
/**
* Grants permission to retrieve descriptions of custom domain names associated with an AWS App Runner service
*
* Access Level: Read
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_DescribeCustomDomains.html
*/
public toDescribeCustomDomains() {
return this.to('DescribeCustomDomains');
}
/**
* Grants permission to retrieve description of an operation that occurred on an AWS App Runner service
*
* Access Level: Read
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_DescribeOperation.html
*/
public toDescribeOperation() {
return this.to('DescribeOperation');
}
/**
* Grants permission to retrieve description of an AWS App Runner service
*
* Access Level: Read
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_DescribeService.html
*/
public toDescribeService() {
return this.to('DescribeService');
}
/**
* Grants permission to disassociate a custom domain name from an AWS App Runner service
*
* Access Level: Write
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_DisassociateCustomDomain.html
*/
public toDisassociateCustomDomain() {
return this.to('DisassociateCustomDomain');
}
/**
* Grants permission to retrieve a list of AWS App Runner automatic scaling configurations in your AWS account
*
* Access Level: List
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_ListAutoScalingConfigurations.html
*/
public toListAutoScalingConfigurations() {
return this.to('ListAutoScalingConfigurations');
}
/**
* Grants permission to retrieve a list of AWS App Runner connections associated with your AWS account
*
* Access Level: List
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_ListConnections.html
*/
public toListConnections() {
return this.to('ListConnections');
}
/**
* Grants permission to retrieve a list of operations that occurred on an AWS App Runner service
*
* Access Level: List
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_ListOperations.html
*/
public toListOperations() {
return this.to('ListOperations');
}
/**
* Grants permission to retrieve a list of running AWS App Runner services in your AWS account
*
* Access Level: List
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_ListServices.html
*/
public toListServices() {
return this.to('ListServices');
}
/**
* Grants permission to list tags associated with an AWS App Runner resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to pause an active AWS App Runner service
*
* Access Level: Write
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_PauseService.html
*/
public toPauseService() {
return this.to('PauseService');
}
/**
* Grants permission to resume an active AWS App Runner service
*
* Access Level: Write
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_ResumeService.html
*/
public toResumeService() {
return this.to('ResumeService');
}
/**
* Grants permission to initiate a manual deployemnt to an AWS App Runner service
*
* Access Level: Write
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_StartDeployment.html
*/
public toStartDeployment() {
return this.to('StartDeployment');
}
/**
* Grants permission to add tags to, or update tag values of, an App Runner resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to remove tags from an App Runner resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update an AWS App Runner service
*
* Access Level: Write
*
* Possible conditions:
* - .ifConnectionArn()
* - .ifAutoScalingConfigurationArn()
*
* https://docs.aws.amazon.com/apprunner/latest/api/API_UpdateService.html
*/
public toUpdateService() {
return this.to('UpdateService');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AssociateCustomDomain",
"CreateAutoScalingConfiguration",
"CreateConnection",
"CreateService",
"DeleteAutoScalingConfiguration",
"DeleteConnection",
"DeleteService",
"DisassociateCustomDomain",
"PauseService",
"ResumeService",
"StartDeployment",
"UpdateService"
],
"Read": [
"DescribeAutoScalingConfiguration",
"DescribeCustomDomains",
"DescribeOperation",
"DescribeService",
"ListTagsForResource"
],
"List": [
"ListAutoScalingConfigurations",
"ListConnections",
"ListOperations",
"ListServices"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type service to the statement
*
* @param serviceName - Identifier for the serviceName.
* @param serviceId - Identifier for the serviceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onService(serviceName: string, serviceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apprunner:${Region}:${Account}:service/${ServiceName}/${ServiceId}';
arn = arn.replace('${ServiceName}', serviceName);
arn = arn.replace('${ServiceId}', serviceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type connection to the statement
*
* @param connectionName - Identifier for the connectionName.
* @param connectionId - Identifier for the connectionId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onConnection(connectionName: string, connectionId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apprunner:${Region}:${Account}:connection/${ConnectionName}/${ConnectionId}';
arn = arn.replace('${ConnectionName}', connectionName);
arn = arn.replace('${ConnectionId}', connectionId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type autoscalingconfiguration to the statement
*
* @param autoscalingConfigurationName - Identifier for the autoscalingConfigurationName.
* @param autoscalingConfigurationVersion - Identifier for the autoscalingConfigurationVersion.
* @param autoscalingConfigurationId - Identifier for the autoscalingConfigurationId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onAutoscalingconfiguration(autoscalingConfigurationName: string, autoscalingConfigurationVersion: string, autoscalingConfigurationId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:apprunner:${Region}:${Account}:autoscalingconfiguration/${AutoscalingConfigurationName}/${AutoscalingConfigurationVersion}/${AutoscalingConfigurationId}';
arn = arn.replace('${AutoscalingConfigurationName}', autoscalingConfigurationName);
arn = arn.replace('${AutoscalingConfigurationVersion}', autoscalingConfigurationVersion);
arn = arn.replace('${AutoscalingConfigurationId}', autoscalingConfigurationId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Filters access to the CreateService and UpdateService actions based on the ARN of an associated AutoScalingConfiguration resource
*
* Applies to actions:
* - .toCreateService()
* - .toUpdateService()
*
* @param value The value(s) to check
* @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike`
*/
public ifAutoScalingConfigurationArn(value: string | string[], operator?: Operator | string) {
return this.if(`AutoScalingConfigurationArn`, value, operator || 'ArnLike');
}
/**
* Filters access to the CreateService and UpdateService actions based on the ARN of an associated Connection resource
*
* Applies to actions:
* - .toCreateService()
* - .toUpdateService()
*
* @param value The value(s) to check
* @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike`
*/
public ifConnectionArn(value: string | string[], operator?: Operator | string) {
return this.if(`ConnectionArn`, value, operator || 'ArnLike');
}
} | the_stack |
import { Component, OnInit, OnDestroy, TemplateRef } from '@angular/core';
import { HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { JhiEventManager, JhiParseLinks, JhiAlertService } from 'ng-jhipster';
import { ActivatedRoute, Router } from '@angular/router';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { IMessage } from 'app/shared/model/messsage.model';
import { AccountService } from 'app/core';
import { ITEMS_PER_PAGE } from 'app/shared';
import { BrokerService } from 'app/entities/broker/broker.service';
import { saveAs } from 'file-saver/FileSaver';
import { IBroker } from 'app/shared/model/broker.model';
import 'brace';
import 'brace/mode/text';
import 'brace/mode/json';
import 'brace/theme/eclipse';
import { IHeaderKeys } from 'app/shared/model/header-keys.model';
@Component({
selector: 'jhi-broker-message-browser',
templateUrl: './broker-message-browser.component.html'
})
export class BrokerMessageBrowserComponent implements OnInit, OnDestroy {
messages: IMessage[];
message: IMessage;
selectedMessage: IMessage = {};
selectedHighlight: string;
allMessages: any;
headers: any;
headerKeys: IHeaderKeys[];
brokers: IBroker[];
brokerType: string;
endpointName: string;
endpointType: string;
targetEndpointName: string;
public isAdmin: boolean;
currentAccount: any;
eventSubscriber: Subscription;
itemsPerPage: number;
links: any;
predicate: any;
reverse: any;
totalItems: number = -1;
page: any;
numberOfMessages: number = 100;
messagesCount: number;
fileExtension: string;
isLoading: boolean = false;
finished = false;
test: any;
searchText: string = '';
active: string = '0';
descending: boolean = false;
ascending: boolean = true;
subtitle: string;
objectKeys = Object.keys;
modalRef: NgbModalRef | null;
constructor(
private brokerService: BrokerService,
protected jhiAlertService: JhiAlertService,
protected eventManager: JhiEventManager,
protected parseLinks: JhiParseLinks,
private modalService: NgbModal,
protected accountService: AccountService,
private router: Router,
private route: ActivatedRoute
) {
this.messages = [];
this.itemsPerPage = ITEMS_PER_PAGE + 5;
this.page = 1;
this.links = {
last: 0
};
this.predicate = 'name';
this.reverse = true;
}
ngOnInit() {
this.accountService.identity().then(account => {
this.currentAccount = account;
});
this.route.params.subscribe(params => {
this.endpointType = params['endpointType'];
this.endpointName = params['endpointName'];
this.brokerType = params['brokerType'];
});
this.loadMessages();
this.finished = true;
this.accountService.hasAuthority('ROLE_ADMIN').then(r => (this.isAdmin = r));
this.registerChangeInFlows();
}
ngAfterViewInit() {
this.finished = true;
}
ngOnDestroy() {
this.eventManager.destroy(this.eventSubscriber);
}
loadMessages() {
this.isLoading = true;
if (this.brokerType) {
this.getMessages();
} else {
this.brokerService.getBrokers().subscribe(
data => {
if (data) {
for (let i = 0; i < data.body.length; i++) {
this.brokers.push(data.body[i]);
}
this.brokerType = this.brokers[0].type;
if (this.brokerType != null) {
this.getMessages();
} else {
console.log('Unknown broker: set brokertype to artemis');
this.brokerType = 'artemis';
this.getMessages();
}
}
},
error => console.log(error)
);
}
}
getMessages() {
this.brokerService.countMessages(this.brokerType, this.endpointName).subscribe(
(res: HttpResponse<string>) => this.onSuccessCount(res.body, res.headers),
(res: HttpErrorResponse) => this.onError(res.message)
);
this.brokerService.browseMessages(this.brokerType, this.endpointName, this.page, this.numberOfMessages, true).subscribe(
(res: HttpResponse<IMessage[]>) => this.onSuccess(res.body, res.headers),
(res: HttpErrorResponse) => this.onError(res.message)
);
}
private onSuccess(data, headers) {
this.isLoading = false;
this.messages = new Array<IMessage>();
this.allMessages = data;
if (data.messages.message) {
let itemNumber = 0;
if (this.page > 1) {
itemNumber = (this.page - 1) * this.numberOfMessages;
}
for (var i = data.messages.message.length - 1; i > -1; i--) {
this.message = {};
itemNumber = itemNumber + 1;
this.message.number = itemNumber;
this.message.messageid = data.messages.message[i].messageid;
if (this.brokerType === 'artemis') {
this.message.timestamp = this.timeConverter(data.messages.message[i].timestamp);
} else {
this.message.timestamp = data.messages.message[i].timestamp;
}
this.messages.push(this.message);
if (i === data.messages.message.length - 1) {
this.showMessage(this.message);
}
}
this.totalItems = this.numberOfMessages;
}
}
private onSuccessCount(data, headers) {
this.messagesCount = parseInt(data);
if (this.messagesCount === 0) {
this.subtitle = '0 messages on ' + this.endpointType + ' ' + this.endpointName;
} else if (this.messagesCount === 1) {
this.subtitle = '1 message on ' + this.endpointType + ' ' + this.endpointName;
} else {
this.subtitle = this.messagesCount.toString() + ' messages on ' + this.endpointType + ' ' + this.endpointName;
}
}
private onSuccessBrowse(data, headers) {
if (data.messages.message) {
for (var i = 0; i < data.messages.message.length; i++) {
const message = data.messages.message[i];
this.selectedMessage = {};
this.selectedMessage.messageid = message.messageid;
this.selectedMessage.timestamp = message.timestamp;
this.selectedMessage.headers = message.headers;
this.selectedMessage.headerKeys = [];
this.selectedMessage.jmsHeaders = message.jmsHeaders;
this.selectedMessage.body = this.getBody(message);
this.selectedMessage.fileType = this.getFileType(this.selectedMessage.body);
}
}
}
getBody(message: any) {
let body: string = '';
if (message.body) {
body = message.body;
} else if (message.BodyPreview) {
// Convert to byte array
let data = new Uint8Array(message.BodyPreview);
// Decode with TextDecoder
body = new TextDecoder('shift-jis').decode(data.buffer);
}
return body;
}
/*
getJMSHeaders(message: any){
const jmsHeaders = Object.keys(message).filter(key => key.startsWith('JMS'))
.reduce((obj, key) => {
obj[key] = message[key];
return obj;
}, {});
return jmsHeaders;
}*/
private onError(errorMessage: string) {
this.isLoading = false;
this.jhiAlertService.error(errorMessage, null, null);
}
reset() {
this.page = 0;
this.messages = [];
this.loadMessages();
}
trackTimestamp(index: number, item: IMessage) {
return item.timestamp;
}
registerChangeInFlows() {
this.eventSubscriber = this.eventManager.subscribe('messageListModification', response => this.reset());
}
sortByTimestamp() {
if (this.descending) {
this.messages.sort((a, b) => b.timestamp.localeCompare(a.timestamp));
this.descending = false;
} else {
this.messages.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
this.descending = true;
}
this.messages = [...this.messages];
}
trigerAction(selectedAction: string) {
this.eventManager.broadcast({ name: 'trigerAction', content: selectedAction });
}
refreshMessages() {
this.loadMessages();
}
deleteMessage(message: IMessage) {
this.brokerService.deleteMessage(this.brokerType, this.endpointName, message.messageid).subscribe(
(res: HttpResponse<any>) => {
this.loadMessages();
},
(res: HttpErrorResponse) => this.onError(res.message)
);
}
moveMessage(message: IMessage) {
this.brokerService.moveMessage(this.brokerType, this.endpointName, this.targetEndpointName, message.messageid).subscribe(
(res: HttpResponse<any>) => {
this.loadMessages();
this.cancelModal();
},
(res: HttpErrorResponse) => this.onError(res.message)
);
}
saveMessage(message: IMessage, bodyOnly: boolean) {
if (message.fileType) {
this.fileExtension = message.fileType;
} else {
this.fileExtension = 'txt';
}
const today = new Date().toISOString().slice(0, 10);
if (bodyOnly) {
const blob = new Blob([message.body], { type: 'application/' + this.fileExtension });
saveAs(blob, `${today}-${this.endpointName}-${message.messageid}.${this.fileExtension}`);
} else {
this.brokerService.browseMessage(this.brokerType, this.endpointName, message.messageid).subscribe(
(res: HttpResponse<any>) => {
const exportMessage = JSON.stringify(res.body);
const blob = new Blob([exportMessage], { type: 'application/json' });
saveAs(blob, `${today}-${this.endpointName}-${message.messageid}.json`);
},
(res: HttpErrorResponse) => this.onError(res.message)
);
}
}
saveAllMessages() {
this.brokerService.browseMessages(this.brokerType, this.endpointName, this.page, this.numberOfMessages, false).subscribe(
(res: HttpResponse<IMessage[]>) => {
this.allMessages = res.body;
const exportMessage = JSON.stringify(this.allMessages);
const blob = new Blob([exportMessage], { type: 'application/json' });
const today = new Date().toISOString().slice(0, 10);
saveAs(blob, `${today}-${this.endpointName}.json`);
},
(res: HttpErrorResponse) => this.onError(res.message)
);
}
showMessage(message: IMessage) {
this.selectedHighlight = message.messageid;
this.brokerService.browseMessage(this.brokerType, this.endpointName, message.messageid).subscribe(
(res: HttpResponse<IMessage[]>) => this.onSuccessBrowse(res.body, res.headers),
(res: HttpErrorResponse) => this.onError(res.message)
);
}
previousPage() {
this.page = this.page - 1;
this.messages = new Array<IMessage>();
this.loadMessages();
}
nextPage() {
this.page = this.page + 1;
this.messages = new Array<IMessage>();
this.loadMessages();
}
openModal(templateRef: TemplateRef<any>) {
this.modalRef = this.modalService.open(templateRef);
}
cancelModal(): void {
if (this.modalRef) {
this.modalRef.dismiss();
this.modalRef = null;
}
}
getFileType(doc) {
try {
//try to parse via json
let a = JSON.parse(doc);
return 'json';
} catch (e) {
try {
//try xml parsing
let parser = new DOMParser();
var xmlDoc = parser.parseFromString(doc, 'application/xml');
if (xmlDoc.documentElement.nodeName == '' || xmlDoc.documentElement.nodeName == 'parsererror') return 'txt';
else return 'xml';
} catch (e) {
return 'txt';
}
}
}
timeConverter(UNIX_timestamp) {
var a = new Date(UNIX_timestamp);
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec;
return time;
}
} | the_stack |
import { FormSchema } from '/@/components/Table';
import { BasicColumn } from '/@/components/Table';
import { message } from 'ant-design-vue';
import { useI18n } from '/@/hooks/web/useI18n';
const { t } = useI18n();
import {
ClientServiceProxy,
EnabledInput,
IdInput,
PagingClientListInput,
AddRedirectUriInput,
RemoveRedirectUriInput,
AddCorsInput,
RemoveCorsInput,
ApiScopeServiceProxy,
UpdateScopeInput,
} from '/@/services/ServiceProxies';
export const searchFormSchema: FormSchema[] = [
{
field: 'filter',
label: t('common.key'),
component: 'Input',
colProps: { span: 8 },
},
];
export const tableColumns: BasicColumn[] = [
{
title: 'ClientId',
dataIndex: 'clientId',
},
{
title: 'ClientName',
dataIndex: 'clientName',
},
{
title: t('common.enabled'),
dataIndex: 'enabled',
slots: { customRender: 'enabled' },
},
{
title: 'AccessTokenLifetime',
dataIndex: 'accessTokenLifetime',
},
{
title: 'AbsoluteRefreshTokenLifetime',
dataIndex: 'absoluteRefreshTokenLifetime',
},
{
title: 'Description',
dataIndex: 'description',
},
];
export const createFormSchema: FormSchema[] = [
{
field: 'clientId',
label: 'ClientId',
component: 'Input',
required: true,
colProps: { span: 20 },
},
{
field: 'clientName',
label: 'ClientName',
component: 'Input',
required: true,
colProps: { span: 20 },
},
{
field: 'allowedGrantTypes',
label: 'GrantType',
component: 'Select',
required: true,
colProps: { span: 20 },
componentProps: {
options: [
{
label: 'ClientCredentials',
value: 'client_credentials',
},
{
label: 'Implicit',
value: 'implicit',
},
{
label: 'AuthorizationCode',
value: 'authorization_code',
},
{
label: 'Hybrid',
value: 'hybrid',
},
{
label: 'ResourceOwnerPassword',
value: 'password',
},
],
},
},
{
field: 'description',
label: 'Description',
component: 'Input',
colProps: { span: 20 },
},
];
export const editBasicDetailSchema: FormSchema[] = [
{
field: 'clientId',
label: 'ClientId',
component: 'Input',
required: true,
labelWidth: 200,
componentProps: {
disabled: true,
},
colProps: { span: 20 },
},
{
field: 'clientName',
label: 'ClientName',
component: 'Input',
labelWidth: 200,
required: true,
colProps: { span: 20 },
},
{
field: 'description',
label: 'Description',
component: 'Input',
labelWidth: 200,
colProps: { span: 20 },
},
{
field: 'allowedGrantTypes',
label: 'GrantType',
component: 'Select',
required: true,
labelWidth: 200,
colProps: { span: 20 },
componentProps: {
options: [
{
label: 'ClientCredentials',
value: 'client_credentials',
},
{
label: 'Implicit',
value: 'implicit',
},
{
label: 'AuthorizationCode',
value: 'authorization_code',
},
{
label: 'Hybrid',
value: 'hybrid',
},
{
label: 'ResourceOwnerPassword',
value: 'password',
},
],
},
},
{
field: 'clientUri',
label: 'ClientUri',
component: 'Input',
labelWidth: 200,
colProps: { span: 20 },
},
{
field: 'logoUri',
label: 'LogoUri',
component: 'Input',
labelWidth: 200,
colProps: { span: 20 },
},
{
field: 'frontChannelLogoutUri',
label: 'FrontChannelLogoutUri',
component: 'Input',
labelWidth: 200,
colProps: { span: 20 },
},
{
field: 'backChannelLogoutUri',
label: 'BackChannelLogoutUri',
component: 'Input',
labelWidth: 200,
colProps: { span: 20 },
},
];
export const editBasicOptionSchema: FormSchema[] = [
{
field: 'enabled',
label: 'Enabled',
labelWidth: 250,
component: 'Switch',
colProps: { span: 10 },
},
{
field: 'requireClientSecret',
label: 'RequireClientSecret',
component: 'Switch',
labelWidth: 250,
colProps: { span: 10 },
},
{
field: 'requireConsent',
label: 'RequireConsent',
component: 'Switch',
labelWidth: 250,
colProps: { span: 10 },
},
{
field: 'allowRememberConsent',
label: 'AllowRememberConsent',
component: 'Switch',
labelWidth: 250,
colProps: { span: 10 },
},
{
field: 'requirePkce',
label: 'RequirePkce',
labelWidth: 250,
component: 'Switch',
colProps: { span: 10 },
},
{
field: 'allowOfflineAccess',
label: 'AllowOfflineAccess',
component: 'Switch',
labelWidth: 250,
colProps: { span: 10 },
},
{
field: 'enableLocalLogin',
label: 'EnableLocalLogin',
component: 'Switch',
labelWidth: 250,
colProps: { span: 10 },
},
{
field: 'includeJwtId',
label: 'IncludeJwtId',
component: 'Switch',
labelWidth: 250,
colProps: { span: 10 },
},
{
field: 'allowAccessTokensViaBrowser',
label: 'AllowAccessTokensViaBrowser',
component: 'Switch',
labelWidth: 250,
colProps: { span: 10 },
},
{
field: 'alwaysIncludeUserClaimsInIdToken',
label: 'AlwaysIncludeUserClaimsInIdToken',
component: 'Switch',
labelWidth: 250,
colProps: { span: 10 },
},
{
field: 'frontChannelLogoutSessionRequired',
label: 'FrontChannelLogoutSessionRequired',
component: 'Switch',
labelWidth: 250,
colProps: { span: 10 },
},
{
field: 'backChannelLogoutSessionRequired',
label: 'BackChannelLogoutSessionRequired',
component: 'Switch',
labelWidth: 250,
colProps: { span: 10 },
},
];
export const editBasicTokenSchema: FormSchema[] = [
{
field: 'accessTokenLifetime',
label: 'AccessTokenLifetime',
labelWidth: 200,
component: 'Input',
},
{
field: 'identityTokenLifetime',
label: 'IdentityTokenLifetime',
labelWidth: 200,
component: 'Input',
},
{
field: 'authorizationCodeLifetime',
label: 'AuthorizationCodeLifetime',
labelWidth: 200,
component: 'Input',
},
{
field: 'absoluteRefreshTokenLifetime',
label: 'AbsoluteRefreshTokenLifetime',
labelWidth: 200,
component: 'Input',
},
{
field: 'slidingRefreshTokenLifetime',
label: 'SlidingRefreshTokenLifetime',
labelWidth: 200,
component: 'Input',
},
{
field: 'refreshTokenExpiration',
label: 'RefreshTokenExpiration',
labelWidth: 200,
component: 'Input',
},
{
field: 'deviceCodeLifetime',
label: 'DeviceCodeLifetime',
labelWidth: 200,
component: 'Input',
},
];
export const editBasicSecretSchema: FormSchema[] = [
{
field: 'secretType',
component: 'Select',
label: 'Secret',
labelWidth: 100,
colProps: {
span: 15,
},
componentProps: {
options: [
{
label: 'SharedSecret',
value: 'SharedSecret',
key: '1',
},
{
label: 'X509Thumbprint',
value: 'X509Thumbprint',
key: '2',
},
],
},
},
{
field: 'secret',
label: 'secret',
labelWidth: 100,
component: 'InputPassword',
},
];
/**
* 分页列表
* @param params
* @returns
*/
export async function getTableListAsync(params: PagingClientListInput) {
const _clientServiceProxy = new ClientServiceProxy();
return _clientServiceProxy.page(params);
}
/**
* 创建client
* @param params
* @returns
*/
export async function createClientAsync({ request, changeOkLoading, validate, closeModal }) {
changeOkLoading(true);
await validate();
const _clientServiceProxy = new ClientServiceProxy();
await _clientServiceProxy.create(request);
changeOkLoading(false);
closeModal();
}
export async function updateClientAsync({ request, changeOkLoading, closeModal }) {
try {
changeOkLoading(true);
const _clientServiceProxy = new ClientServiceProxy();
await _clientServiceProxy.updateBasic(request);
message.success(t('common.operationSuccess'));
closeModal();
} catch (error) {
} finally {
changeOkLoading(false);
}
}
/**
* 删除
* @param param0
*/
export async function deleteClientAsync({ id, reload }) {
const _clientServiceProxy = new ClientServiceProxy();
const request = new IdInput();
request.id = id;
await _clientServiceProxy.delete(request);
reload();
}
/**
* 启用禁用
* @param param0
*/
export async function enabledClientAsync({ clientId, enabled, reload }) {
const _clientServiceProxy = new ClientServiceProxy();
const request = new EnabledInput();
request.clientId = clientId;
request.enabled = enabled;
await _clientServiceProxy.enabled(request);
reload();
}
export async function addRedirectUriAsync({ clientId, uri }) {
const _clientServiceProxy = new ClientServiceProxy();
let request = new AddRedirectUriInput();
request.clientId = clientId;
request.uri = uri;
return await _clientServiceProxy.addRedirectUri(request);
}
export async function removeRedirectUriAsync({ clientId, uri }) {
const _clientServiceProxy = new ClientServiceProxy();
let request = new RemoveRedirectUriInput();
request.clientId = clientId;
request.uri = uri;
return await _clientServiceProxy.removeRedirectUri(request);
}
export async function addLogoutRedirectUriAsync({ clientId, uri }) {
const _clientServiceProxy = new ClientServiceProxy();
let request = new RemoveRedirectUriInput();
request.clientId = clientId;
request.uri = uri;
return await _clientServiceProxy.addLogoutRedirectUri(request);
}
export async function removeLogoutRedirectUriAsync({ clientId, uri }) {
const _clientServiceProxy = new ClientServiceProxy();
let request = new RemoveRedirectUriInput();
request.clientId = clientId;
request.uri = uri;
return await _clientServiceProxy.removeLogoutRedirectUri(request);
}
export async function addCorsAsync({ clientId, origin }) {
const _clientServiceProxy = new ClientServiceProxy();
let request = new AddCorsInput();
request.clientId = clientId;
request.origin = origin;
return await _clientServiceProxy.addCors(request);
}
export async function removeCorsAsync({ clientId, origin }) {
const _clientServiceProxy = new ClientServiceProxy();
let request = new RemoveCorsInput();
request.clientId = clientId;
request.origin = origin;
return await _clientServiceProxy.removeCors(request);
}
export async function getAllScopeAsync() {
const _apiScopeServiceProxy = new ApiScopeServiceProxy();
return _apiScopeServiceProxy.all();
}
export async function updateScopesAsync({ clientId, scopes }) {
const _clientServiceProxy = new ClientServiceProxy();
let request = new UpdateScopeInput();
request.clientId = clientId;
request.scopes = scopes;
return await _clientServiceProxy.updateScopes(request);
} | the_stack |
export const lightGraphTheme = {
// 全图默认背景
// backgroundColor: 'rgba(0,0,0,0)',
// 默认色板
// color:['#ff0000','#00ff00','#0000ff','#F8D282','#D2BC5A','#CEA67C','#429698','#57B8B0'],
//color: ['#8AC8C8', '#DA8782', '#F8D282', '#3cb371','#CEA67C', '#429698', '#b8860b', '#ff6347'],
color: ['#1e7ffb', '#e67608', '#07bb74', '#4ac6d7', '#c156f3', '#f5d23d', '#30404f','#778cef'],
// color: ['#325bdb','#87cefa','#da70d6','#32cd32','#6495ed',
// '#ff69b4','#ba55d3','#cd5c5c','#ffa500','#40e0d0',
// '#1e90ff','#ff6347','#7b68ee','#00fa9a','#ffd700',
// '#6699FF','#ff6666','#3cb371','#b8860b','#30e0e0'],
// 图表标题
textStyle: {
fontWeight: 'normal',
fontStyle: 'normal',
fontFamily: '微软雅黑, Arial, Verdana, sans-serif',
fontFamily2: 'microsoft yahei' // IE8- 字体模糊并且不支持不同字体混排,额外指定一份
},
title: {
left: 'center', // 水平安放位置,默认为左对齐,可选为:
// 'center' ¦ 'left' ¦ 'right'
// ¦ {number}(x坐标,单位px)
top: 'top', // 垂直安放位置,默认为全图顶端,可选为:
// 'top' ¦ 'bottom' ¦ 'center'
// ¦ {number}(y坐标,单位px)
//textAlign: null // 水平对齐方式,默认根据x设置自动调整
backgroundColor: 'rgba(0,0,0,0)',
borderColor: '#ccc', // 标题边框颜色
borderWidth: 0, // 标题边框线宽,单位px,默认为0(无边框)
padding: 5, // 标题内边距,单位px,默认各方向内边距为5,
// 接受数组分别设定上右下左边距,同css
itemGap: 25, // 主副标题纵向间隔,单位px,默认为10,
textStyle: {
fontSize: 14,
fontWeight: 'normal',
fontStyle: 'normal',
fontFamily: '微软雅黑, Arial, Verdana, sans-serif',
},
subtextStyle: {
color: '#aaa' // 副标题文字颜色
}
},
// 图例
legend: {
orient: 'horizontal', // 布局方式,默认为水平布局,可选为:
// 'horizontal' ¦ 'vertical'
left: 'right', // 水平安放位置,默认为全图居中,可选为:
// 'center' ¦ 'left' ¦ 'right'
// ¦ {number}(x坐标,单位px)
top: 'top', // 垂直安放位置,默认为全图顶端,可选为:
// 'top' ¦ 'bottom' ¦ 'center'
// ¦ {number}(y坐标,单位px)
backgroundColor: 'rgba(0,0,0,0)',
borderColor: '#ccc', // 图例边框颜色
borderWidth: 0, // 图例边框线宽,单位px,默认为0(无边框)
padding: 5, // 图例内边距,单位px,默认各方向内边距为5,
// 接受数组分别设定上右下左边距,同css
itemGap: 10, // 各个item之间的间隔,单位px,默认为10,
// 横向布局时为水平间隔,纵向布局时为纵向间隔
itemWidth: 20, // 图例图形宽度
itemHeight: 14 // 图例图形高度
},
// 值域
dataRange: {
orient: 'vertical', // 布局方式,默认为垂直布局,可选为:
// 'horizontal' ¦ 'vertical'
x: 'left', // 水平安放位置,默认为全图左对齐,可选为:
// 'center' ¦ 'left' ¦ 'right'
// ¦ {number}(x坐标,单位px)
y: 'bottom', // 垂直安放位置,默认为全图底部,可选为:
// 'top' ¦ 'bottom' ¦ 'center'
// ¦ {number}(y坐标,单位px)
backgroundColor: 'rgba(0,0,0,0)',
borderColor: '#ccc', // 值域边框颜色
borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
// 接受数组分别设定上右下左边距,同css
itemGap: 10, // 各个item之间的间隔,单位px,默认为10,
// 横向布局时为水平间隔,纵向布局时为纵向间隔
itemWidth: 20, // 值域图形宽度,线性渐变水平布局宽度为该值 * 10
itemHeight: 14, // 值域图形高度,线性渐变垂直布局高度为该值 * 10
splitNumber: 5, // 分割段数,默认为5,为0时为线性渐变
color: ['#1e90ff', '#f0ffff'] //颜色
//text:['高','低'], // 文本,默认为数值文本
},
toolbox: {
orient: 'horizontal', // 布局方式,默认为水平布局,可选为:
// 'horizontal' ¦ 'vertical'
x: 'right', // 水平安放位置,默认为全图右对齐,可选为:
// 'center' ¦ 'left' ¦ 'right'
// ¦ {number}(x坐标,单位px)
y: 'top', // 垂直安放位置,默认为全图顶端,可选为:
// 'top' ¦ 'bottom' ¦ 'center'
// ¦ {number}(y坐标,单位px)
color: ['#1e90ff', '#22bb22', '#4b0082', '#d2691e'],
backgroundColor: 'rgba(0,0,0,0)', // 工具箱背景颜色
borderColor: '#ccc', // 工具箱边框颜色
borderWidth: 0, // 工具箱边框线宽,单位px,默认为0(无边框)
padding: 5, // 工具箱内边距,单位px,默认各方向内边距为5,
// 接受数组分别设定上右下左边距,同css
itemGap: 10, // 各个item之间的间隔,单位px,默认为10,
// 横向布局时为水平间隔,纵向布局时为纵向间隔
itemSize: 16, // 工具箱图形宽度
featureImageIcon: {}, // 自定义图片icon
featureTitle: {
mark: '辅助线开关',
markUndo: '删除辅助线',
markClear: '清空辅助线',
dataZoom: '区域缩放',
dataZoomReset: '区域缩放后退',
dataView: '数据视图',
lineChart: '折线图切换',
barChart: '柱形图切换',
restore: '还原',
saveAsImage: '保存为图片'
}
},
// 提示框
tooltip: {
trigger: 'item', // 触发类型,默认数据触发,见下图,可选为:'item' ¦ 'axis'
showDelay: 20, // 显示延迟,添加显示延迟可以避免频繁切换,单位ms
hideDelay: 20, // 隐藏延迟,单位ms
transitionDuration: 0.2, // 动画变换时间,单位s
backgroundColor: 'rgba(0,0,0,0.7)', // 提示背景颜色,默认为透明度为0.7的黑色
borderColor: '#333', // 提示边框颜色
borderRadius: 4, // 提示边框圆角,单位px,默认为4
borderWidth: 0, // 提示边框线宽,单位px,默认为0(无边框)
padding: 5, // 提示内边距,单位px,默认各方向内边距为5,
// 接受数组分别设定上右下左边距,同css
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'line', // 默认为直线,可选为:'line' | 'shadow'
lineStyle: { // 直线指示器样式设置
color: '#48b',
width: 2,
type: 'solid'
},
shadowStyle: { // 阴影指示器样式设置
width: 'auto', // 阴影大小
color: 'rgba(150,150,150,0.3)' // 阴影颜色
}
},
color: '#fff'
},
// 区域缩放控制器
dataZoom: {
orient: 'horizontal', // 布局方式,默认为水平布局,可选为:
// 'horizontal' ¦ 'vertical'
// x: {number}, // 水平安放位置,默认为根据grid参数适配,可选为:
// {number}(x坐标,单位px)
// y: {number}, // 垂直安放位置,默认为根据grid参数适配,可选为:
// {number}(y坐标,单位px)
// width: {number}, // 指定宽度,横向布局时默认为根据grid参数适配
// height: {number}, // 指定高度,纵向布局时默认为根据grid参数适配
backgroundColor: 'rgba(0,0,0,0)', // 背景颜色
dataBackgroundColor: '#eee', // 数据背景颜色
fillerColor: 'rgba(144,197,237,0.2)', // 填充颜色
handleColor: 'rgba(70,130,180,0.8)' // 手柄颜色
},
// 网格
grid: {
x: 80,
y: 60,
x2: 80,
y2: 60,
// width: {totalWidth} - x - x2,
// height: {totalHeight} - y - y2,
backgroundColor: 'rgba(0,0,0,0)',
borderWidth: 1,
borderColor: '#ccc'
},
// 类目轴
categoryAxis: {
position: 'bottom', // 位置
nameLocation: 'end', // 坐标轴名字位置,支持'start' | 'end'
boundaryGap: true, // 类目起始和结束两端空白策略
axisLine: { // 坐标轴线
show: true, // 默认显示,属性show控制显示与否
lineStyle: { // 属性lineStyle控制线条样式
color: 'rgb(255,255,255,0.15)',
width: 1,
type: 'solid'
}
},
axisTick: { // 坐标轴小标记
show: false, // 属性show控制显示与否,默认不显示
interval: 'auto',
// onGap: null,
inside: false, // 控制小标记是否在grid里
length: 5, // 属性length控制线长
lineStyle: { // 属性lineStyle控制线条样式
width: 1
}
},
axisLabel: { // 坐标轴文本标签,详见axis.axisLabel
show: true,
interval: 'auto',
rotate: 0,
margin: 8,
// formatter: null,
// 其余属性默认使用全局文本样式,详见TEXTSTYLE
color: '#666'
},
splitLine: { // 分隔线
show: true, // 默认显示,属性show控制显示与否
// onGap: null,
lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式
color: ["#e9e9e9"],
width: 1,
type: 'solid'
}
},
splitArea: { // 分隔区域
show: false, // 默认不显示,属性show控制显示与否
// onGap: null,
areaStyle: { // 属性areaStyle(详见areaStyle)控制区域样式
color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
}
}
},
// 数值型坐标轴默认参数
valueAxis: {
position: 'left', // 位置
nameLocation: 'end', // 坐标轴名字位置,支持'start' | 'end'
color: ['#325bdb'],
fontSize: 12,
// 坐标轴文字样式,默认取全局样式
boundaryGap: [0, 0], // 数值起始和结束两端空白策略
splitNumber: 5, // 分割段数,默认为5
axisLine: { // 坐标轴线
show: true, // 默认显示,属性show控制显示与否
lineStyle: { // 属性lineStyle控制线条样式
color: 'rgb(255,255,255,0.15)',
width: 1,
type: 'solid'
}
},
nameTextStyle: {
color: '#ccc'
},
axisTick: { // 坐标轴小标记
show: false, // 属性show控制显示与否,默认不显示
inside: false, // 控制小标记是否在grid里
length: 5, // 属性length控制线长
lineStyle: { // 属性lineStyle控制线条样式
color: '#333',
width: 1
}
},
axisLabel: { // 坐标轴文本标签,详见axis.axisLabel
show: true,
rotate: 0,
margin: 8,
color: '#666',
formatter: null,
// 其余属性默认使用全局文本样式,详见TEXTSTYLE
},
splitLine: { // 分隔线
show: true, // 默认显示,属性show控制显示与否
lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式
color: ['#e9e9e9'],
width: 1,
type: 'solid'
}
},
splitArea: { // 分隔区域
show: false, // 默认不显示,属性show控制显示与否
areaStyle: { // 属性areaStyle(详见areaStyle)控制区域样式
color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
}
}
},
polar: {
center: ['50%', '50%'], // 默认全局居中
radius: '75%',
startAngle: 90,
splitNumber: 5,
name: {
show: true,
color: '#333'
},
axisLine: { // 坐标轴线
show: true, // 默认显示,属性show控制显示与否
lineStyle: { // 属性lineStyle控制线条样式
color: '#ccc',
width: 1,
type: 'solid'
}
},
axisLabel: { // 坐标轴文本标签,详见axis.axisLabel
show: false,
color: '#333'
},
splitArea: {
show: true,
areaStyle: {
color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
}
},
splitLine: {
show: true,
lineStyle: {
width: 1,
color: '#ccc'
}
}
},
// 柱形图默认参数
bar: {
barMinHeight: 0, // 最小高度改为0
// barWidth: null, // 默认自适应
barGap: '30%', // 柱间距离,默认为柱形宽度的30%,可设固定值
barCategoryGap: '20%', // 类目间柱形距离,默认为类目间距的20%,可设固定值
itemStyle: {
normal: {
// color: '各异',
barBorderColor: '#fff', // 柱条边线
barBorderWidth: 0, // 柱条边线线宽,单位px,默认为1
label: {
show: false
// position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
// 'inside'|'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
},
emphasis: {
// color: '各异',
barBorderColor: 'rgba(0,0,0,0)', // 柱条边线
barBorderWidth: 0, // 柱条边线线宽,单位px,默认为1
label: {
show: false
// position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
// 'inside'|'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
}
}
},
// 折线图默认参数
line: {
calculable: false,
itemStyle: {
normal: {
// color: 各异,
label: {
show: false
// position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
// 'inside'|'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
lineStyle: {
width: 2,
type: 'solid',
shadowColor: 'rgba(0,0,0,0)', //默认透明
shadowBlur: 5,
shadowOffsetX: 3,
shadowOffsetY: 3
}
},
emphasis: {
// color: 各异,
label: {
show: false
// position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
// 'inside'|'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
}
},
smooth: true,
//symbol: null, // 拐点图形类型
symbolSize: 2, // 拐点图形大小
//symbolRotate : null, // 拐点图形旋转控制
showAllSymbol: true // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略)
},
// K线图默认参数
k: {
// barWidth : null // 默认自适应
// barMaxWidth : null // 默认自适应
itemStyle: {
normal: {
color: '#fff', // 阳线填充颜色
color0: '#00aa11', // 阴线填充颜色
lineStyle: {
width: 1,
color: '#ff3200', // 阳线边框颜色
color0: '#00aa11' // 阴线边框颜色
}
},
emphasis: {
// color: 各异,
// color0: 各异
}
}
},
// 散点图默认参数
scatter: {
//symbol: null, // 图形类型
symbolSize: 4, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
//symbolRotate : null, // 图形旋转控制
large: false, // 大规模散点图
largeThreshold: 2000, // 大规模阀值,large为true且数据量>largeThreshold才启用大规模模式
itemStyle: {
normal: {
// color: 各异,
label: {
show: false
// position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
// 'inside'|'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
},
emphasis: {
// color: '各异'
label: {
show: false
// position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
// 'inside'|'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
}
}
},
// 雷达图默认参数
radar: {
itemStyle: {
normal: {
// color: 各异,
label: {
show: false
},
lineStyle: {
width: 2,
type: 'solid'
}
},
emphasis: {
// color: 各异,
label: {
show: false
}
}
},
//symbol: null, // 拐点图形类型
symbolSize: 2 // 可计算特性参数,空数据拖拽提示图形大小
//symbolRotate : null, // 图形旋转控制
},
// 饼图默认参数
pie: {
center: ['50%', '50%'], // 默认全局居中
radius: [0, '75%'],
clockWise: false, // 默认逆时针
startAngle: 90,
minAngle: 1, // 最小角度改为0
selectedOffset: 10, // 选中是扇区偏移量
hoverAnimation:false,
calculable: false,
itemStyle: {
normal: {
// color: 各异,
borderColor: '#fff',
borderWidth: 0,
label: {
show: true,
position: 'outer',
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
labelLine: {
show: true,
length: 35,
lineStyle: {
// color: 各异,
width: 1,
type: 'solid'
}
}
},
emphasis: {
// color: 各异,
borderColor: 'rgba(0,0,0,0)',
borderWidth: 1,
label: {
show: false
// position: 'outer'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
labelLine: {
show: false,
length: 35,
lineStyle: {
// color: 各异,
width: 1,
type: 'solid'
}
}
}
}
},
map: {
mapType: 'china', // 各省的mapType暂时都用中文
mapLocation: {
x: 'center',
y: 'center'
// width // 自适应
// height // 自适应
},
showLegendSymbol: true, // 显示图例颜色标识(系列标识的小圆点),存在legend时生效
itemStyle: {
normal: {
// color: 各异,
borderColor: '#fff',
borderWidth: 1,
areaStyle: {
color: '#ccc' //rgba(135,206,250,0.8)
},
label: {
show: false,
color: 'rgba(139,69,19,1)'
}
},
emphasis: { // 也是选中样式
// color: 各异,
borderColor: 'rgba(0,0,0,0)',
borderWidth: 1,
areaStyle: {
color: 'rgba(255,215,0,0.8)'
},
label: {
show: false,
color: 'rgba(139,69,19,1)'
}
}
}
},
force: {
// 数据map到圆的半径的最小值和最大值
minRadius: 10,
maxRadius: 20,
density: 1.0,
attractiveness: 1.0,
// 初始化的随机大小位置
initSize: 300,
// 向心力因子,越大向心力越大
centripetal: 1,
// 冷却因子
coolDown: 0.99,
// 分类里如果有样式会覆盖节点默认样式
itemStyle: {
normal: {
// color: 各异,
label: {
show: false
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
nodeStyle: {
brushType: 'both',
color: '#f08c2e',
strokeColor: '#5182ab'
},
linkStyle: {
strokeColor: '#5182ab'
}
},
emphasis: {
// color: 各异,
label: {
show: false
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
nodeStyle: {},
linkStyle: {}
}
}
},
chord: {
radius: ['65%', '75%'],
center: ['50%', '50%'],
padding: 2,
sort: 'none', // can be 'none', 'ascending', 'descending'
sortSub: 'none', // can be 'none', 'ascending', 'descending'
startAngle: 90,
clockWise: false,
showScale: false,
showScaleText: false,
itemStyle: {
normal: {
label: {
show: true
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
lineStyle: {
width: 0,
color: '#000'
},
chordStyle: {
lineStyle: {
width: 1,
color: '#666'
}
}
},
emphasis: {
lineStyle: {
width: 0,
color: '#000'
},
chordStyle: {
lineStyle: {
width: 2,
color: '#333'
}
}
}
}
},
island: {
r: 15,
calculateStep: 0.1 // 滚轮可计算步长 0.1 = 10%
},
markPoint: {
symbol: 'pin', // 标注类型
symbolSize: 10, // 标注大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
//symbolRotate : null, // 标注旋转控制
itemStyle: {
normal: {
// color: 各异,
// borderColor: 各异, // 标注边线颜色,优先于color
borderWidth: 2, // 标注边线线宽,单位px,默认为1
label: {
show: true,
position: 'inside' // 可选为'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
},
emphasis: {
// color: 各异
label: {
show: true
// position: 'inside' // 'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
}
}
},
markLine: {
// 标线起始和结束的symbol介绍类型,如果都一样,可以直接传string
symbol: ['circle', 'arrow'],
// 标线起始和结束的symbol大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
symbolSize: [2, 4],
// 标线起始和结束的symbol旋转控制
//symbolRotate : null,
itemStyle: {
normal: {
// color: 各异, // 标线主色,线色,symbol主色
// borderColor: 随color, // 标线symbol边框颜色,优先于color
borderWidth: 2, // 标线symbol边框线宽,单位px,默认为2
label: {
// show: false,
// 可选为 'start'|'end'|'left'|'right'|'top'|'bottom'
position: 'end',
fontSize: 12
},
lineStyle: {
// color: 随borderColor, // 主色,线色,优先级高于borderColor和color
// width: 随borderWidth, // 优先于borderWidth
type: 'solid',
shadowColor: 'rgba(0,0,0,0)', //默认透明
shadowBlur: 5,
shadowOffsetX: 3,
shadowOffsetY: 3
}
},
emphasis: {
// color: 各异
label: {
show: false
// position: 'inside' // 'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
lineStyle: {}
}
}
},
// 默认标志图形类型列表
symbolList: [
'circle', 'rectangle', 'triangle', 'diamond',
'emptyCircle', 'emptyRectangle', 'emptyTriangle', 'emptyDiamond'
],
loadingText: 'Loading...',
// 可计算特性配置,孤岛,提示颜色
calculable: false, // 默认关闭可计算特性
calculableColor: 'rgba(255,165,0,0.6)', // 拖拽提示边框颜色
calculableHolderColor: '#ccc', // 可计算占位提示颜色
nameConnector: ' & ',
valueConnector: ' : ',
animation: true,
animationThreshold: 2500, // 动画元素阀值,产生的图形原素超过2500不出动画
addDataAnimation: true, // 动态数据接口是否开启动画效果
animationDuration: 2000,
animationEasing: 'ExponentialOut' //BounceOut
}
export const darkGraphTheme = {
// 全图默认背景
// backgroundColor: 'rgba(0,0,0,0)',
// 默认色板
// color:['#ff0000','#00ff00','#0000ff','#F8D282','#D2BC5A','#CEA67C','#429698','#57B8B0'],
//color: ['#8AC8C8', '#DA8782', '#F8D282', '#3cb371','#CEA67C', '#429698', '#b8860b', '#ff6347'],
color: ['#207ef8', '#ed8a2b', '#06ba74', '#4ac6d7', '#c156f3', '#f5d23d', '#778cef', '#f26c82', '#186bd2'],
// color: ['#325bdb','#87cefa','#da70d6','#32cd32','#6495ed',
// '#ff69b4','#ba55d3','#cd5c5c','#ffa500','#40e0d0',
// '#1e90ff','#ff6347','#7b68ee','#00fa9a','#ffd700',
// '#6699FF','#ff6666','#3cb371','#b8860b','#30e0e0'],
// 图表标题
textStyle: {
fontWeight: 'normal',
fontStyle: 'normal',
fontFamily: '微软雅黑, Arial, Verdana, sans-serif',
fontFamily2: 'microsoft yahei' // IE8- 字体模糊并且不支持不同字体混排,额外指定一份
},
title: {
left: 'center', // 水平安放位置,默认为左对齐,可选为:
// 'center' ¦ 'left' ¦ 'right'
// ¦ {number}(x坐标,单位px)
top: 'top', // 垂直安放位置,默认为全图顶端,可选为:
// 'top' ¦ 'bottom' ¦ 'center'
// ¦ {number}(y坐标,单位px)
//textAlign: null // 水平对齐方式,默认根据x设置自动调整
backgroundColor: 'rgba(0,0,0,0)',
borderColor: '#ccc', // 标题边框颜色
borderWidth: 0, // 标题边框线宽,单位px,默认为0(无边框)
padding: 5, // 标题内边距,单位px,默认各方向内边距为5,
// 接受数组分别设定上右下左边距,同css
itemGap: 25, // 主副标题纵向间隔,单位px,默认为10,
textStyle: {
fontSize: 14,
fontWeight: 'normal',
fontStyle: 'normal',
fontFamily: '微软雅黑, Arial, Verdana, sans-serif',
color: '#fff'
},
subtextStyle: {
color: '#fff' // 副标题文字颜色
}
},
// 图例
legend: {
orient: 'horizontal', // 布局方式,默认为水平布局,可选为:
// 'horizontal' ¦ 'vertical'
left: 'right', // 水平安放位置,默认为全图居中,可选为:
// 'center' ¦ 'left' ¦ 'right'
// ¦ {number}(x坐标,单位px)
top: 'top', // 垂直安放位置,默认为全图顶端,可选为:
// 'top' ¦ 'bottom' ¦ 'center'
// ¦ {number}(y坐标,单位px)
backgroundColor: 'rgba(0,0,0,0)',
borderColor: '#ccc', // 图例边框颜色
borderWidth: 0, // 图例边框线宽,单位px,默认为0(无边框)
padding: 5, // 图例内边距,单位px,默认各方向内边距为5,
// 接受数组分别设定上右下左边距,同css
itemGap: 10, // 各个item之间的间隔,单位px,默认为10,
// 横向布局时为水平间隔,纵向布局时为纵向间隔
itemWidth: 20, // 图例图形宽度
itemHeight: 14, // 图例图形高度
textStyle: {
color: '#666'
}
},
// 值域
dataRange: {
orient: 'vertical', // 布局方式,默认为垂直布局,可选为:
// 'horizontal' ¦ 'vertical'
x: 'left', // 水平安放位置,默认为全图左对齐,可选为:
// 'center' ¦ 'left' ¦ 'right'
// ¦ {number}(x坐标,单位px)
y: 'bottom', // 垂直安放位置,默认为全图底部,可选为:
// 'top' ¦ 'bottom' ¦ 'center'
// ¦ {number}(y坐标,单位px)
backgroundColor: 'rgba(0,0,0,0)',
borderColor: '#ccc', // 值域边框颜色
borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
// 接受数组分别设定上右下左边距,同css
itemGap: 10, // 各个item之间的间隔,单位px,默认为10,
// 横向布局时为水平间隔,纵向布局时为纵向间隔
itemWidth: 20, // 值域图形宽度,线性渐变水平布局宽度为该值 * 10
itemHeight: 14, // 值域图形高度,线性渐变垂直布局高度为该值 * 10
splitNumber: 5, // 分割段数,默认为5,为0时为线性渐变
color: ['#1e90ff', '#f0ffff'] //颜色
//text:['高','低'], // 文本,默认为数值文本
},
toolbox: {
orient: 'horizontal', // 布局方式,默认为水平布局,可选为:
// 'horizontal' ¦ 'vertical'
x: 'right', // 水平安放位置,默认为全图右对齐,可选为:
// 'center' ¦ 'left' ¦ 'right'
// ¦ {number}(x坐标,单位px)
y: 'top', // 垂直安放位置,默认为全图顶端,可选为:
// 'top' ¦ 'bottom' ¦ 'center'
// ¦ {number}(y坐标,单位px)
color: ['#1e90ff', '#22bb22', '#4b0082', '#d2691e'],
backgroundColor: 'rgba(0,0,0,0)', // 工具箱背景颜色
borderColor: '#ccc', // 工具箱边框颜色
borderWidth: 0, // 工具箱边框线宽,单位px,默认为0(无边框)
padding: 5, // 工具箱内边距,单位px,默认各方向内边距为5,
// 接受数组分别设定上右下左边距,同css
itemGap: 10, // 各个item之间的间隔,单位px,默认为10,
// 横向布局时为水平间隔,纵向布局时为纵向间隔
itemSize: 16, // 工具箱图形宽度
featureImageIcon: {}, // 自定义图片icon
featureTitle: {
mark: '辅助线开关',
markUndo: '删除辅助线',
markClear: '清空辅助线',
dataZoom: '区域缩放',
dataZoomReset: '区域缩放后退',
dataView: '数据视图',
lineChart: '折线图切换',
barChart: '柱形图切换',
restore: '还原',
saveAsImage: '保存为图片'
}
},
// 提示框
tooltip: {
trigger: 'item', // 触发类型,默认数据触发,见下图,可选为:'item' ¦ 'axis'
showDelay: 20, // 显示延迟,添加显示延迟可以避免频繁切换,单位ms
hideDelay: 20, // 隐藏延迟,单位ms
transitionDuration: 0.2, // 动画变换时间,单位s
backgroundColor: 'rgba(0,0,0,0.7)', // 提示背景颜色,默认为透明度为0.7的黑色
borderColor: '#333', // 提示边框颜色
borderRadius: 4, // 提示边框圆角,单位px,默认为4
borderWidth: 0, // 提示边框线宽,单位px,默认为0(无边框)
padding: 5, // 提示内边距,单位px,默认各方向内边距为5,
// 接受数组分别设定上右下左边距,同css
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'line', // 默认为直线,可选为:'line' | 'shadow'
lineStyle: { // 直线指示器样式设置
color: '#48b',
width: 2,
type: 'solid'
},
shadowStyle: { // 阴影指示器样式设置
width: 'auto', // 阴影大小
color: 'rgba(150,150,150,0.3)' // 阴影颜色
}
},
color: '#fff'
},
// 区域缩放控制器
dataZoom: {
orient: 'horizontal', // 布局方式,默认为水平布局,可选为:
// 'horizontal' ¦ 'vertical'
// x: {number}, // 水平安放位置,默认为根据grid参数适配,可选为:
// {number}(x坐标,单位px)
// y: {number}, // 垂直安放位置,默认为根据grid参数适配,可选为:
// {number}(y坐标,单位px)
// width: {number}, // 指定宽度,横向布局时默认为根据grid参数适配
// height: {number}, // 指定高度,纵向布局时默认为根据grid参数适配
backgroundColor: 'rgba(0,0,0,0)', // 背景颜色
dataBackgroundColor: '#eee', // 数据背景颜色
fillerColor: 'rgba(144,197,237,0.2)', // 填充颜色
handleColor: 'rgba(70,130,180,0.8)' // 手柄颜色
},
// 网格
grid: {
x: 80,
y: 60,
x2: 80,
y2: 60,
// width: {totalWidth} - x - x2,
// height: {totalHeight} - y - y2,
backgroundColor: 'rgba(0,0,0,0)',
borderWidth: 1,
borderColor: '#ccc'
},
// 类目轴
categoryAxis: {
position: 'bottom', // 位置
nameLocation: 'end', // 坐标轴名字位置,支持'start' | 'end'
boundaryGap: true, // 类目起始和结束两端空白策略
axisLine: { // 坐标轴线
show: true, // 默认显示,属性show控制显示与否
lineStyle: { // 属性lineStyle控制线条样式
color: '#30414c',
width: 1,
type: 'solid'
}
},
axisTick: { // 坐标轴小标记
show: false, // 属性show控制显示与否,默认不显示
interval: 'auto',
// onGap: null,
inside: false, // 控制小标记是否在grid里
length: 5, // 属性length控制线长
lineStyle: { // 属性lineStyle控制线条样式
width: 1
}
},
axisLabel: { // 坐标轴文本标签,详见axis.axisLabel
show: true,
interval: 'auto',
rotate: 0,
margin: 8,
// formatter: null,
// 其余属性默认使用全局文本样式,详见TEXTSTYLE
color: '#666'
},
splitLine: { // 分隔线
show: true, // 默认显示,属性show控制显示与否
// onGap: null,
lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式
color: ["#30414c"],
width: 1,
type: 'solid'
}
},
splitArea: { // 分隔区域
show: false, // 默认不显示,属性show控制显示与否
// onGap: null,
areaStyle: { // 属性areaStyle(详见areaStyle)控制区域样式
color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
}
}
},
// 数值型坐标轴默认参数
valueAxis: {
position: 'left', // 位置
nameLocation: 'end', // 坐标轴名字位置,支持'start' | 'end'
color: ['#325bdb'],
fontSize: 12,
// 坐标轴文字样式,默认取全局样式
boundaryGap: [0, 0], // 数值起始和结束两端空白策略
splitNumber: 5, // 分割段数,默认为5
axisLine: { // 坐标轴线
show: true, // 默认显示,属性show控制显示与否
lineStyle: { // 属性lineStyle控制线条样式
color: '#30414c',
width: 1,
type: 'solid'
}
},
axisTick: { // 坐标轴小标记
show: false, // 属性show控制显示与否,默认不显示
inside: false, // 控制小标记是否在grid里
length: 5, // 属性length控制线长
lineStyle: { // 属性lineStyle控制线条样式
color: '#333',
width: 1
}
},
axisLabel: { // 坐标轴文本标签,详见axis.axisLabel
show: true,
rotate: 0,
margin: 8,
color: '#666',
formatter: null,
// 其余属性默认使用全局文本样式,详见TEXTSTYLE
},
splitLine: { // 分隔线
show: true, // 默认显示,属性show控制显示与否
lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式
color: ['#30414c'],
width: 1,
type: 'solid'
}
},
splitArea: { // 分隔区域
show: false, // 默认不显示,属性show控制显示与否
areaStyle: { // 属性areaStyle(详见areaStyle)控制区域样式
color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
}
}
},
polar: {
center: ['50%', '50%'], // 默认全局居中
radius: '75%',
startAngle: 90,
splitNumber: 5,
name: {
show: true,
color: '#333'
},
axisLine: { // 坐标轴线
show: true, // 默认显示,属性show控制显示与否
lineStyle: { // 属性lineStyle控制线条样式
color: '#ccc',
width: 1,
type: 'solid'
}
},
axisLabel: { // 坐标轴文本标签,详见axis.axisLabel
show: false,
color: '#fff'
},
splitArea: {
show: true,
areaStyle: {
color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
}
},
splitLine: {
show: true,
lineStyle: {
width: 1,
color: '#ccc'
}
}
},
// 柱形图默认参数
bar: {
barMinHeight: 0, // 最小高度改为0
// barWidth: null, // 默认自适应
barGap: '30%', // 柱间距离,默认为柱形宽度的30%,可设固定值
barCategoryGap: '20%', // 类目间柱形距离,默认为类目间距的20%,可设固定值
itemStyle: {
normal: {
// color: '各异',
barBorderColor: '#fff', // 柱条边线
barBorderWidth: 0, // 柱条边线线宽,单位px,默认为1
label: {
show: false
// position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
// 'inside'|'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
},
emphasis: {
// color: '各异',
barBorderColor: 'rgba(0,0,0,0)', // 柱条边线
barBorderWidth: 0, // 柱条边线线宽,单位px,默认为1
label: {
show: false
// position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
// 'inside'|'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
}
}
},
// 折线图默认参数
line: {
calculable: false,
itemStyle: {
normal: {
// color: 各异,
label: {
show: false
// position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
// 'inside'|'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
lineStyle: {
width: 2,
type: 'solid',
shadowColor: 'rgba(0,0,0,0)', //默认透明
shadowBlur: 5,
shadowOffsetX: 3,
shadowOffsetY: 3
}
},
emphasis: {
// color: 各异,
label: {
show: false
// position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
// 'inside'|'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
}
},
smooth: true,
//symbol: null, // 拐点图形类型
symbolSize: 2, // 拐点图形大小
//symbolRotate : null, // 拐点图形旋转控制
showAllSymbol: true // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略)
},
// K线图默认参数
k: {
// barWidth : null // 默认自适应
// barMaxWidth : null // 默认自适应
itemStyle: {
normal: {
color: '#fff', // 阳线填充颜色
color0: '#00aa11', // 阴线填充颜色
lineStyle: {
width: 1,
color: '#ff3200', // 阳线边框颜色
color0: '#00aa11' // 阴线边框颜色
}
},
emphasis: {
// color: 各异,
// color0: 各异
}
}
},
// 散点图默认参数
scatter: {
//symbol: null, // 图形类型
symbolSize: 4, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
//symbolRotate : null, // 图形旋转控制
large: false, // 大规模散点图
largeThreshold: 2000, // 大规模阀值,large为true且数据量>largeThreshold才启用大规模模式
itemStyle: {
normal: {
// color: 各异,
label: {
show: false
// position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
// 'inside'|'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
},
emphasis: {
// color: '各异'
label: {
show: false
// position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
// 'inside'|'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
}
}
},
// 雷达图默认参数
radar: {
itemStyle: {
normal: {
// color: 各异,
label: {
show: false
},
lineStyle: {
width: 2,
type: 'solid'
}
},
emphasis: {
// color: 各异,
label: {
show: false
}
}
},
//symbol: null, // 拐点图形类型
symbolSize: 2 // 可计算特性参数,空数据拖拽提示图形大小
//symbolRotate : null, // 图形旋转控制
},
// 饼图默认参数
pie: {
center: ['50%', '50%'], // 默认全局居中
radius: [0, '75%'],
clockWise: false, // 默认逆时针
startAngle: 90,
minAngle: 1, // 最小角度改为0
selectedOffset: 10, // 选中是扇区偏移量
hoverAnimation:false,
calculable: false,
itemStyle: {
normal: {
// color: 各异,
borderColor: '#fff',
borderWidth: 0,
label: {
show: true,
position: 'outer',
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
labelLine: {
show: true,
length: 35,
lineStyle: {
// color: 各异,
width: 1,
type: 'solid'
}
}
},
emphasis: {
// color: 各异,
borderColor: 'rgba(0,0,0,0)',
borderWidth: 1,
label: {
show: false
// position: 'outer'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
labelLine: {
show: false,
length: 35,
lineStyle: {
// color: 各异,
width: 1,
type: 'solid'
}
}
}
}
},
map: {
mapType: 'china', // 各省的mapType暂时都用中文
mapLocation: {
x: 'center',
y: 'center'
// width // 自适应
// height // 自适应
},
showLegendSymbol: true, // 显示图例颜色标识(系列标识的小圆点),存在legend时生效
itemStyle: {
normal: {
// color: 各异,
borderColor: '#fff',
borderWidth: 1,
areaStyle: {
color: '#ccc' //rgba(135,206,250,0.8)
},
label: {
show: false,
color: 'rgba(139,69,19,1)'
}
},
emphasis: { // 也是选中样式
// color: 各异,
borderColor: 'rgba(0,0,0,0)',
borderWidth: 1,
areaStyle: {
color: 'rgba(255,215,0,0.8)'
},
label: {
show: false,
color: 'rgba(139,69,19,1)'
}
}
}
},
force: {
// 数据map到圆的半径的最小值和最大值
minRadius: 10,
maxRadius: 20,
density: 1.0,
attractiveness: 1.0,
// 初始化的随机大小位置
initSize: 300,
// 向心力因子,越大向心力越大
centripetal: 1,
// 冷却因子
coolDown: 0.99,
// 分类里如果有样式会覆盖节点默认样式
itemStyle: {
normal: {
// color: 各异,
label: {
show: false
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
nodeStyle: {
brushType: 'both',
color: '#f08c2e',
strokeColor: '#5182ab'
},
linkStyle: {
strokeColor: '#5182ab'
}
},
emphasis: {
// color: 各异,
label: {
show: false
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
nodeStyle: {},
linkStyle: {}
}
}
},
chord: {
radius: ['65%', '75%'],
center: ['50%', '50%'],
padding: 2,
sort: 'none', // can be 'none', 'ascending', 'descending'
sortSub: 'none', // can be 'none', 'ascending', 'descending'
startAngle: 90,
clockWise: false,
showScale: false,
showScaleText: false,
itemStyle: {
normal: {
label: {
show: true
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
lineStyle: {
width: 0,
color: '#000'
},
chordStyle: {
lineStyle: {
width: 1,
color: '#666'
}
}
},
emphasis: {
lineStyle: {
width: 0,
color: '#000'
},
chordStyle: {
lineStyle: {
width: 2,
color: '#333'
}
}
}
}
},
island: {
r: 15,
calculateStep: 0.1 // 滚轮可计算步长 0.1 = 10%
},
markPoint: {
symbol: 'pin', // 标注类型
symbolSize: 10, // 标注大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
//symbolRotate : null, // 标注旋转控制
itemStyle: {
normal: {
// color: 各异,
// borderColor: 各异, // 标注边线颜色,优先于color
borderWidth: 2, // 标注边线线宽,单位px,默认为1
label: {
show: true,
position: 'inside' // 可选为'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
},
emphasis: {
// color: 各异
label: {
show: true
// position: 'inside' // 'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
}
}
}
},
markLine: {
// 标线起始和结束的symbol介绍类型,如果都一样,可以直接传string
symbol: ['circle', 'arrow'],
// 标线起始和结束的symbol大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
symbolSize: [2, 4],
// 标线起始和结束的symbol旋转控制
//symbolRotate : null,
itemStyle: {
normal: {
// color: 各异, // 标线主色,线色,symbol主色
// borderColor: 随color, // 标线symbol边框颜色,优先于color
borderWidth: 2, // 标线symbol边框线宽,单位px,默认为2
label: {
// show: false,
// 可选为 'start'|'end'|'left'|'right'|'top'|'bottom'
position: 'end',
fontSize: 12
},
lineStyle: {
// color: 随borderColor, // 主色,线色,优先级高于borderColor和color
// width: 随borderWidth, // 优先于borderWidth
type: 'solid',
shadowColor: 'rgba(0,0,0,0)', //默认透明
shadowBlur: 5,
shadowOffsetX: 3,
shadowOffsetY: 3
}
},
emphasis: {
// color: 各异
label: {
show: false
// position: 'inside' // 'left'|'right'|'top'|'bottom'
// textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE
},
lineStyle: {}
}
}
},
// 默认标志图形类型列表
symbolList: [
'circle', 'rectangle', 'triangle', 'diamond',
'emptyCircle', 'emptyRectangle', 'emptyTriangle', 'emptyDiamond'
],
loadingText: 'Loading...',
// 可计算特性配置,孤岛,提示颜色
calculable: false, // 默认关闭可计算特性
calculableColor: 'rgba(255,165,0,0.6)', // 拖拽提示边框颜色
calculableHolderColor: '#ccc', // 可计算占位提示颜色
nameConnector: ' & ',
valueConnector: ' : ',
animation: true,
animationThreshold: 2500, // 动画元素阀值,产生的图形原素超过2500不出动画
addDataAnimation: true, // 动态数据接口是否开启动画效果
animationDuration: 2000,
animationEasing: 'ExponentialOut' //BounceOut
} | the_stack |
import { Viewport } from '../../mol-canvas3d/camera/util';
import { CameraHelperParams } from '../../mol-canvas3d/helper/camera-helper';
import { ImagePass } from '../../mol-canvas3d/passes/image';
import { canvasToBlob } from '../../mol-canvas3d/util';
import { equalEps } from '../../mol-math/linear-algebra/3d/common';
import { PluginComponent } from '../../mol-plugin-state/component';
import { PluginStateObject } from '../../mol-plugin-state/objects';
import { StateSelection } from '../../mol-state';
import { RuntimeContext, Task } from '../../mol-task';
import { Color } from '../../mol-util/color';
import { download } from '../../mol-util/download';
import { ParamDefinition as PD } from '../../mol-util/param-definition';
import { SetUtils } from '../../mol-util/set';
import { PluginContext } from '../context';
export { ViewportScreenshotHelper, ViewportScreenshotHelperParams };
namespace ViewportScreenshotHelper {
export type ResolutionSettings = PD.Values<ReturnType<ViewportScreenshotHelper['createParams']>>['resolution']
export type ResolutionTypes = ResolutionSettings['name']
}
type ViewportScreenshotHelperParams = PD.Values<ReturnType<ViewportScreenshotHelper['createParams']>>
class ViewportScreenshotHelper extends PluginComponent {
private createParams() {
const max = Math.min(this.plugin.canvas3d ? this.plugin.canvas3d.webgl.maxRenderbufferSize : 4096, 4096);
return {
resolution: PD.MappedStatic('viewport', {
viewport: PD.Group({}),
hd: PD.Group({}),
'full-hd': PD.Group({}),
'ultra-hd': PD.Group({}),
custom: PD.Group({
width: PD.Numeric(1920, { min: 128, max, step: 1 }),
height: PD.Numeric(1080, { min: 128, max, step: 1 }),
}, { isFlat: true })
}, {
options: [
['viewport', 'Viewport'],
['hd', 'HD (1280 x 720)'],
['full-hd', 'Full HD (1920 x 1080)'],
['ultra-hd', 'Ultra HD (3840 x 2160)'],
['custom', 'Custom']
]
}),
transparent: PD.Boolean(false),
axes: CameraHelperParams.axes,
};
}
private _params: ReturnType<ViewportScreenshotHelper['createParams']> = void 0 as any;
get params() {
if (this._params) return this._params;
return this._params = this.createParams();
}
readonly behaviors = {
values: this.ev.behavior<ViewportScreenshotHelperParams>({
transparent: this.params.transparent.defaultValue,
axes: { name: 'off', params: {} },
resolution: this.params.resolution.defaultValue
}),
cropParams: this.ev.behavior<{ auto: boolean, relativePadding: number }>({ auto: true, relativePadding: 0.1 }),
relativeCrop: this.ev.behavior<Viewport>({ x: 0, y: 0, width: 1, height: 1 }),
};
readonly events = {
previewed: this.ev<any>()
};
get values() {
return this.behaviors.values.value;
}
get cropParams() {
return this.behaviors.cropParams.value;
}
get relativeCrop() {
return this.behaviors.relativeCrop.value;
}
private getCanvasSize() {
return {
width: this.plugin.canvas3d?.webgl.gl.drawingBufferWidth || 0,
height: this.plugin.canvas3d?.webgl.gl.drawingBufferHeight || 0
};
}
private getSize() {
const values = this.values;
switch (values.resolution.name) {
case 'viewport': return this.getCanvasSize();
case 'hd': return { width: 1280, height: 720 };
case 'full-hd': return { width: 1920, height: 1080 };
case 'ultra-hd': return { width: 3840, height: 2160 };
default: return { width: values.resolution.params.width, height: values.resolution.params.height };
}
}
private createPass(mutlisample: boolean) {
const c = this.plugin.canvas3d!;
const { colorBufferFloat, textureFloat } = c.webgl.extensions;
const aoProps = c.props.postprocessing.occlusion;
return c.getImagePass({
transparentBackground: this.values.transparent,
cameraHelper: { axes: this.values.axes },
multiSample: {
mode: mutlisample ? 'on' : 'off',
sampleLevel: colorBufferFloat && textureFloat ? 4 : 2
},
postprocessing: {
...c.props.postprocessing,
occlusion: aoProps.name === 'on'
? { name: 'on', params: { ...aoProps.params, samples: 128 } }
: aoProps
},
marking: { ...c.props.marking }
});
}
private _previewPass: ImagePass;
private get previewPass() {
return this._previewPass || (this._previewPass = this.createPass(false));
}
private _imagePass: ImagePass;
get imagePass() {
if (this._imagePass) {
const c = this.plugin.canvas3d!;
const aoProps = c.props.postprocessing.occlusion;
this._imagePass.setProps({
cameraHelper: { axes: this.values.axes },
transparentBackground: this.values.transparent,
// TODO: optimize because this creates a copy of a large object!
postprocessing: {
...c.props.postprocessing,
occlusion: aoProps.name === 'on'
? { name: 'on', params: { ...aoProps.params, samples: 128 } }
: aoProps
},
marking: { ...c.props.marking }
});
return this._imagePass;
}
return this._imagePass = this.createPass(true);
}
getFilename(extension = '.png') {
const models = this.plugin.state.data.select(StateSelection.Generators.rootsOfType(PluginStateObject.Molecule.Model)).map(s => s.obj!.data);
const uniqueIds = new Set<string>();
models.forEach(m => uniqueIds.add(m.entryId.toUpperCase()));
const idString = SetUtils.toArray(uniqueIds).join('-');
return `${idString || 'molstar-image'}${extension}`;
}
private canvas = function () {
const canvas = document.createElement('canvas');
return canvas;
}();
private previewCanvas = function () {
const canvas = document.createElement('canvas');
return canvas;
}();
private previewData = {
image: { data: new Uint8ClampedArray(1), width: 1, height: 0 } as ImageData,
background: Color(0),
transparent: false
};
resetCrop() {
this.behaviors.relativeCrop.next({ x: 0, y: 0, width: 1, height: 1 });
}
toggleAutocrop() {
if (this.cropParams.auto) {
this.behaviors.cropParams.next({ ...this.cropParams, auto: false });
this.resetCrop();
} else {
this.behaviors.cropParams.next({ ...this.cropParams, auto: true });
}
}
get isFullFrame() {
const crop = this.relativeCrop;
return equalEps(crop.x, 0, 1e-5) && equalEps(crop.y, 0, 1e-5) && equalEps(crop.width, 1, 1e-5) && equalEps(crop.height, 1, 1e-5);
}
autocrop(relativePadding = this.cropParams.relativePadding) {
const { data, width, height } = this.previewData.image;
const isTransparent = this.previewData.transparent;
const bgColor = isTransparent ? this.previewData.background : 0xff000000 | this.previewData.background;
let l = width, r = 0, t = height, b = 0;
for (let j = 0; j < height; j++) {
const jj = j * width;
for (let i = 0; i < width; i++) {
const o = 4 * (jj + i);
if (isTransparent) {
if (data[o + 3] === 0) continue;
} else {
const c = (data[o] << 16) | (data[o + 1] << 8) | (data[o + 2]) | (data[o + 3] << 24);
if (c === bgColor) continue;
}
if (i < l) l = i;
if (i > r) r = i;
if (j < t) t = j;
if (j > b) b = j;
}
}
if (l > r) {
const x = l;
l = r;
r = x;
}
if (t > b) {
const x = t;
t = b;
b = x;
}
const tw = r - l + 1, th = b - t + 1;
l -= relativePadding * tw;
r += relativePadding * tw;
t -= relativePadding * th;
b += relativePadding * th;
const crop: Viewport = {
x: Math.max(0, l / width),
y: Math.max(0, t / height),
width: Math.min(1, (r - l + 1) / width),
height: Math.min(1, (b - t + 1) / height)
};
this.behaviors.relativeCrop.next(crop);
}
getPreview(maxDim = 320) {
const { width, height } = this.getSize();
if (width <= 0 || height <= 0) return;
const f = width / height;
let w = 0, h = 0;
if (f > 1) {
w = maxDim;
h = Math.round(maxDim / f);
} else {
h = maxDim;
w = Math.round(maxDim * f);
}
const canvasProps = this.plugin.canvas3d!.props;
this.previewPass.setProps({
cameraHelper: { axes: this.values.axes },
transparentBackground: this.values.transparent,
// TODO: optimize because this creates a copy of a large object!
postprocessing: canvasProps.postprocessing,
marking: canvasProps.marking
});
const imageData = this.previewPass.getImageData(w, h);
const canvas = this.previewCanvas;
canvas.width = imageData.width;
canvas.height = imageData.height;
this.previewData.image = imageData;
this.previewData.background = canvasProps.renderer.backgroundColor;
this.previewData.transparent = this.values.transparent;
const canvasCtx = canvas.getContext('2d');
if (!canvasCtx) throw new Error('Could not create canvas 2d context');
canvasCtx.putImageData(imageData, 0, 0);
if (this.cropParams.auto) this.autocrop();
this.events.previewed.next(void 0);
return { canvas, width: w, height: h };
}
getSizeAndViewport() {
const { width, height } = this.getSize();
const crop = this.relativeCrop;
const viewport: Viewport = {
x: Math.floor(crop.x * width),
y: Math.floor(crop.y * height),
width: Math.ceil(crop.width * width),
height: Math.ceil(crop.height * height)
};
if (viewport.width + viewport.x > width) viewport.width = width - viewport.x;
if (viewport.height + viewport.y > height) viewport.height = height - viewport.y;
return { width, height, viewport };
}
private async draw(ctx: RuntimeContext) {
const { width, height, viewport } = this.getSizeAndViewport();
if (width <= 0 || height <= 0) return;
await ctx.update('Rendering image...');
const imageData = this.imagePass.getImageData(width, height, viewport);
await ctx.update('Encoding image...');
const canvas = this.canvas;
canvas.width = imageData.width;
canvas.height = imageData.height;
const canvasCtx = canvas.getContext('2d');
if (!canvasCtx) throw new Error('Could not create canvas 2d context');
canvasCtx.putImageData(imageData, 0, 0);
return;
}
private copyToClipboardTask() {
const cb = navigator.clipboard as any;
if (!cb?.write) {
this.plugin.log.error('clipboard.write not supported!');
return;
}
return Task.create('Copy Image', async ctx => {
await this.draw(ctx);
await ctx.update('Converting image...');
const blob = await canvasToBlob(this.canvas, 'png');
const item = new ClipboardItem({ 'image/png': blob });
await cb.write([item]);
this.plugin.log.message('Image copied to clipboard.');
});
}
getImageDataUri() {
return this.plugin.runTask(Task.create('Generate Image', async ctx => {
await this.draw(ctx);
await ctx.update('Converting image...');
return this.canvas.toDataURL('png');
}));
}
copyToClipboard() {
const task = this.copyToClipboardTask();
if (!task) return;
return this.plugin.runTask(task);
}
private downloadTask(filename?: string) {
return Task.create('Download Image', async ctx => {
await this.draw(ctx);
await ctx.update('Downloading image...');
const blob = await canvasToBlob(this.canvas, 'png');
download(blob, filename ?? this.getFilename());
});
}
download(filename?: string) {
this.plugin.runTask(this.downloadTask(filename));
}
constructor(private plugin: PluginContext) {
super();
}
}
declare const ClipboardItem: any; | the_stack |
import { inject, injectable } from 'inversify';
import * as apid from '../../../api';
import Rule from '../../db/entities/Rule';
import StrUtil from '../../util/StrUtil';
import IPromiseRetry from '../IPromiseRetry';
import DBUtil from './DBUtil';
import IDBOperator from './IDBOperator';
import IRuleDB, { RuleWithCnt } from './IRuleDB';
@injectable()
export default class RuleDB implements IRuleDB {
private op: IDBOperator;
private promieRetry: IPromiseRetry;
constructor(@inject('IDBOperator') op: IDBOperator, @inject('IPromiseRetry') promieRetry: IPromiseRetry) {
this.op = op;
this.promieRetry = promieRetry;
}
/**
* バックアップから復元
* @param items: RuleWithCnt[]
* @return Promise<void>
*/
public async restore(items: RuleWithCnt[]): Promise<void> {
// get queryRunner
const connection = await this.op.getConnection();
const queryRunner = connection.createQueryRunner();
// start transaction
await queryRunner.startTransaction();
let hasError = false;
try {
// 削除
await queryRunner.manager.delete(Rule, {});
// 挿入処理
for (const item of items) {
await queryRunner.manager.insert(Rule, this.convertRuleToDBRule(item));
}
await queryRunner.commitTransaction();
} catch (err) {
console.error(err);
hasError = err;
await queryRunner.rollbackTransaction();
} finally {
await queryRunner.release();
}
if (hasError) {
throw new Error('restore error');
}
}
/**
* ルールを1件挿入
* @param rule apid.Rule | apid.AddRuleOption
* @return inserted id
*/
public async insertOnce(rule: apid.Rule | apid.AddRuleOption): Promise<apid.RuleId> {
const connection = await this.op.getConnection();
const queryBuilder = connection.createQueryBuilder().insert().into(Rule).values(this.convertRuleToDBRule(rule));
const insertedResult = await this.promieRetry.run(() => {
return queryBuilder.execute();
});
return insertedResult.identifiers[0].id;
}
/**
* ルールをi件更新
* @param rule: apidRule
*/
public async updateOnce(newRule: apid.Rule): Promise<void> {
// updateCnt 更新のために古いルールを取り出す
const oldRule = <RuleWithCnt>await this.findId(newRule.id, true);
if (oldRule === null) {
throw new Error('RuleIsNull');
}
// updateCnt 更新
const convertedRule = this.convertRuleToDBRule(newRule);
convertedRule.updateCnt = oldRule.updateCnt + 1;
const connection = await this.op.getConnection();
const queryBuilder = connection
.createQueryBuilder()
.update(Rule)
.set(convertedRule)
.where('id = :id', { id: newRule.id });
await this.promieRetry.run(() => {
return queryBuilder.execute();
});
}
/**
* 指定したルールを1件有効化
* @param ruleId: apid.RuleId
*/
public async enableOnce(ruleId: apid.RuleId): Promise<void> {
const rule = <RuleWithCnt>await this.findId(ruleId, true);
if (rule === null) {
throw new Error('RuleIsNull');
}
// すでに有効か
if (rule.reserveOption.enable === true) {
return;
}
const connection = await this.op.getConnection();
const queryBuilder = connection
.createQueryBuilder()
.update(Rule)
.set({
enable: true,
updateCnt: rule.updateCnt + 1,
})
.where('id = :id', { id: ruleId });
await this.promieRetry.run(() => {
return queryBuilder.execute();
});
}
/**
* 指定したルールを1件無効化
* @param ruleId: apid.RuleId
*/
public async disableOnce(ruleId: apid.RuleId): Promise<void> {
const rule = <RuleWithCnt>await this.findId(ruleId, true);
if (rule === null) {
throw new Error('RuleIsNull');
}
// すでに無効か
if (rule.reserveOption.enable === false) {
return;
}
const connection = await this.op.getConnection();
const queryBuilder = connection
.createQueryBuilder()
.update(Rule)
.set({
enable: false,
updateCnt: rule.updateCnt + 1,
})
.where('id = :id', { id: ruleId });
await this.promieRetry.run(() => {
return queryBuilder.execute();
});
}
/**
* 指定したルールを1件削除
* @param ruleId: apid.RuleId
*/
public async deleteOnce(ruleId: apid.RuleId): Promise<void> {
const connection = await this.op.getConnection();
const queryBuilder = connection.createQueryBuilder().delete().from(Rule).where('id = :id', { id: ruleId });
await this.promieRetry.run(() => {
return queryBuilder.execute();
});
}
/**
* id を指定して取得
* @param ruleId rule id
* @param updateCnt を削除するか
* @return Promise<apidRule | RuleWithCnt | null>
*/
public async findId(ruleId: apid.RuleId, isNeedCnt: boolean = false): Promise<apid.Rule | RuleWithCnt | null> {
const connection = await this.op.getConnection();
const queryBuilder = connection.getRepository(Rule);
const result = await this.promieRetry.run(() => {
return queryBuilder.findOne({
where: { id: ruleId },
});
});
if (typeof result === 'undefined') {
return null;
} else if (isNeedCnt === true) {
return this.convertDBRuleToRule(result);
} else {
const rule = this.convertDBRuleToRule(result);
delete (rule as any).updateCnt;
return rule;
}
}
/**
* RuleWithCnt から Rule へ変換する
* @param rule: RuleWithCnt
* @return Rule
*/
private convertRuleToDBRule(rule: RuleWithCnt | apid.Rule | apid.AddRuleOption): Rule {
const convertedRule: Rule = <any>{
updateCnt: typeof rule === 'undefined' ? 0 : (<RuleWithCnt>rule).updateCnt,
isTimeSpecification: rule.isTimeSpecification,
keyword: typeof rule.searchOption.keyword === 'undefined' ? null : rule.searchOption.keyword,
halfWidthKeyword:
typeof rule.searchOption.keyword === 'undefined' ? null : StrUtil.toHalf(rule.searchOption.keyword),
ignoreKeyword:
typeof rule.searchOption.ignoreKeyword === 'undefined' ? null : rule.searchOption.ignoreKeyword,
halfWidthIgnoreKeyword:
typeof rule.searchOption.ignoreKeyword === 'undefined'
? null
: StrUtil.toHalf(rule.searchOption.ignoreKeyword),
keyCS: !!rule.searchOption.keyCS,
keyRegExp: !!rule.searchOption.keyRegExp,
name: !!rule.searchOption.name,
description: !!rule.searchOption.description,
extended: !!rule.searchOption.extended,
ignoreKeyCS: !!rule.searchOption.ignoreKeyCS,
ignoreKeyRegExp: !!rule.searchOption.ignoreKeyRegExp,
ignoreName: !!rule.searchOption.ignoreName,
ignoreDescription: !!rule.searchOption.ignoreDescription,
ignoreExtended: !!rule.searchOption.ignoreExtended,
GR: !!rule.searchOption.GR,
BS: !!rule.searchOption.BS,
CS: !!rule.searchOption.CS,
SKY: !!rule.searchOption.SKY,
channelIds:
typeof rule.searchOption.channelIds === 'undefined'
? null
: JSON.stringify(rule.searchOption.channelIds),
genres: typeof rule.searchOption.genres === 'undefined' ? null : JSON.stringify(rule.searchOption.genres),
times: typeof rule.searchOption.times === 'undefined' ? null : JSON.stringify(rule.searchOption.times),
isFree: !!rule.searchOption.isFree,
durationMin: typeof rule.searchOption.durationMin === 'undefined' ? null : rule.searchOption.durationMin,
durationMax: typeof rule.searchOption.durationMax === 'undefined' ? null : rule.searchOption.durationMax,
searchPeriods:
typeof rule.searchOption.searchPeriods === 'undefined'
? null
: JSON.stringify(rule.searchOption.searchPeriods),
enable: rule.reserveOption.enable,
avoidDuplicate: rule.reserveOption.avoidDuplicate,
periodToAvoidDuplicate:
typeof rule.reserveOption.periodToAvoidDuplicate === 'undefined'
? null
: rule.reserveOption.periodToAvoidDuplicate,
allowEndLack: rule.reserveOption.allowEndLack,
tags: typeof rule.reserveOption.tags === 'undefined' ? null : JSON.stringify(rule.reserveOption.tags),
parentDirectoryName: null,
directory: null,
recordedFormat: null,
mode1: null,
parentDirectoryName1: null,
directory1: null,
mode2: null,
parentDirectoryName2: null,
directory2: null,
mode3: null,
parentDirectoryName3: null,
directory3: null,
isDeleteOriginalAfterEncode: false,
};
if (typeof (<apid.Rule>rule).id !== 'undefined') {
convertedRule.id = (<apid.Rule>rule).id;
}
if (typeof rule.saveOption !== 'undefined') {
convertedRule.parentDirectoryName =
typeof rule.saveOption.parentDirectoryName === 'undefined' ? null : rule.saveOption.parentDirectoryName;
convertedRule.directory =
typeof rule.saveOption.directory === 'undefined' ? null : rule.saveOption.directory;
convertedRule.recordedFormat =
typeof rule.saveOption.recordedFormat === 'undefined' ? null : rule.saveOption.recordedFormat;
}
if (typeof rule.encodeOption !== 'undefined') {
convertedRule.mode1 = typeof rule.encodeOption.mode1 === 'undefined' ? null : rule.encodeOption.mode1;
convertedRule.parentDirectoryName1 =
typeof rule.encodeOption.encodeParentDirectoryName1 === 'undefined'
? null
: rule.encodeOption.encodeParentDirectoryName1;
convertedRule.directory1 =
typeof rule.encodeOption.directory1 === 'undefined' ? null : rule.encodeOption.directory1;
convertedRule.mode2 = typeof rule.encodeOption.mode2 === 'undefined' ? null : rule.encodeOption.mode2;
convertedRule.parentDirectoryName2 =
typeof rule.encodeOption.encodeParentDirectoryName2 === 'undefined'
? null
: rule.encodeOption.encodeParentDirectoryName2;
convertedRule.directory2 =
typeof rule.encodeOption.directory2 === 'undefined' ? null : rule.encodeOption.directory2;
convertedRule.mode3 = typeof rule.encodeOption.mode3 === 'undefined' ? null : rule.encodeOption.mode3;
convertedRule.parentDirectoryName3 =
typeof rule.encodeOption.encodeParentDirectoryName3 === 'undefined'
? null
: rule.encodeOption.encodeParentDirectoryName3;
convertedRule.directory3 =
typeof rule.encodeOption.directory3 === 'undefined' ? null : rule.encodeOption.directory3;
convertedRule.isDeleteOriginalAfterEncode = rule.encodeOption.isDeleteOriginalAfterEncode;
}
return convertedRule;
}
/**
* Rule から RuleWithCnt へ変換する
* @param rule: Rule
* @return RuleWithCnt
*/
private convertDBRuleToRule(rule: Rule): RuleWithCnt {
const convertedRule: RuleWithCnt = {
id: rule.id,
updateCnt: rule.updateCnt,
isTimeSpecification: rule.isTimeSpecification,
searchOption: {
keyCS: rule.keyCS,
keyRegExp: rule.keyRegExp,
name: rule.name,
description: rule.description,
extended: rule.extended,
ignoreKeyCS: rule.ignoreKeyCS,
ignoreKeyRegExp: rule.ignoreKeyRegExp,
ignoreName: rule.ignoreName,
ignoreDescription: rule.ignoreDescription,
ignoreExtended: rule.ignoreExtended,
GR: rule.GR,
BS: rule.BS,
CS: rule.CS,
SKY: rule.SKY,
isFree: rule.isFree,
},
reserveOption: {
enable: rule.enable,
allowEndLack: rule.allowEndLack,
avoidDuplicate: rule.avoidDuplicate,
},
};
/**
* 検索オプションセット
*/
if (rule.keyword !== null) {
convertedRule.searchOption.keyword = rule.keyword;
}
if (rule.ignoreKeyword !== null) {
convertedRule.searchOption.ignoreKeyword = rule.ignoreKeyword;
}
if (rule.channelIds !== null) {
convertedRule.searchOption.channelIds = JSON.parse(rule.channelIds);
}
if (rule.genres !== null) {
convertedRule.searchOption.genres = JSON.parse(rule.genres);
}
if (rule.times !== null) {
convertedRule.searchOption.times = JSON.parse(rule.times);
}
if (rule.durationMin !== null) {
convertedRule.searchOption.durationMin = rule.durationMin;
}
if (rule.durationMax !== null) {
convertedRule.searchOption.durationMax = rule.durationMax;
}
if (rule.searchPeriods !== null) {
convertedRule.searchOption.searchPeriods = JSON.parse(rule.searchPeriods);
}
/**
* 予約オプションセット
*/
if (rule.periodToAvoidDuplicate !== null) {
convertedRule.reserveOption.periodToAvoidDuplicate = rule.periodToAvoidDuplicate;
}
if (rule.tags !== null) {
convertedRule.reserveOption.tags = JSON.parse(rule.tags);
}
/**
* 保存オプション
*/
const saveOption: apid.ReserveSaveOption = {};
if (rule.parentDirectoryName !== null) {
saveOption.parentDirectoryName = rule.parentDirectoryName;
}
if (rule.directory !== null) {
saveOption.directory = rule.directory;
}
if (rule.recordedFormat !== null) {
saveOption.recordedFormat = rule.recordedFormat;
}
if (Object.keys(saveOption).length > 0) {
convertedRule.saveOption = saveOption;
}
/**
* エンコードオプション
*/
const encodeOption: apid.ReserveEncodedOption = <any>{};
if (rule.mode1 !== null) {
encodeOption.mode1 = rule.mode1;
}
if (rule.parentDirectoryName1 !== null) {
encodeOption.encodeParentDirectoryName1 = rule.parentDirectoryName1;
}
if (rule.directory1 !== null) {
encodeOption.directory1 = rule.directory1;
}
if (rule.mode2 !== null) {
encodeOption.mode2 = rule.mode2;
}
if (rule.parentDirectoryName2 !== null) {
encodeOption.encodeParentDirectoryName2 = rule.parentDirectoryName2;
}
if (rule.directory2 !== null) {
encodeOption.directory2 = rule.directory2;
}
if (rule.mode3 !== null) {
encodeOption.mode3 = rule.mode3;
}
if (rule.parentDirectoryName3 !== null) {
encodeOption.encodeParentDirectoryName3 = rule.parentDirectoryName3;
}
if (rule.directory3 !== null) {
encodeOption.directory3 = rule.directory3;
}
if (Object.keys(encodeOption).length > 0) {
encodeOption.isDeleteOriginalAfterEncode = rule.isDeleteOriginalAfterEncode;
convertedRule.encodeOption = encodeOption;
}
return convertedRule;
}
/**
* 全件取得
* @param option: apid.GetRuleOption
* @return Promise<[apid.Rule[], number]>
*/
public async findAll(option: apid.GetRuleOption, isNeedCnt: boolean = false): Promise<[apid.Rule[], number]> {
const connection = await this.op.getConnection();
let queryBuilder = connection.getRepository(Rule).createQueryBuilder('rule');
// keyword
if (typeof option.keyword !== 'undefined') {
const names = StrUtil.toHalf(option.keyword).split(/ /);
const like = this.op.getLikeStr(false);
const keywordAnd: string[] = [];
const values: any = {};
names.forEach((str, i) => {
str = `%${str}%`;
// value
const valueName = `keyword${i}`;
values[valueName] = str;
// keyword
keywordAnd.push(`halfWidthKeyword ${like} :${valueName}`);
});
const or: string[] = [];
if (keywordAnd.length > 0) {
or.push(`(${DBUtil.createAndQuery(keywordAnd)})`);
}
queryBuilder = queryBuilder.andWhere(DBUtil.createOrQuery(or), values);
}
// offset
if (typeof option.offset !== 'undefined') {
queryBuilder = queryBuilder.skip(option.offset);
}
// limit
if (typeof option.limit !== 'undefined') {
queryBuilder = queryBuilder.take(option.limit);
}
// order by
queryBuilder = queryBuilder.orderBy('rule.id', 'ASC');
const [rules, total] = await this.promieRetry.run(() => {
return queryBuilder.getManyAndCount();
});
return [
rules.map(rule => {
const result = this.convertDBRuleToRule(rule);
if (isNeedCnt === false) {
delete (result as any).updateCnt;
}
return result;
}),
total,
];
}
/**
* キーワード検索
* @param option: apid.GetRuleOption
* @return Promise<apid.RuleKeywordItem[]>
*/
public async findKeyword(option: apid.GetRuleOption): Promise<apid.RuleKeywordItem[]> {
const connection = await this.op.getConnection();
let queryBuilder = connection
.createQueryBuilder()
.select('rule.id, rule.keyword')
.from(Rule, 'rule')
.orderBy('rule.id', 'ASC');
// keyword
if (typeof option.keyword !== 'undefined') {
const names = StrUtil.toHalf(option.keyword).split(/ /);
const like = this.op.getLikeStr(false);
const keywordAnd: string[] = [];
const values: any = {};
names.forEach((str, i) => {
str = `%${str}%`;
// value
const valueName = `keyword${i}`;
values[valueName] = str;
// keyword
keywordAnd.push(`halfWidthKeyword ${like} :${valueName}`);
});
const or: string[] = [];
if (keywordAnd.length > 0) {
or.push(`(${DBUtil.createAndQuery(keywordAnd)})`);
}
queryBuilder = queryBuilder.andWhere(DBUtil.createOrQuery(or), values);
}
// offset
if (typeof option.offset !== 'undefined') {
queryBuilder = queryBuilder.skip(option.offset);
}
// limit
if (typeof option.limit !== 'undefined') {
queryBuilder = queryBuilder.take(option.limit);
}
const result = await this.promieRetry.run(() => {
return queryBuilder.getRawMany();
});
return result.map(r => {
return {
id: r.id,
keyword: r.keyword === null ? '' : r.keyword,
};
});
}
/**
* rule id を全て取得する
* @return Promise<apid.RuleId[]>
*/
public async getIds(): Promise<apid.RuleId[]> {
const connection = await this.op.getConnection();
const queryBuilder = connection
.createQueryBuilder()
.select('rule.id')
.from(Rule, 'rule')
.orderBy('rule.id', 'ASC');
const result = await this.promieRetry.run(() => {
return queryBuilder.getMany();
});
return result.map(r => {
return r.id;
});
}
} | the_stack |
import express from 'express'
import { LogInstance } from 'log/loginstance'
import { User } from 'entities/user'
import { UsersService } from 'services/usersservice'
import { WebSession, SessionRedirectError } from 'websession'
import { FORM_SECURITY_QUESTIONS } from 'securityquestions'
/**
* handles requests to /do_*
*/
export class ActionsController {
/**
* setup the controller's routes
* @param app the server's express instance
*/
public static setup(app: express.Express): void {
app.route('/do_signup').post(async (req, res) => {
await ActionsController.OnPostDoSignup(req, res)
})
app.route('/do_login').post(async (req, res) => {
await ActionsController.OnPostDoLogin(req, res)
})
app.route('/do_delete').post(async (req, res) => {
await ActionsController.OnPostDoDelete(req, res)
})
app.route('/do_recover_pw').post(async (req, res) => {
await ActionsController.OnPostDoRecoverPw(req, res)
})
app.route('/do_recover_pw2').post(async (req, res) => {
await ActionsController.OnPostDoRecoverPwUpdate(req, res)
})
}
/**
* called when a POST request to /do_signup is done
* creates a new user account
* @param req the request data
* @param res the response data
*/
private static async OnPostDoSignup(
req: express.Request,
res: express.Response
): Promise<void> {
if (req.session.userId != null) {
return res.redirect('/user')
}
type signupBody = {
username?: string
playername?: string
password?: string
confirmed_password?: string
security_question?: string
security_answer?: string
coolfield?: string // anti bot field
}
const typedBody = req.body as signupBody
const userName = typedBody.username
const playerName = typedBody.playername
const password = typedBody.password
const confirmedPassword = typedBody.confirmed_password
const securityQuestion = Number(typedBody.security_question)
const securityAnswer = typedBody.security_answer
const antiBotField = typedBody.coolfield
if (
userName == null ||
playerName == null ||
password == null ||
confirmedPassword == null ||
isNaN(securityQuestion) === true ||
securityAnswer == null ||
antiBotField.length !== 0
) {
return SessionRedirectError(
'A bad request was made.',
'/signup',
req,
res
)
}
if (password !== confirmedPassword) {
return SessionRedirectError(
'The passwords do not match.',
'/signup',
req,
res
)
}
if (
securityQuestion < 0 ||
securityQuestion >= FORM_SECURITY_QUESTIONS.length
) {
return SessionRedirectError(
'An invalid security question was picked.',
'/signup',
req,
res
)
}
try {
const newUser: User = await UsersService.create(
userName,
playerName,
password,
securityQuestion,
securityAnswer
)
if (newUser == null) {
SessionRedirectError(
'Invalid new user credentials',
'/signup',
req,
res
)
return
}
const results: boolean[] = await Promise.all([
UsersService.createInventory(newUser.id),
UsersService.createCosmetics(newUser.id),
UsersService.createLoadouts(newUser.id),
UsersService.createBuymenu(newUser.id)
])
for (const r of results) {
if (r === false) {
SessionRedirectError(
'Internal error: could not create inventory for user',
'/signup',
req,
res
)
return
}
}
req.session.userId = newUser.id
req.session.userName = newUser.playername
req.session.save((err) => {
if (err) {
throw err
}
})
return res.redirect('/user')
} catch (error) {
if (error) {
const typedError = error as { toString: () => string }
const errorMessage: string = typedError.toString()
LogInstance.error(errorMessage)
SessionRedirectError(errorMessage, '/signup', req, res)
}
}
}
/**
* called when a POST request to /do_login is done
* logs in to an user's account
* @param req the request data
* @param res the response data
*/
private static async OnPostDoLogin(
req: express.Request,
res: express.Response
): Promise<void> {
if (req.session.userId != null) {
return res.redirect('/user')
}
type loginBody = {
username?: string
password?: string
coolfield?: string // anti bot field
}
const typedBody = req.body as loginBody
const username: string = typedBody.username
const password: string = typedBody.password
const antiBotField: string = typedBody.coolfield
if (username == null || password == null || antiBotField.length !== 0) {
return SessionRedirectError('A bad request was made.', '/login', req, res)
}
try {
const authedUserId: number = await UsersService.validate(
username,
password
)
if (authedUserId) {
const loggedUser = await UsersService.get(authedUserId)
if (loggedUser == null) {
throw new Error('Failed to get valid user data')
}
req.session.userId = authedUserId
req.session.userName = loggedUser.playername
req.session.save((err) => {
if (err) {
throw err
}
})
return res.redirect('/user')
}
SessionRedirectError('Bad credentials', '/login', req, res)
} catch (error) {
if (error) {
let errorMessage: string = null
const typedError = error as {
status: number
toString: () => string
}
if (typedError.status === 404) {
errorMessage = 'User was not found'
} else {
errorMessage = typedError.toString()
}
LogInstance.error(errorMessage)
SessionRedirectError(errorMessage, '/login', req, res)
}
}
}
/**
* called when a POST request to /do_delete is done
* delete's an user's account
* @param req the request data
* @param res the response data
*/
private static async OnPostDoDelete(
req: express.Request,
res: express.Response
): Promise<void> {
const session = req.session as WebSession
const typedBody = req.body as { confirmation: string }
const targetUserId: number = session.userId
if (targetUserId == null) {
return res.redirect('/login')
}
const confirmation: string = typedBody.confirmation
if (confirmation !== 'on') {
return SessionRedirectError(
'The user did not tick the confirmation box',
'/user/delete',
req,
res
)
}
try {
const deleted: boolean = await UsersService.delete(targetUserId)
if (deleted) {
req.session.userId = null
req.session.status = 'Account deleted successfully.'
req.session.save((err) => {
if (err) {
throw err
}
})
return res.redirect('/login')
}
SessionRedirectError('Failed to delete account.', '/user', req, res)
} catch (error) {
if (error) {
const typedError = error as { toString: () => string }
const errorMessage: string = typedError.toString()
LogInstance.error(errorMessage)
SessionRedirectError(errorMessage, '/signup', req, res)
}
}
}
/**
* called when a POST request to /do_recover_pw is done
* checks for an user's security question
* @param req the request data
* @param res the response data
*/
private static async OnPostDoRecoverPw(
req: express.Request,
res: express.Response
): Promise<void> {
const session = req.session as WebSession
const body = req.body as {
username: string
}
if (session.userId != null) {
return res.redirect('/')
}
const username = body.username
if (username == null) {
return SessionRedirectError(
'Please fill in all the required fields',
'/recover_pw',
req,
res
)
}
try {
const user = await UsersService.getByName(username)
if (user == null) {
return SessionRedirectError(
'The user does not exist.',
'/recover_pw',
req,
res
)
}
req.session.security_username = username
req.session.security_question =
FORM_SECURITY_QUESTIONS[user.security_question_index]
req.session.save((err) => {
if (err) {
throw err
}
})
return res.redirect('/recover_pw')
} catch (error) {
if (error) {
const typedError = error as { toString: () => string }
const errorMessage: string = typedError.toString()
LogInstance.error(errorMessage)
SessionRedirectError(errorMessage, '/recover_pw', req, res)
}
}
}
/**
* called when a POST request to /do_recover_pw2 is done
* update's an user's password
* @param req the request data
* @param res the response data
*/
private static async OnPostDoRecoverPwUpdate(
req: express.Request,
res: express.Response
): Promise<void> {
const session = req.session as WebSession
const body = req.body as {
username: string
security_answer: string
password: string
confirmed_password: string
}
if (session.userId != null) {
return res.redirect('/')
}
const username = body.username
const securityAnswer = body.security_answer
const password = body.password
const confirmedPassword = body.confirmed_password
if (
username == null ||
securityAnswer == null ||
password == null ||
confirmedPassword == null
) {
return SessionRedirectError(
'Please fill in all the required fields',
'/recover_pw',
req,
res
)
}
if (password !== confirmedPassword) {
return SessionRedirectError(
'The passwords do not match.',
'/recover_pw',
req,
res
)
}
try {
const targetUserId = await UsersService.validateSecurityAnswer(
username,
securityAnswer
)
if (targetUserId == null) {
return SessionRedirectError(
'The user name or the security answer are incorrect.',
'/recover_pw',
req,
res
)
}
const updated = await UsersService.updatePassword(targetUserId, password)
if (updated === false) {
return SessionRedirectError(
'Failed to update the password.',
'/recover_pw',
req,
res
)
}
req.session.status = 'Password updated successfully.'
req.session.save((err) => {
if (err) {
throw err
}
})
return res.redirect('/login')
} catch (error) {
if (error) {
const typedError = error as { toString: () => string }
const errorMessage: string = typedError.toString()
LogInstance.error(errorMessage)
SessionRedirectError(errorMessage, '/recover_pw', req, res)
}
}
}
} | the_stack |
import {$A, $S, IterationState, Operation} from '../types';
import {createOperation} from '../utils';
/**
* Value index details, during [[split]] operation.
*/
export interface ISplitIndex {
/**
* Start Index - absolute value index, from the start of the iterable.
*/
start: number;
/**
* List Index - relative to the current list.
* Index of the value within the currently accumulated list.
*
* Note that when `split` or `toggle-OFF` values are carried forward,
* it starts with 1, as 0 refers to the value that was carried forward.
*/
list: number;
/**
* Split Index - of resulting emits by the operator, starts with 0,
* and incremented every time the operator emits data.
*/
split: number;
}
/**
* Set of options that can be passed into [[split]] operator.
*/
export interface ISplitOptions {
/**
* Strategy for carrying every `toggle-ON` value.
* It is used only when in `toggle` mode.
*/
carryStart?: SplitValueCarry;
/**
* Strategy for carrying every `toggle-OFF` or `split` value.
*/
carryEnd?: SplitValueCarry;
/**
* Changes what the `split` callback result represents.
* By default, it signals when we find a split value.
*
* This option changes that into a `toggle` logic:
*
* We start collecting values into a new list when the callback returns true
* one time, and we stop collecting values when it returns true the next time.
* And we do so repeatedly, skipping values outside `[true, ..., true]` toggles.
*/
toggle?: boolean;
}
/**
* Strategy for carrying over split/toggle values.
* It defines what to do with each value that triggers the split/toggle.
*
* Note that [[split]] operator treats this enum in non-strict manner:
* - any negative number is treated as `back`
* - any positive number is treated as `forward`
* - everything else is treated as `none`
*/
export enum SplitValueCarry {
/**
* Split/toggle value is carried back, to be the last value in the current list.
*/
back = -1,
/**
* Split/toggle value is just a placeholder/gap, to be skipped.
* This is the default.
*/
none = 0,
/**
* Split/toggle value is carried forward, to make the first value in the next list.
*/
forward = 1,
}
/**
* Splits values into separate lists when predicate returns `true` (or resolves with `true`).
* When option `toggle` is set, the split uses the toggle start/end logic.
*
* Note that the predicate can only return a `Promise` inside an asynchronous pipeline,
* or else the `Promise` will be treated as a truthy value.
*
* When you know only the split value of each block, you can use the default split mode,
* with `carryEnd` set to `1/forward` (in case you do not want it skipped);
*
* When you know only the end value of each block, you can use the default split mode,
* with `carryEnd` set to `-1/back` (in case you do not want it skipped);
*
* When you know both start and end values of each block, you can use the `toggle` mode,
* with `carryStart` set to `1/forward`, and `carryEnd` set to `-1/back`, unless you want
* either of those skipped, then leave them at `0/none`.
*
* Note that in `toggle` mode, you cannot use `carryStart=back` (it will be ignored),
* because it would delay emission of the current block indefinitely, plus carrying
* block start backward doesn't make much sense anyway.
*
* @see [[https://github.com/vitaly-t/iter-ops/wiki/Split Split WiKi]], [[page]]
* @category Sync+Async
*/
export function split<T>(
cb: (
value: T,
index: ISplitIndex,
state: IterationState
) => boolean | Promise<boolean>,
options?: ISplitOptions
): Operation<T, T[]>;
export function split(...args: unknown[]) {
return createOperation(splitSync, splitAsync, args);
}
function splitSync<T>(
iterable: Iterable<T>,
cb: (value: T, index: ISplitIndex, state: IterationState) => boolean,
options?: ISplitOptions
): Iterable<T[]> {
return {
[$S](): Iterator<T[]> {
const i = iterable[$S]();
const state: IterationState = {};
// quick access to the options:
const carryStart = options?.carryStart
? options?.carryStart < 0
? -1
: options?.carryStart > 0
? 1
: 0
: 0;
const carryEnd = options?.carryEnd
? options?.carryEnd < 0
? -1
: options?.carryEnd > 0
? 1
: 0
: 0;
const toggle = !!options?.toggle;
// all indexes:
let startIndex = 0;
let listIndex = 0;
let splitIndex = 0;
let collecting = !toggle; // indicates when we are collecting values
let finished = false; // indicates when we are all done
let prev: IteratorResult<T> | null; // previous value when carrying forward
return {
next(): IteratorResult<T[]> {
const list: T[] = [];
let v: IteratorResult<T>; // next value object
do {
if (prev) {
// previous trigger value is being moved forward;
list.push(prev.value);
prev = null;
}
v = i.next();
if (!v.done) {
const index: ISplitIndex = {
start: startIndex++,
list: listIndex,
split: splitIndex,
};
if (cb(v.value, index, state)) {
// split/toggle has been triggered;
const carry = collecting
? carryEnd
: carryStart;
if (carry) {
if (carry < 0) {
list.push(v.value);
} else {
prev = v; // carry "forward", save for the next list
}
}
if (toggle) {
collecting = !collecting;
listIndex = collecting && carry > 0 ? 1 : 0;
if (collecting) {
splitIndex++;
continue;
}
return {value: list, done: false};
}
listIndex = carry > 0 ? 1 : 0;
splitIndex++;
break;
}
if (collecting) {
listIndex++;
list.push(v.value);
}
}
} while (!v.done);
if (!finished) {
finished = !!v.done;
if (collecting) {
return {value: list, done: false};
}
}
return {value: undefined, done: true};
},
};
},
};
}
function splitAsync<T>(
iterable: AsyncIterable<T>,
cb: (
value: T,
index: ISplitIndex,
state: IterationState
) => boolean | Promise<boolean>,
options?: ISplitOptions
): AsyncIterable<T[]> {
return {
[$A](): AsyncIterator<T[]> {
const i = iterable[$A]();
const state: IterationState = {};
// quick access to the options:
const carryStart = options?.carryStart
? options?.carryStart < 0
? -1
: options?.carryStart > 0
? 1
: 0
: 0;
const carryEnd = options?.carryEnd
? options?.carryEnd < 0
? -1
: options?.carryEnd > 0
? 1
: 0
: 0;
const toggle = !!options?.toggle;
// all indexes:
let startIndex = 0;
let listIndex = 0;
let splitIndex = 0;
let collecting = !toggle; // indicates when we are collecting values
let finished = false; // indicates when we are all done
let prev: IteratorResult<T> | null; // previous value when carrying forward
return {
async next(): Promise<IteratorResult<T[]>> {
const list: T[] = [];
let v: IteratorResult<T>; // next value object
do {
if (prev) {
// previous trigger value is being moved forward;
list.push(prev.value);
prev = null;
}
v = await i.next();
if (!v.done) {
const index: ISplitIndex = {
start: startIndex++,
list: listIndex,
split: splitIndex,
};
if (await cb(v.value, index, state)) {
// split/toggle has been triggered;
const carry = collecting
? carryEnd
: carryStart;
if (carry) {
if (carry < 0) {
list.push(v.value);
} else {
prev = v; // carry "forward", save for the next list
}
}
if (toggle) {
collecting = !collecting;
listIndex = collecting && carry > 0 ? 1 : 0;
if (collecting) {
splitIndex++;
continue;
}
return {value: list, done: false};
}
listIndex = carry > 0 ? 1 : 0;
splitIndex++;
break;
}
if (collecting) {
listIndex++;
list.push(v.value);
}
}
} while (!v.done);
if (!finished) {
finished = !!v.done;
if (collecting) {
return {value: list, done: false};
}
}
return {value: undefined, done: true};
},
};
},
};
} | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import _ from 'lodash';
import { opensearchClientMock } from '../../../opensearch/client/mocks';
import * as Index from './opensearch_index';
describe('ElasticIndex', () => {
let client: ReturnType<typeof opensearchClientMock.createOpenSearchClient>;
beforeEach(() => {
client = opensearchClientMock.createOpenSearchClient();
});
describe('fetchInfo', () => {
test('it handles 404', async () => {
client.indices.get.mockResolvedValue(
opensearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 })
);
const info = await Index.fetchInfo(client, '.opensearch_dashboards_test');
expect(info).toEqual({
aliases: {},
exists: false,
indexName: '.opensearch_dashboards_test',
mappings: { dynamic: 'strict', properties: {} },
});
expect(client.indices.get).toHaveBeenCalledWith(
{ index: '.opensearch_dashboards_test' },
{ ignore: [404] }
);
});
test('fails if the index doc type is unsupported', async () => {
client.indices.get.mockImplementation((params) => {
const index = params!.index as string;
return opensearchClientMock.createSuccessTransportRequestPromise({
[index]: {
aliases: { foo: index },
mappings: { spock: { dynamic: 'strict', properties: { a: 'b' } } },
},
});
});
await expect(Index.fetchInfo(client, '.baz')).rejects.toThrow(
/cannot be automatically migrated/
);
});
test('fails if there are multiple root types', async () => {
client.indices.get.mockImplementation((params) => {
const index = params!.index as string;
return opensearchClientMock.createSuccessTransportRequestPromise({
[index]: {
aliases: { foo: index },
mappings: {
doc: { dynamic: 'strict', properties: { a: 'b' } },
doctor: { dynamic: 'strict', properties: { a: 'b' } },
},
},
});
});
await expect(Index.fetchInfo(client, '.baz')).rejects.toThrow(
/cannot be automatically migrated/
);
});
test('decorates index info with exists and indexName', async () => {
client.indices.get.mockImplementation((params) => {
const index = params!.index as string;
return opensearchClientMock.createSuccessTransportRequestPromise({
[index]: {
aliases: { foo: index },
mappings: { dynamic: 'strict', properties: { a: 'b' } },
},
});
});
const info = await Index.fetchInfo(client, '.baz');
expect(info).toEqual({
aliases: { foo: '.baz' },
mappings: { dynamic: 'strict', properties: { a: 'b' } },
exists: true,
indexName: '.baz',
});
});
});
describe('createIndex', () => {
test('calls indices.create', async () => {
await Index.createIndex(client, '.abcd', { foo: 'bar' } as any);
expect(client.indices.create).toHaveBeenCalledTimes(1);
expect(client.indices.create).toHaveBeenCalledWith({
body: {
mappings: { foo: 'bar' },
settings: {
auto_expand_replicas: '0-1',
number_of_shards: 1,
},
},
index: '.abcd',
});
});
});
describe('deleteIndex', () => {
test('calls indices.delete', async () => {
await Index.deleteIndex(client, '.lotr');
expect(client.indices.delete).toHaveBeenCalledTimes(1);
expect(client.indices.delete).toHaveBeenCalledWith({
index: '.lotr',
});
});
});
describe('claimAlias', () => {
test('handles unaliased indices', async () => {
client.indices.getAlias.mockResolvedValue(
opensearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 })
);
await Index.claimAlias(client, '.hola-42', '.hola');
expect(client.indices.getAlias).toHaveBeenCalledWith(
{
name: '.hola',
},
{ ignore: [404] }
);
expect(client.indices.updateAliases).toHaveBeenCalledWith({
body: {
actions: [{ add: { index: '.hola-42', alias: '.hola' } }],
},
});
expect(client.indices.refresh).toHaveBeenCalledWith({
index: '.hola-42',
});
});
test('removes existing alias', async () => {
client.indices.getAlias.mockResolvedValue(
opensearchClientMock.createSuccessTransportRequestPromise({
'.my-fanci-index': '.muchacha',
})
);
await Index.claimAlias(client, '.ze-index', '.muchacha');
expect(client.indices.getAlias).toHaveBeenCalledTimes(1);
expect(client.indices.updateAliases).toHaveBeenCalledWith({
body: {
actions: [
{ remove: { index: '.my-fanci-index', alias: '.muchacha' } },
{ add: { index: '.ze-index', alias: '.muchacha' } },
],
},
});
expect(client.indices.refresh).toHaveBeenCalledWith({
index: '.ze-index',
});
});
test('allows custom alias actions', async () => {
client.indices.getAlias.mockResolvedValue(
opensearchClientMock.createSuccessTransportRequestPromise({
'.my-fanci-index': '.muchacha',
})
);
await Index.claimAlias(client, '.ze-index', '.muchacha', [
{ remove_index: { index: 'awww-snap!' } },
]);
expect(client.indices.getAlias).toHaveBeenCalledTimes(1);
expect(client.indices.updateAliases).toHaveBeenCalledWith({
body: {
actions: [
{ remove_index: { index: 'awww-snap!' } },
{ remove: { index: '.my-fanci-index', alias: '.muchacha' } },
{ add: { index: '.ze-index', alias: '.muchacha' } },
],
},
});
expect(client.indices.refresh).toHaveBeenCalledWith({
index: '.ze-index',
});
});
});
describe('convertToAlias', () => {
test('it creates the destination index, then reindexes to it', async () => {
client.indices.getAlias.mockResolvedValue(
opensearchClientMock.createSuccessTransportRequestPromise({
'.my-fanci-index': '.muchacha',
})
);
client.reindex.mockResolvedValue(
opensearchClientMock.createSuccessTransportRequestPromise({ task: 'abc' })
);
client.tasks.get.mockResolvedValue(
opensearchClientMock.createSuccessTransportRequestPromise({ completed: true })
);
const info = {
aliases: {},
exists: true,
indexName: '.ze-index',
mappings: {
dynamic: 'strict',
properties: { foo: { type: 'keyword' } },
},
};
await Index.convertToAlias(
client,
info,
'.muchacha',
10,
`ctx._id = ctx._source.type + ':' + ctx._id`
);
expect(client.indices.create).toHaveBeenCalledWith({
body: {
mappings: {
dynamic: 'strict',
properties: { foo: { type: 'keyword' } },
},
settings: { auto_expand_replicas: '0-1', number_of_shards: 1 },
},
index: '.ze-index',
});
expect(client.reindex).toHaveBeenCalledWith({
body: {
dest: { index: '.ze-index' },
source: { index: '.muchacha', size: 10 },
script: {
source: `ctx._id = ctx._source.type + ':' + ctx._id`,
lang: 'painless',
},
},
refresh: true,
wait_for_completion: false,
});
expect(client.tasks.get).toHaveBeenCalledWith({
task_id: 'abc',
});
expect(client.indices.updateAliases).toHaveBeenCalledWith({
body: {
actions: [
{ remove_index: { index: '.muchacha' } },
{ remove: { alias: '.muchacha', index: '.my-fanci-index' } },
{ add: { index: '.ze-index', alias: '.muchacha' } },
],
},
});
expect(client.indices.refresh).toHaveBeenCalledWith({
index: '.ze-index',
});
});
test('throws error if re-index task fails', async () => {
client.indices.getAlias.mockResolvedValue(
opensearchClientMock.createSuccessTransportRequestPromise({
'.my-fanci-index': '.muchacha',
})
);
client.reindex.mockResolvedValue(
opensearchClientMock.createSuccessTransportRequestPromise({ task: 'abc' })
);
client.tasks.get.mockResolvedValue(
opensearchClientMock.createSuccessTransportRequestPromise({
completed: true,
error: {
type: 'search_phase_execution_exception',
reason: 'all shards failed',
failed_shards: [],
},
})
);
const info = {
aliases: {},
exists: true,
indexName: '.ze-index',
mappings: {
dynamic: 'strict',
properties: { foo: { type: 'keyword' } },
},
};
await expect(Index.convertToAlias(client, info, '.muchacha', 10)).rejects.toThrow(
/Re-index failed \[search_phase_execution_exception\] all shards failed/
);
expect(client.indices.create).toHaveBeenCalledWith({
body: {
mappings: {
dynamic: 'strict',
properties: { foo: { type: 'keyword' } },
},
settings: { auto_expand_replicas: '0-1', number_of_shards: 1 },
},
index: '.ze-index',
});
expect(client.reindex).toHaveBeenCalledWith({
body: {
dest: { index: '.ze-index' },
source: { index: '.muchacha', size: 10 },
},
refresh: true,
wait_for_completion: false,
});
expect(client.tasks.get).toHaveBeenCalledWith({
task_id: 'abc',
});
});
});
describe('write', () => {
test('writes documents in bulk to the index', async () => {
client.bulk.mockResolvedValue(
opensearchClientMock.createSuccessTransportRequestPromise({ items: [] })
);
const index = '.myalias';
const docs = [
{
_id: 'niceguy:fredrogers',
_source: {
type: 'niceguy',
niceguy: {
aka: 'Mr Rogers',
},
quotes: ['The greatest gift you ever give is your honest self.'],
},
},
{
_id: 'badguy:rickygervais',
_source: {
type: 'badguy',
badguy: {
aka: 'Dominic Badguy',
},
migrationVersion: { badguy: '2.3.4' },
},
},
];
await Index.write(client, index, docs);
expect(client.bulk).toHaveBeenCalled();
expect(client.bulk.mock.calls[0]).toMatchSnapshot();
});
test('fails if any document fails', async () => {
client.bulk.mockResolvedValue(
opensearchClientMock.createSuccessTransportRequestPromise({
items: [{ index: { error: { type: 'shazm', reason: 'dern' } } }],
})
);
const index = '.myalias';
const docs = [
{
_id: 'niceguy:fredrogers',
_source: {
type: 'niceguy',
niceguy: {
aka: 'Mr Rogers',
},
},
},
];
await expect(Index.write(client as any, index, docs)).rejects.toThrow(/dern/);
expect(client.bulk).toHaveBeenCalledTimes(1);
});
});
describe('reader', () => {
test('returns docs in batches', async () => {
const index = '.myalias';
const batch1 = [
{
_id: 'such:1',
_source: { type: 'such', such: { num: 1 } },
},
];
const batch2 = [
{
_id: 'aaa:2',
_source: { type: 'aaa', aaa: { num: 2 } },
},
{
_id: 'bbb:3',
_source: {
bbb: { num: 3 },
migrationVersion: { bbb: '3.2.5' },
type: 'bbb',
},
},
];
client.search = jest.fn().mockReturnValue(
opensearchClientMock.createSuccessTransportRequestPromise({
_scroll_id: 'x',
_shards: { success: 1, total: 1 },
hits: { hits: _.cloneDeep(batch1) },
})
);
client.scroll = jest
.fn()
.mockReturnValueOnce(
opensearchClientMock.createSuccessTransportRequestPromise({
_scroll_id: 'y',
_shards: { success: 1, total: 1 },
hits: { hits: _.cloneDeep(batch2) },
})
)
.mockReturnValueOnce(
opensearchClientMock.createSuccessTransportRequestPromise({
_scroll_id: 'z',
_shards: { success: 1, total: 1 },
hits: { hits: [] },
})
);
const read = Index.reader(client, index, { batchSize: 100, scrollDuration: '5m' });
expect(await read()).toEqual(batch1);
expect(await read()).toEqual(batch2);
expect(await read()).toEqual([]);
expect(client.search).toHaveBeenCalledWith({
body: { size: 100 },
index,
scroll: '5m',
});
expect(client.scroll).toHaveBeenCalledWith({
scroll: '5m',
scroll_id: 'x',
});
expect(client.scroll).toHaveBeenCalledWith({
scroll: '5m',
scroll_id: 'y',
});
expect(client.clearScroll).toHaveBeenCalledWith({
scroll_id: 'z',
});
});
test('returns all root-level properties', async () => {
const index = '.myalias';
const batch = [
{
_id: 'such:1',
_source: {
acls: '3230a',
foos: { is: 'fun' },
such: { num: 1 },
type: 'such',
},
},
];
client.search = jest.fn().mockReturnValueOnce(
opensearchClientMock.createSuccessTransportRequestPromise({
_scroll_id: 'x',
_shards: { success: 1, total: 1 },
hits: { hits: _.cloneDeep(batch) },
})
);
client.scroll = jest.fn().mockReturnValueOnce(
opensearchClientMock.createSuccessTransportRequestPromise({
_scroll_id: 'z',
_shards: { success: 1, total: 1 },
hits: { hits: [] },
})
);
const read = Index.reader(client, index, {
batchSize: 100,
scrollDuration: '5m',
});
expect(await read()).toEqual(batch);
});
test('fails if not all shards were successful', async () => {
const index = '.myalias';
client.search = jest.fn().mockReturnValueOnce(
opensearchClientMock.createSuccessTransportRequestPromise({
_shards: { successful: 1, total: 2 },
})
);
const read = Index.reader(client, index, {
batchSize: 100,
scrollDuration: '5m',
});
await expect(read()).rejects.toThrow(/shards failed/);
});
test('handles shards not being returned', async () => {
const index = '.myalias';
const batch = [
{
_id: 'such:1',
_source: {
acls: '3230a',
foos: { is: 'fun' },
such: { num: 1 },
type: 'such',
},
},
];
client.search = jest.fn().mockReturnValueOnce(
opensearchClientMock.createSuccessTransportRequestPromise({
_scroll_id: 'x',
hits: { hits: _.cloneDeep(batch) },
})
);
client.scroll = jest.fn().mockReturnValueOnce(
opensearchClientMock.createSuccessTransportRequestPromise({
_scroll_id: 'z',
hits: { hits: [] },
})
);
const read = Index.reader(client, index, {
batchSize: 100,
scrollDuration: '5m',
});
expect(await read()).toEqual(batch);
});
});
describe('migrationsUpToDate', () => {
// A helper to reduce boilerplate in the hasMigration tests that follow.
async function testMigrationsUpToDate({
index = '.myindex',
mappings,
count,
migrations,
}: any) {
client.indices.get = jest.fn().mockReturnValueOnce(
opensearchClientMock.createSuccessTransportRequestPromise({
[index]: { mappings },
})
);
client.count = jest.fn().mockReturnValueOnce(
opensearchClientMock.createSuccessTransportRequestPromise({
count,
_shards: { success: 1, total: 1 },
})
);
const hasMigrations = await Index.migrationsUpToDate(client, index, migrations);
return { hasMigrations };
}
test('is false if the index mappings do not contain migrationVersion', async () => {
const { hasMigrations } = await testMigrationsUpToDate({
index: '.myalias',
mappings: {
properties: {
dashboard: { type: 'text' },
},
},
count: 0,
migrations: { dashy: '2.3.4' },
});
expect(hasMigrations).toBeFalsy();
expect(client.indices.get).toHaveBeenCalledWith(
{
index: '.myalias',
},
{
ignore: [404],
}
);
});
test('is true if there are no migrations defined', async () => {
const { hasMigrations } = await testMigrationsUpToDate({
index: '.myalias',
mappings: {
properties: {
migrationVersion: {
dynamic: 'true',
type: 'object',
},
dashboard: { type: 'text' },
},
},
count: 2,
migrations: {},
});
expect(hasMigrations).toBeTruthy();
expect(client.indices.get).toHaveBeenCalledTimes(1);
});
test('is true if there are no documents out of date', async () => {
const { hasMigrations } = await testMigrationsUpToDate({
index: '.myalias',
mappings: {
properties: {
migrationVersion: {
dynamic: 'true',
type: 'object',
},
dashboard: { type: 'text' },
},
},
count: 0,
migrations: { dashy: '23.2.5' },
});
expect(hasMigrations).toBeTruthy();
expect(client.indices.get).toHaveBeenCalledTimes(1);
expect(client.count).toHaveBeenCalledTimes(1);
});
test('is false if there are documents out of date', async () => {
const { hasMigrations } = await testMigrationsUpToDate({
index: '.myalias',
mappings: {
properties: {
migrationVersion: {
dynamic: 'true',
type: 'object',
},
dashboard: { type: 'text' },
},
},
count: 3,
migrations: { dashy: '23.2.5' },
});
expect(hasMigrations).toBeFalsy();
expect(client.indices.get).toHaveBeenCalledTimes(1);
expect(client.count).toHaveBeenCalledTimes(1);
});
test('counts docs that are out of date', async () => {
await testMigrationsUpToDate({
index: '.myalias',
mappings: {
properties: {
migrationVersion: {
dynamic: 'true',
type: 'object',
},
dashboard: { type: 'text' },
},
},
count: 0,
migrations: {
dashy: '23.2.5',
bashy: '99.9.3',
flashy: '3.4.5',
},
});
function shouldClause(type: string, version: string) {
return {
bool: {
must: [
{ exists: { field: type } },
{
bool: {
must_not: { term: { [`migrationVersion.${type}`]: version } },
},
},
],
},
};
}
expect(client.count).toHaveBeenCalledWith({
body: {
query: {
bool: {
should: [
shouldClause('dashy', '23.2.5'),
shouldClause('bashy', '99.9.3'),
shouldClause('flashy', '3.4.5'),
],
},
},
},
index: '.myalias',
});
});
});
}); | the_stack |
* This is an autogenerated file created by the Stencil compiler.
* It contains typing information for all components that exist in this project.
*/
import { HTMLStencilElement, JSXBase } from "@stencil/core/internal";
import { ApiError, LoginResponse, Routes } from "@identifo/identifo-auth-js";
export namespace Components {
interface IdentifoForm {
"appId": string;
"callbackUrl": string;
"debug": boolean;
"federatedRedirectUrl": string;
"postLogoutRedirectUri": string;
"route": Routes;
"theme": 'dark' | 'light' | 'auto';
"url": string;
}
interface IdentifoFormCallback {
}
interface IdentifoFormError {
}
interface IdentifoFormErrorAlert {
}
interface IdentifoFormForgot {
}
interface IdentifoFormForgotSuccess {
"selectedTheme": 'dark' | 'light';
}
interface IdentifoFormGoback {
}
interface IdentifoFormLogin {
}
interface IdentifoFormOtpLogin {
}
interface IdentifoFormPasswordReset {
}
interface IdentifoFormRegister {
}
interface IdentifoFormTfaSelect {
}
interface IdentifoFormTfaSetup {
}
interface IdentifoFormTfaSetupApp {
}
interface IdentifoFormTfaSetupEmail {
}
interface IdentifoFormTfaSetupSms {
}
interface IdentifoFormTfaVerify {
}
}
declare global {
interface HTMLIdentifoFormElement extends Components.IdentifoForm, HTMLStencilElement {
}
var HTMLIdentifoFormElement: {
prototype: HTMLIdentifoFormElement;
new (): HTMLIdentifoFormElement;
};
interface HTMLIdentifoFormCallbackElement extends Components.IdentifoFormCallback, HTMLStencilElement {
}
var HTMLIdentifoFormCallbackElement: {
prototype: HTMLIdentifoFormCallbackElement;
new (): HTMLIdentifoFormCallbackElement;
};
interface HTMLIdentifoFormErrorElement extends Components.IdentifoFormError, HTMLStencilElement {
}
var HTMLIdentifoFormErrorElement: {
prototype: HTMLIdentifoFormErrorElement;
new (): HTMLIdentifoFormErrorElement;
};
interface HTMLIdentifoFormErrorAlertElement extends Components.IdentifoFormErrorAlert, HTMLStencilElement {
}
var HTMLIdentifoFormErrorAlertElement: {
prototype: HTMLIdentifoFormErrorAlertElement;
new (): HTMLIdentifoFormErrorAlertElement;
};
interface HTMLIdentifoFormForgotElement extends Components.IdentifoFormForgot, HTMLStencilElement {
}
var HTMLIdentifoFormForgotElement: {
prototype: HTMLIdentifoFormForgotElement;
new (): HTMLIdentifoFormForgotElement;
};
interface HTMLIdentifoFormForgotSuccessElement extends Components.IdentifoFormForgotSuccess, HTMLStencilElement {
}
var HTMLIdentifoFormForgotSuccessElement: {
prototype: HTMLIdentifoFormForgotSuccessElement;
new (): HTMLIdentifoFormForgotSuccessElement;
};
interface HTMLIdentifoFormGobackElement extends Components.IdentifoFormGoback, HTMLStencilElement {
}
var HTMLIdentifoFormGobackElement: {
prototype: HTMLIdentifoFormGobackElement;
new (): HTMLIdentifoFormGobackElement;
};
interface HTMLIdentifoFormLoginElement extends Components.IdentifoFormLogin, HTMLStencilElement {
}
var HTMLIdentifoFormLoginElement: {
prototype: HTMLIdentifoFormLoginElement;
new (): HTMLIdentifoFormLoginElement;
};
interface HTMLIdentifoFormOtpLoginElement extends Components.IdentifoFormOtpLogin, HTMLStencilElement {
}
var HTMLIdentifoFormOtpLoginElement: {
prototype: HTMLIdentifoFormOtpLoginElement;
new (): HTMLIdentifoFormOtpLoginElement;
};
interface HTMLIdentifoFormPasswordResetElement extends Components.IdentifoFormPasswordReset, HTMLStencilElement {
}
var HTMLIdentifoFormPasswordResetElement: {
prototype: HTMLIdentifoFormPasswordResetElement;
new (): HTMLIdentifoFormPasswordResetElement;
};
interface HTMLIdentifoFormRegisterElement extends Components.IdentifoFormRegister, HTMLStencilElement {
}
var HTMLIdentifoFormRegisterElement: {
prototype: HTMLIdentifoFormRegisterElement;
new (): HTMLIdentifoFormRegisterElement;
};
interface HTMLIdentifoFormTfaSelectElement extends Components.IdentifoFormTfaSelect, HTMLStencilElement {
}
var HTMLIdentifoFormTfaSelectElement: {
prototype: HTMLIdentifoFormTfaSelectElement;
new (): HTMLIdentifoFormTfaSelectElement;
};
interface HTMLIdentifoFormTfaSetupElement extends Components.IdentifoFormTfaSetup, HTMLStencilElement {
}
var HTMLIdentifoFormTfaSetupElement: {
prototype: HTMLIdentifoFormTfaSetupElement;
new (): HTMLIdentifoFormTfaSetupElement;
};
interface HTMLIdentifoFormTfaSetupAppElement extends Components.IdentifoFormTfaSetupApp, HTMLStencilElement {
}
var HTMLIdentifoFormTfaSetupAppElement: {
prototype: HTMLIdentifoFormTfaSetupAppElement;
new (): HTMLIdentifoFormTfaSetupAppElement;
};
interface HTMLIdentifoFormTfaSetupEmailElement extends Components.IdentifoFormTfaSetupEmail, HTMLStencilElement {
}
var HTMLIdentifoFormTfaSetupEmailElement: {
prototype: HTMLIdentifoFormTfaSetupEmailElement;
new (): HTMLIdentifoFormTfaSetupEmailElement;
};
interface HTMLIdentifoFormTfaSetupSmsElement extends Components.IdentifoFormTfaSetupSms, HTMLStencilElement {
}
var HTMLIdentifoFormTfaSetupSmsElement: {
prototype: HTMLIdentifoFormTfaSetupSmsElement;
new (): HTMLIdentifoFormTfaSetupSmsElement;
};
interface HTMLIdentifoFormTfaVerifyElement extends Components.IdentifoFormTfaVerify, HTMLStencilElement {
}
var HTMLIdentifoFormTfaVerifyElement: {
prototype: HTMLIdentifoFormTfaVerifyElement;
new (): HTMLIdentifoFormTfaVerifyElement;
};
interface HTMLElementTagNameMap {
"identifo-form": HTMLIdentifoFormElement;
"identifo-form-callback": HTMLIdentifoFormCallbackElement;
"identifo-form-error": HTMLIdentifoFormErrorElement;
"identifo-form-error-alert": HTMLIdentifoFormErrorAlertElement;
"identifo-form-forgot": HTMLIdentifoFormForgotElement;
"identifo-form-forgot-success": HTMLIdentifoFormForgotSuccessElement;
"identifo-form-goback": HTMLIdentifoFormGobackElement;
"identifo-form-login": HTMLIdentifoFormLoginElement;
"identifo-form-otp-login": HTMLIdentifoFormOtpLoginElement;
"identifo-form-password-reset": HTMLIdentifoFormPasswordResetElement;
"identifo-form-register": HTMLIdentifoFormRegisterElement;
"identifo-form-tfa-select": HTMLIdentifoFormTfaSelectElement;
"identifo-form-tfa-setup": HTMLIdentifoFormTfaSetupElement;
"identifo-form-tfa-setup-app": HTMLIdentifoFormTfaSetupAppElement;
"identifo-form-tfa-setup-email": HTMLIdentifoFormTfaSetupEmailElement;
"identifo-form-tfa-setup-sms": HTMLIdentifoFormTfaSetupSmsElement;
"identifo-form-tfa-verify": HTMLIdentifoFormTfaVerifyElement;
}
}
declare namespace LocalJSX {
interface IdentifoForm {
"appId"?: string;
"callbackUrl"?: string;
"debug"?: boolean;
"federatedRedirectUrl"?: string;
"onComplete"?: (event: CustomEvent<LoginResponse>) => void;
"onError"?: (event: CustomEvent<ApiError>) => void;
"postLogoutRedirectUri"?: string;
"route"?: Routes;
"theme"?: 'dark' | 'light' | 'auto';
"url"?: string;
}
interface IdentifoFormCallback {
}
interface IdentifoFormError {
}
interface IdentifoFormErrorAlert {
}
interface IdentifoFormForgot {
}
interface IdentifoFormForgotSuccess {
"selectedTheme"?: 'dark' | 'light';
}
interface IdentifoFormGoback {
}
interface IdentifoFormLogin {
}
interface IdentifoFormOtpLogin {
}
interface IdentifoFormPasswordReset {
}
interface IdentifoFormRegister {
}
interface IdentifoFormTfaSelect {
}
interface IdentifoFormTfaSetup {
}
interface IdentifoFormTfaSetupApp {
}
interface IdentifoFormTfaSetupEmail {
}
interface IdentifoFormTfaSetupSms {
}
interface IdentifoFormTfaVerify {
}
interface IntrinsicElements {
"identifo-form": IdentifoForm;
"identifo-form-callback": IdentifoFormCallback;
"identifo-form-error": IdentifoFormError;
"identifo-form-error-alert": IdentifoFormErrorAlert;
"identifo-form-forgot": IdentifoFormForgot;
"identifo-form-forgot-success": IdentifoFormForgotSuccess;
"identifo-form-goback": IdentifoFormGoback;
"identifo-form-login": IdentifoFormLogin;
"identifo-form-otp-login": IdentifoFormOtpLogin;
"identifo-form-password-reset": IdentifoFormPasswordReset;
"identifo-form-register": IdentifoFormRegister;
"identifo-form-tfa-select": IdentifoFormTfaSelect;
"identifo-form-tfa-setup": IdentifoFormTfaSetup;
"identifo-form-tfa-setup-app": IdentifoFormTfaSetupApp;
"identifo-form-tfa-setup-email": IdentifoFormTfaSetupEmail;
"identifo-form-tfa-setup-sms": IdentifoFormTfaSetupSms;
"identifo-form-tfa-verify": IdentifoFormTfaVerify;
}
}
export { LocalJSX as JSX };
declare module "@stencil/core" {
export namespace JSX {
interface IntrinsicElements {
"identifo-form": LocalJSX.IdentifoForm & JSXBase.HTMLAttributes<HTMLIdentifoFormElement>;
"identifo-form-callback": LocalJSX.IdentifoFormCallback & JSXBase.HTMLAttributes<HTMLIdentifoFormCallbackElement>;
"identifo-form-error": LocalJSX.IdentifoFormError & JSXBase.HTMLAttributes<HTMLIdentifoFormErrorElement>;
"identifo-form-error-alert": LocalJSX.IdentifoFormErrorAlert & JSXBase.HTMLAttributes<HTMLIdentifoFormErrorAlertElement>;
"identifo-form-forgot": LocalJSX.IdentifoFormForgot & JSXBase.HTMLAttributes<HTMLIdentifoFormForgotElement>;
"identifo-form-forgot-success": LocalJSX.IdentifoFormForgotSuccess & JSXBase.HTMLAttributes<HTMLIdentifoFormForgotSuccessElement>;
"identifo-form-goback": LocalJSX.IdentifoFormGoback & JSXBase.HTMLAttributes<HTMLIdentifoFormGobackElement>;
"identifo-form-login": LocalJSX.IdentifoFormLogin & JSXBase.HTMLAttributes<HTMLIdentifoFormLoginElement>;
"identifo-form-otp-login": LocalJSX.IdentifoFormOtpLogin & JSXBase.HTMLAttributes<HTMLIdentifoFormOtpLoginElement>;
"identifo-form-password-reset": LocalJSX.IdentifoFormPasswordReset & JSXBase.HTMLAttributes<HTMLIdentifoFormPasswordResetElement>;
"identifo-form-register": LocalJSX.IdentifoFormRegister & JSXBase.HTMLAttributes<HTMLIdentifoFormRegisterElement>;
"identifo-form-tfa-select": LocalJSX.IdentifoFormTfaSelect & JSXBase.HTMLAttributes<HTMLIdentifoFormTfaSelectElement>;
"identifo-form-tfa-setup": LocalJSX.IdentifoFormTfaSetup & JSXBase.HTMLAttributes<HTMLIdentifoFormTfaSetupElement>;
"identifo-form-tfa-setup-app": LocalJSX.IdentifoFormTfaSetupApp & JSXBase.HTMLAttributes<HTMLIdentifoFormTfaSetupAppElement>;
"identifo-form-tfa-setup-email": LocalJSX.IdentifoFormTfaSetupEmail & JSXBase.HTMLAttributes<HTMLIdentifoFormTfaSetupEmailElement>;
"identifo-form-tfa-setup-sms": LocalJSX.IdentifoFormTfaSetupSms & JSXBase.HTMLAttributes<HTMLIdentifoFormTfaSetupSmsElement>;
"identifo-form-tfa-verify": LocalJSX.IdentifoFormTfaVerify & JSXBase.HTMLAttributes<HTMLIdentifoFormTfaVerifyElement>;
}
}
} | the_stack |
import EventSource from '../../view/event/EventSource';
import { fit, getDocumentScrollOrigin } from '../Utils';
import EventObject from '../../view/event/EventObject';
import mxClient from '../../mxClient';
import InternalEvent from '../../view/event/InternalEvent';
import { write } from '../DomUtils';
import { isLeftMouseButton } from '../EventUtils';
import Cell from '../../view/cell/datatypes/Cell';
import InternalMouseEvent from '../../view/event/InternalMouseEvent';
import { PopupMenuItem } from '../../types';
/**
* Class: mxPopupMenu
*
* Basic popup menu. To add a vertical scrollbar to a given submenu, the
* following code can be used.
*
* (code)
* let mxPopupMenuShowMenu = showMenu;
* showMenu = ()=>
* {
* mxPopupMenuShowMenu.apply(this, arguments);
*
* this.div.style.overflowY = 'auto';
* this.div.style.overflowX = 'hidden';
* this.div.style.maxHeight = '160px';
* };
* (end)
*
* Constructor: mxPopupMenu
*
* Constructs a popupmenu.
*
* Event: mxEvent.SHOW
*
* Fires after the menu has been shown in <popup>.
*/
class PopupMenu extends EventSource implements Partial<PopupMenuItem> {
constructor(
factoryMethod?: (handler: PopupMenuItem, cell: Cell | null, me: MouseEvent) => void
) {
super();
this.factoryMethod = factoryMethod;
// Adds the inner table
this.table = document.createElement('table');
this.table.className = 'mxPopupMenu';
this.tbody = document.createElement('tbody');
this.table.appendChild(this.tbody);
// Adds the outer div
this.div = document.createElement('div');
this.div.className = 'mxPopupMenu';
this.div.style.display = 'inline';
this.div.style.zIndex = String(this.zIndex);
this.div.appendChild(this.table);
// Disables the context menu on the outer div
InternalEvent.disableContextMenu(this.div);
}
div: HTMLElement;
table: HTMLElement;
tbody: HTMLElement;
activeRow: PopupMenuItem | null = null;
eventReceiver: HTMLElement | null = null;
/**
* Variable: submenuImage
*
* URL of the image to be used for the submenu icon.
*/
submenuImage = `${mxClient.imageBasePath}/submenu.gif`;
/**
* Variable: zIndex
*
* Specifies the zIndex for the popupmenu and its shadow. Default is 1006.
*/
zIndex = 10006;
/**
* Variable: factoryMethod
*
* Function that is used to create the popup menu. The function takes the
* current panning handler, the <mxCell> under the mouse and the mouse
* event that triggered the call as arguments.
*/
factoryMethod?: (handler: PopupMenuItem, cell: Cell | null, me: MouseEvent) => void;
/**
* Variable: useLeftButtonForPopup
*
* Specifies if popupmenus should be activated by clicking the left mouse
* button. Default is false.
*/
useLeftButtonForPopup = false;
/**
* Variable: enabled
*
* Specifies if events are handled. Default is true.
*/
enabled = true;
/**
* Variable: itemCount
*
* Contains the number of times <addItem> has been called for a new menu.
*/
itemCount = 0;
/**
* Variable: autoExpand
*
* Specifies if submenus should be expanded on mouseover. Default is false.
*/
autoExpand = false;
/**
* Variable: smartSeparators
*
* Specifies if separators should only be added if a menu item follows them.
* Default is false.
*/
smartSeparators = false;
/**
* Variable: labels
*
* Specifies if any labels should be visible. Default is true.
*/
labels = true;
willAddSeparator = false;
containsItems = false;
/**
* Function: isEnabled
*
* Returns true if events are handled. This implementation
* returns <enabled>.
*/
isEnabled() {
return this.enabled;
}
/**
* Function: setEnabled
*
* Enables or disables event handling. This implementation
* updates <enabled>.
*/
setEnabled(enabled: boolean) {
this.enabled = enabled;
}
/**
* Function: isPopupTrigger
*
* Returns true if the given event is a popupmenu trigger for the optional
* given cell.
*
* Parameters:
*
* me - <mxMouseEvent> that represents the mouse event.
*/
isPopupTrigger(me: InternalMouseEvent) {
return (
me.isPopupTrigger() ||
(this.useLeftButtonForPopup && isLeftMouseButton(me.getEvent()))
);
}
/**
* Function: addItem
*
* Adds the given item to the given parent item. If no parent item is specified
* then the item is added to the top-level menu. The return value may be used
* as the parent argument, ie. as a submenu item. The return value is the table
* row that represents the item.
*
* Paramters:
*
* title - String that represents the title of the menu item.
* image - Optional URL for the image icon.
* funct - Function associated that takes a mouseup or touchend event.
* parent - Optional item returned by <addItem>.
* iconCls - Optional string that represents the CSS class for the image icon.
* IconsCls is ignored if image is given.
* enabled - Optional boolean indicating if the item is enabled. Default is true.
* active - Optional boolean indicating if the menu should implement any event handling.
* Default is true.
* noHover - Optional boolean to disable hover state.
*/
addItem(
title: string,
image: string | null,
funct: Function,
parent: PopupMenuItem | null = null,
iconCls?: string,
enabled?: boolean,
active?: boolean,
noHover?: boolean
) {
parent = (parent ?? this) as PopupMenuItem;
this.itemCount++;
// Smart separators only added if element contains items
if (parent.willAddSeparator) {
if (parent.containsItems) {
this.addSeparator(parent, true);
}
parent.willAddSeparator = false;
}
parent.containsItems = true;
const tr = <PopupMenuItem>(<unknown>document.createElement('tr'));
tr.className = 'mxPopupMenuItem';
const col1 = document.createElement('td');
col1.className = 'mxPopupMenuIcon';
// Adds the given image into the first column
if (image) {
const img = document.createElement('img');
img.src = image;
col1.appendChild(img);
} else if (iconCls) {
const div = document.createElement('div');
div.className = iconCls;
col1.appendChild(div);
}
tr.appendChild(col1);
if (this.labels) {
const col2 = document.createElement('td');
col2.className = `mxPopupMenuItem${!enabled ? ' mxDisabled' : ''}`;
write(col2, title);
col2.align = 'left';
tr.appendChild(col2);
const col3 = document.createElement('td');
col3.className = `mxPopupMenuItem${!enabled ? ' mxDisabled' : ''}`;
col3.style.paddingRight = '6px';
col3.style.textAlign = 'right';
tr.appendChild(col3);
if (parent.div == null) {
this.createSubmenu(parent);
}
}
parent.tbody?.appendChild(tr);
if (active && enabled) {
InternalEvent.addGestureListeners(
tr,
(evt) => {
this.eventReceiver = tr;
if (parent && parent.activeRow != tr && parent.activeRow != parent) {
if (parent.activeRow != null && parent.activeRow.div.parentNode != null) {
this.hideSubmenu(parent);
}
if (tr.div != null) {
this.showSubmenu(parent, tr);
parent.activeRow = tr;
}
}
InternalEvent.consume(evt);
},
(evt) => {
if (parent && parent.activeRow != tr && parent.activeRow != parent) {
if (parent.activeRow != null && parent.activeRow.div.parentNode != null) {
this.hideSubmenu(parent);
}
if (this.autoExpand && tr.div != null) {
this.showSubmenu(parent, tr);
parent.activeRow = tr;
}
}
// Sets hover style because TR in IE doesn't have hover
if (!noHover) {
tr.className = 'mxPopupMenuItemHover';
}
},
(evt) => {
// EventReceiver avoids clicks on a submenu item
// which has just been shown in the mousedown
if (this.eventReceiver == tr) {
if (parent && parent.activeRow != tr) {
this.hideMenu();
}
if (funct != null) {
funct(evt);
}
}
this.eventReceiver = null;
InternalEvent.consume(evt);
}
);
// Resets hover style because TR in IE doesn't have hover
if (!noHover) {
InternalEvent.addListener(tr, 'mouseout', (evt: MouseEvent) => {
tr.className = 'mxPopupMenuItem';
});
}
}
return tr;
}
/**
* Adds a checkmark to the given menuitem.
*/
addCheckmark(item: HTMLElement, img: string) {
if (item.firstChild) {
const td = item.firstChild.nextSibling as HTMLElement;
td.style.backgroundImage = `url('${img}')`;
td.style.backgroundRepeat = 'no-repeat';
td.style.backgroundPosition = '2px 50%';
}
}
/**
* Function: createSubmenu
*
* Creates the nodes required to add submenu items inside the given parent
* item. This is called in <addItem> if a parent item is used for the first
* time. This adds various DOM nodes and a <submenuImage> to the parent.
*
* Parameters:
*
* parent - An item returned by <addItem>.
*/
createSubmenu(parent: PopupMenuItem) {
parent.table = document.createElement('table');
parent.table.className = 'mxPopupMenu';
parent.tbody = document.createElement('tbody');
parent.table.appendChild(parent.tbody);
parent.div = document.createElement('div');
parent.div.className = 'mxPopupMenu';
parent.div.style.position = 'absolute';
parent.div.style.display = 'inline';
parent.div.style.zIndex = String(this.zIndex);
parent.div.appendChild(parent.table);
const img = document.createElement('img');
img.setAttribute('src', this.submenuImage);
// Last column of the submenu item in the parent menu
if (parent.firstChild?.nextSibling?.nextSibling) {
const td = parent.firstChild.nextSibling.nextSibling;
td.appendChild(img);
}
}
/**
* Function: showSubmenu
*
* Shows the submenu inside the given parent row.
*/
// showSubmenu(parent: Element, row: Element): void;
showSubmenu(parent: PopupMenuItem, row: PopupMenuItem) {
if (row.div != null) {
row.div.style.left = `${
parent.div.offsetLeft + row.offsetLeft + row.offsetWidth - 1
}px`;
row.div.style.top = `${parent.div.offsetTop + row.offsetTop}px`;
document.body.appendChild(row.div);
// Moves the submenu to the left side if there is no space
const left = row.div.offsetLeft;
const width = row.div.offsetWidth;
const offset = getDocumentScrollOrigin(document);
const b = document.body;
const d = document.documentElement;
const right = offset.x + (b.clientWidth || d.clientWidth);
if (left + width > right) {
row.div.style.left = `${Math.max(0, parent.div.offsetLeft - width - 6)}px`;
}
fit(row.div);
}
}
/**
* Function: addSeparator
*
* Adds a horizontal separator in the given parent item or the top-level menu
* if no parent is specified.
*
* Parameters:
*
* parent - Optional item returned by <addItem>.
* force - Optional boolean to ignore <smartSeparators>. Default is false.
*/
addSeparator(parent: PopupMenuItem, force = false) {
parent = parent || this;
if (this.smartSeparators && !force) {
parent.willAddSeparator = true;
} else if (parent.tbody) {
parent.willAddSeparator = false;
const tr = document.createElement('tr');
const col1 = document.createElement('td');
col1.className = 'mxPopupMenuIcon';
col1.style.padding = '0 0 0 0px';
tr.appendChild(col1);
const col2 = document.createElement('td');
col2.style.padding = '0 0 0 0px';
col2.setAttribute('colSpan', '2');
const hr = document.createElement('hr');
hr.setAttribute('size', '1');
col2.appendChild(hr);
tr.appendChild(col2);
parent.tbody.appendChild(tr);
}
}
/**
* Function: popup
*
* Shows the popup menu for the given event and cell.
*
* Example:
*
* (code)
* graph.panningHandler.popup(x, y, cell, evt)
* {
* mxUtils.alert('Hello, World!');
* }
* (end)
*/
popup(x: number, y: number, cell: Cell | null, evt: MouseEvent) {
if (this.div != null && this.tbody != null && this.factoryMethod != null) {
this.div.style.left = `${x}px`;
this.div.style.top = `${y}px`;
// Removes all child nodes from the existing menu
while (this.tbody.firstChild != null) {
InternalEvent.release(this.tbody.firstChild);
this.tbody.removeChild(this.tbody.firstChild);
}
this.itemCount = 0;
this.factoryMethod(<PopupMenuItem>(<unknown>this), cell, evt);
if (this.itemCount > 0) {
this.showMenu();
this.fireEvent(new EventObject(InternalEvent.SHOW));
}
}
}
/**
* Function: isMenuShowing
*
* Returns true if the menu is showing.
*/
// isMenuShowing(): boolean;
isMenuShowing() {
return this.div != null && this.div.parentNode == document.body;
}
/**
* Function: showMenu
*
* Shows the menu.
*/
// showMenu(): void;
showMenu() {
// Fits the div inside the viewport
document.body.appendChild(this.div);
fit(this.div);
}
/**
* Function: hideMenu
*
* Removes the menu and all submenus.
*/
// hideMenu(): void;
hideMenu() {
if (this.div != null) {
if (this.div.parentNode != null) {
this.div.parentNode.removeChild(this.div);
}
this.hideSubmenu(<PopupMenuItem>(<unknown>this));
this.containsItems = false;
this.fireEvent(new EventObject(InternalEvent.HIDE));
}
}
/**
* Function: hideSubmenu
*
* Removes all submenus inside the given parent.
*
* Parameters:
*
* parent - An item returned by <addItem>.
*/
hideSubmenu(parent: PopupMenuItem) {
if (parent.activeRow != null) {
this.hideSubmenu(parent.activeRow);
if (parent.activeRow.div.parentNode != null) {
parent.activeRow.div.parentNode.removeChild(parent.activeRow.div);
}
parent.activeRow = null;
}
}
/**
* Function: destroy
*
* Destroys the handler and all its resources and DOM nodes.
*/
destroy() {
if (this.div != null) {
InternalEvent.release(this.div);
if (this.div.parentNode != null) {
this.div.parentNode.removeChild(this.div);
}
}
}
}
export default PopupMenu; | the_stack |
import { outputFileSync } from 'fs-extra';
import path from 'path';
import { Logger } from 'pino';
import { Browser, CDPSession, Protocol, ElementHandle, Page } from 'puppeteer';
import { config, CONFIG_DIR } from '../common/config';
import { EPIC_PURCHASE_ENDPOINT, STORE_HOMEPAGE_EN } from '../common/constants';
import { getLocaltunnelUrl } from '../common/localtunnel';
import logger from '../common/logger';
import puppeteer, {
getDevtoolsUrl,
launchArgs,
toughCookieFileStoreToPuppeteerCookie,
} from '../common/puppeteer';
import { getCookiesRaw, setPuppeteerCookies } from '../common/request';
import { NotificationReason } from '../interfaces/notification-reason';
import { sendNotification } from '../notify';
import { getHcaptchaCookies } from './hcaptcha';
const NOTIFICATION_TIMEOUT = config.notificationTimeoutHours * 60 * 60 * 1000;
export default class PuppetPurchase {
private L: Logger;
private email: string;
constructor(email: string) {
this.L = logger.child({
user: email,
});
this.email = email;
}
/**
* Completes a purchase starting from the product page using its productSlug
* **Currently unused**
*/
public async purchaseFull(productSlug: string): Promise<void> {
const hCaptchaCookies = await getHcaptchaCookies();
const userCookies = await getCookiesRaw(this.email);
const puppeteerCookies = toughCookieFileStoreToPuppeteerCookie(userCookies);
this.L.debug('Purchasing with puppeteer');
const browser = await puppeteer.launch(launchArgs);
const page = await browser.newPage();
this.L.trace(getDevtoolsUrl(page));
const cdpClient = await page.target().createCDPSession();
await cdpClient.send('Network.setCookies', {
cookies: [...puppeteerCookies, ...hCaptchaCookies],
});
await page.setCookie(...puppeteerCookies, ...hCaptchaCookies);
await page.setCookie({
name: 'HAS_ACCEPTED_AGE_GATE_ONCE',
domain: 'www.epicgames.com',
value: 'true',
});
await page.goto(`${STORE_HOMEPAGE_EN}p/${productSlug}`);
this.L.trace('Waiting for getButton');
const getButton = (await page.waitForSelector(
`button[data-testid='purchase-cta-button']:not([aria-disabled='true'])`
)) as ElementHandle<HTMLButtonElement>;
// const buttonMessage: ElementHandle<HTMLSpanElement> | null = await getButton.$(
// `span[data-component='Message']`
// );
await getButton.click({ delay: 100 });
this.L.trace('Waiting for placeOrderButton');
const waitForPurchaseButton = async (
startTime = new Date()
): Promise<ElementHandle<HTMLButtonElement>> => {
const timeout = 30000;
const poll = 100;
try {
const purchaseHandle = await page.waitForSelector('#webPurchaseContainer > iframe', {
timeout: 100,
});
if (!purchaseHandle) throw new Error('Could not find webPurchaseContainer iframe');
const purchaseFrame = await purchaseHandle.contentFrame();
if (!purchaseFrame) throw new Error('Could not find purchaseFrame contentFrame');
const button = await purchaseFrame.$(`button.payment-btn`);
if (!button) throw new Error('Could not find purchase button in iframe');
return button;
} catch (err) {
if (startTime.getTime() + timeout <= new Date().getTime()) {
throw new Error(`Timeout after ${timeout}ms: ${err.message}`);
}
await new Promise((resolve) => setTimeout(resolve, poll));
return waitForPurchaseButton(startTime);
}
};
const [placeOrderButton] = await Promise.all([
waitForPurchaseButton(),
page.waitForNetworkIdle(),
]);
this.L.trace('Clicking placeOrderButton');
await placeOrderButton.click({ delay: 100 });
this.L.trace('Waiting for purchased button');
await page.waitForSelector(
`button[data-testid='purchase-cta-button'] > span[data-component='Icon']`
);
this.L.info(`Puppeteer purchase of ${productSlug} complete`);
this.L.trace('Saving new cookies');
const currentUrlCookies = (await cdpClient.send('Network.getAllCookies')) as {
cookies: Protocol.Network.Cookie[];
};
setPuppeteerCookies(this.email, currentUrlCookies.cookies);
this.L.trace('Saved cookies, closing browser');
await browser.close();
}
private async waitForHCaptcha(page: Page): Promise<'captcha' | 'nav'> {
try {
const talonHandle = await page.$('iframe#talon_frame_checkout_free_prod');
if (!talonHandle) throw new Error('Could not find talon_frame_checkout_free_prod');
const talonFrame = await talonHandle.contentFrame();
if (!talonFrame) throw new Error('Could not find talonFrame contentFrame');
this.L.trace('Waiting for hcaptcha iframe');
await talonFrame.waitForSelector(`#challenge_container_hcaptcha > iframe[src*="hcaptcha"]`, {
visible: true,
});
return 'captcha';
} catch (err) {
if (err.message.includes('timeout')) {
throw err;
}
if (err.message.includes('detached')) {
this.L.trace(err);
} else {
this.L.warn(err);
}
return 'nav';
}
}
/**
* Completes a purchase starting from the purchase iframe using its namespace and offerId
*/
public async purchaseShort(namespace: string, offer: string): Promise<void> {
const hCaptchaCookies = await getHcaptchaCookies();
const userCookies = await getCookiesRaw(this.email);
const puppeteerCookies = toughCookieFileStoreToPuppeteerCookie(userCookies);
this.L.debug('Purchasing with puppeteer (short)');
const browser = await puppeteer.launch(launchArgs);
const page = await browser.newPage();
this.L.trace(getDevtoolsUrl(page));
const cdpClient = await page.target().createCDPSession();
try {
await cdpClient.send('Network.setCookies', {
cookies: [...puppeteerCookies, ...hCaptchaCookies],
});
await page.setCookie(...puppeteerCookies, ...hCaptchaCookies);
const purchaseUrl = `${EPIC_PURCHASE_ENDPOINT}?highlightColor=0078f2&offers=1-${namespace}-${offer}&orderId&purchaseToken&showNavigation=true`;
this.L.info({ purchaseUrl }, 'Loading purchase page');
await page.goto(purchaseUrl, { waitUntil: 'networkidle0' });
await page.waitForNetworkIdle({ idleTime: 2000 });
try {
this.L.trace('Waiting for cookieDialog');
const cookieDialog = (await page.waitForSelector(`button#onetrust-accept-btn-handler`, {
timeout: 3000,
})) as ElementHandle<HTMLButtonElement>;
this.L.trace('Clicking cookieDialog');
await cookieDialog.click({ delay: 100 });
} catch (err) {
if (!err.message.includes('timeout')) {
throw err;
}
this.L.trace('No cookie dialog presented');
}
this.L.trace('Waiting for placeOrderButton');
const placeOrderButton = (await page.waitForSelector(
`button.payment-btn:not([disabled])`
)) as ElementHandle<HTMLButtonElement>;
this.L.debug('Clicking placeOrderButton');
await placeOrderButton.click({ delay: 100 });
try {
const euRefundAgreeButton = (await page.waitForSelector(
`div.payment-confirm__actions > button.payment-btn.payment-confirm__btn.payment-btn--primary`,
{ timeout: 3000 }
)) as ElementHandle<HTMLButtonElement>;
this.L.debug('Clicking euRefundAgreeButton');
await euRefundAgreeButton.click({ delay: 100 });
} catch (err) {
if (!err.message.includes('timeout')) {
throw err;
}
this.L.trace('No EU "Refund and Right of Withdrawal Information" dialog presented');
}
this.L.debug('Waiting for receipt');
const purchaseEvent = await Promise.race([
page
.waitForFunction(() => document.location.hash.includes('/purchase/receipt'))
.then(() => 'nav'),
page
.waitForSelector('span.payment-alert__content')
.then((errorHandle: ElementHandle<HTMLSpanElement> | null) =>
errorHandle ? errorHandle.evaluate((el) => el.innerText) : 'Unknown purchase error'
),
this.waitForHCaptcha(page),
]);
if (purchaseEvent === 'captcha') {
this.L.debug('Captcha detected');
let url = await page.openPortal();
if (config.webPortalConfig?.localtunnel) {
url = await getLocaltunnelUrl(url);
}
this.L.info({ url }, 'Go to this URL and do something');
await sendNotification(url, this.email, NotificationReason.PURCHASE);
await page
.waitForFunction(() => document.location.hash.includes('/purchase/receipt'), {
timeout: NOTIFICATION_TIMEOUT,
})
.then(() => 'nav');
await page.closePortal();
} else if (purchaseEvent !== 'nav') {
throw new Error(purchaseEvent);
}
await this.finishPurchase(browser, cdpClient);
} catch (err) {
let success = false;
if (page) {
const errorPrefix = `error-${new Date().toISOString()}`.replace(/:/g, '-');
const errorImage = path.join(CONFIG_DIR, `${errorPrefix}.png`);
await page.screenshot({ path: errorImage });
const errorHtml = path.join(CONFIG_DIR, `${errorPrefix}.html`);
const htmlContent = await page.content();
outputFileSync(errorHtml, htmlContent, 'utf8');
this.L.error(
{ errorImage, errorHtml },
'Encountered an error during browser automation. Saved a screenshot and page HTML for debugging purposes.'
);
if (!config.noHumanErrorHelp)
success = await this.sendErrorManualHelpNotification(page, browser, cdpClient);
}
if (browser) await browser.close();
if (!success) throw err;
}
}
private async finishPurchase(browser: Browser, cdpClient: CDPSession): Promise<void> {
this.L.trace(`Puppeteer purchase successful`);
this.L.trace('Saving new cookies');
const currentUrlCookies = (await cdpClient.send('Network.getAllCookies')) as {
cookies: Protocol.Network.Cookie[];
};
setPuppeteerCookies(this.email, currentUrlCookies.cookies);
this.L.trace('Saved cookies, closing browser');
await browser.close();
}
private async sendErrorManualHelpNotification(
page: Page,
browser: Browser,
cdpClient: CDPSession
): Promise<boolean> {
this.L.info('Asking a human for help...');
try {
let url = await page.openPortal();
if (config.webPortalConfig?.localtunnel) {
url = await getLocaltunnelUrl(url);
}
this.L.info({ url }, 'Go to this URL and purchase the game');
await sendNotification(url, this.email, NotificationReason.PURCHASE_ERROR);
await page.waitForFunction(() => document.location.hash.includes('/purchase/receipt'), {
timeout: NOTIFICATION_TIMEOUT,
});
await page.closePortal();
await this.finishPurchase(browser, cdpClient);
return true;
} catch (err) {
this.L.error('Encountered an error when asking a human for help');
this.L.error(err);
return false;
}
}
} | the_stack |
'use strict';
import { LSPConnection, webSocketTransport } from '@sourcegraph/lsp-client';
import {
CancellationToken,
Definition,
DefinitionLink,
Disposable,
DocumentSymbol,
Hover,
Location,
LocationLink,
MarkdownString,
Position,
Range,
ReferenceContext,
SymbolInformation,
TextDocument,
Uri,
workspace,
WorkspaceFolder
} from 'vscode';
import {
ClientCapabilities,
DefinitionRequest,
DocumentSymbolRequest,
HoverRequest,
ImplementationRequest,
InitializeRequest,
DocumentSymbol as LspDocumentSymbol,
Location as LspLocation,
LocationLink as LspLocationLink,
MarkupContent as LspMarkupContent,
Range as LspRange,
SymbolInformation as LspSymbolInformation,
MarkupKind,
ReferencesRequest,
RequestType,
ServerCapabilities,
WorkspaceSymbolRequest
} from 'vscode-languageserver-protocol';
import { Logger } from './logger';
import { SourcegraphApi } from './sourcegraphApi';
import { fromRemoteHubUri, fromSourcegraphUri, toSourcegraphUri } from './uris';
import { debug } from './system';
type RequestParamsOf<RT> = RT extends RequestType<infer R, any, any, any> ? R : never;
type RequestResponseOf<RT> = RT extends RequestType<any, infer R, any, any> ? R : never;
export class SourcegraphLsp implements Disposable {
private readonly _disposable: Disposable | undefined;
private readonly _connections = new Map<string, WorkspaceLspConnection>();
constructor(private readonly _sourcegraph: SourcegraphApi) {}
dispose() {
this._disposable && this._disposable.dispose();
}
@debug({
args: {
0: document => Logger.toLoggable(document.uri),
2: () => false
}
})
async definition(
document: TextDocument,
position: Position,
token: CancellationToken
): Promise<Definition | DefinitionLink[] | undefined> {
const response = await this.lsp(
DefinitionRequest.type,
{
position: {
character: position.character,
line: position.line
},
textDocument: { uri: '' }
},
document.uri,
document.languageId
);
if (!response) return undefined;
if (!Array.isArray(response)) {
return new Location(fromSourcegraphUri(Uri.parse(response.uri)), toRange(response.range));
}
const definition = (response as (LspLocation | LspLocationLink)[]).map(d => {
if (LspLocationLink.is(d)) {
const link: LocationLink = {
targetUri: fromSourcegraphUri(Uri.parse(d.targetUri)),
targetRange: toRange(d.targetRange),
targetSelectionRange: d.targetSelectionRange && toRange(d.targetSelectionRange),
originSelectionRange: d.originSelectionRange && toRange(d.originSelectionRange)
};
return link;
}
return new Location(fromSourcegraphUri(Uri.parse(d.uri)), toRange(d.range));
});
return definition as Definition | DefinitionLink[];
}
@debug({
args: {
0: document => Logger.toLoggable(document.uri),
1: () => false
}
})
async documentSymbols(
document: TextDocument,
token: CancellationToken
): Promise<SymbolInformation[] | DocumentSymbol[] | undefined> {
const response = await this.lsp(
DocumentSymbolRequest.type,
{
textDocument: { uri: '' }
},
document.uri,
document.languageId,
token
);
if (!response) return undefined;
const symbols = (response as (LspSymbolInformation | LspDocumentSymbol)[]).map(s => {
if (LspDocumentSymbol.is(s)) {
return new DocumentSymbol(s.name, s.detail!, s.kind, toRange(s.range), toRange(s.selectionRange));
}
return new SymbolInformation(
s.name,
s.kind,
s.containerName!,
new Location(fromSourcegraphUri(Uri.parse(s.location.uri)), toRange(s.location.range))
);
});
return symbols as SymbolInformation[] | DocumentSymbol[];
}
@debug({
args: {
0: document => Logger.toLoggable(document.uri),
2: () => false
}
})
async hover(document: TextDocument, position: Position, token: CancellationToken): Promise<Hover | undefined> {
const response = await this.lsp(
HoverRequest.type,
{
position: {
character: position.character,
line: position.line
},
textDocument: { uri: '' }
},
document.uri,
document.languageId,
token
);
if (!response) return undefined;
const s = new MarkdownString();
const contents = Array.isArray(response.contents) ? response.contents : [response.contents];
for (const c of contents) {
if (LspMarkupContent.is(c)) {
if (c.kind === MarkupKind.Markdown) {
s.appendMarkdown(c.value);
}
else {
s.appendText(c.value);
}
}
else if (typeof c === 'string') {
s.appendText(c);
}
else {
s.appendCodeblock(c.value, c.language);
}
}
const hover = new Hover(s, response.range && toRange(response.range));
return hover;
}
@debug({
args: {
0: document => Logger.toLoggable(document.uri),
2: () => false
}
})
async implementation(
document: TextDocument,
position: Position,
token: CancellationToken
): Promise<Definition | DefinitionLink[] | undefined> {
const response = await this.lsp(
ImplementationRequest.type,
{
position: {
character: position.character,
line: position.line
},
textDocument: { uri: '' }
},
document.uri,
document.languageId
);
if (!response) return undefined;
if (!Array.isArray(response)) {
return new Location(fromSourcegraphUri(Uri.parse(response.uri)), toRange(response.range));
}
const definition = (response as (LspLocation | LspLocationLink)[]).map(d => {
if (LspLocationLink.is(d)) {
const link: LocationLink = {
targetUri: fromSourcegraphUri(Uri.parse(d.targetUri)),
targetRange: toRange(d.targetRange),
targetSelectionRange: d.targetSelectionRange && toRange(d.targetSelectionRange),
originSelectionRange: d.originSelectionRange && toRange(d.originSelectionRange)
};
return link;
}
return new Location(fromSourcegraphUri(Uri.parse(d.uri)), toRange(d.range));
});
return definition as Definition | DefinitionLink[];
}
@debug({
args: {
0: document => Logger.toLoggable(document.uri),
2: () => false
}
})
async references(
document: TextDocument,
position: Position,
context: ReferenceContext,
token: CancellationToken
): Promise<Location[] | undefined> {
const response = await this.lsp(
ReferencesRequest.type,
{
position: {
character: position.character,
line: position.line
},
context: {
...context
},
textDocument: { uri: '' }
},
document.uri,
document.languageId
);
if (!response) return undefined;
const locations = response.map(d => new Location(fromSourcegraphUri(Uri.parse(d.uri)), toRange(d.range)));
return locations;
}
@debug({ args: { 2: () => false } })
async workspaceSymbols(
query: string,
uri: Uri,
languageId: string | undefined,
token: CancellationToken
): Promise<SymbolInformation[] | undefined> {
const response = await this.lsp(
WorkspaceSymbolRequest.type,
{
query: query
},
uri,
languageId,
token
);
if (!response) return undefined;
const symbols = response.map(s => {
return new SymbolInformation(
s.name,
s.kind,
s.containerName!,
new Location(fromSourcegraphUri(Uri.parse(s.location.uri)), toRange(s.location.range))
);
});
return symbols;
}
@debug({
args: {
0: type => type.method,
4: () => false
}
})
private async lsp<RT extends RequestType<any, any, any, any>>(
type: RT,
params: RequestParamsOf<RT>,
uri: Uri,
languageId: string | undefined,
token?: CancellationToken
): Promise<RequestResponseOf<RT> | undefined> {
const cc = Logger.getCorrelationContext();
const folder = workspace.getWorkspaceFolder(uri);
if (folder === undefined) return undefined;
const key = `${folder.uri.toString(true)}${languageId ? `|${languageId}` : ''}`;
let connection = this._connections.get(key);
if (connection === undefined) {
const [owner, name] = fromRemoteHubUri(uri);
const repo = await this._sourcegraph.repositoryQuery(owner, name);
if (repo === undefined) return undefined;
connection = new WorkspaceLspConnection(folder, repo.languageId || languageId!, repo.revision);
await connection.connect();
this._connections.set(key, connection);
}
try {
const sgUri = toSourcegraphUri(uri, connection.revision);
if (params.textDocument) {
params.textDocument.uri = sgUri.toString(true);
}
const response = await connection.sendRequest(type, params, token);
return response;
}
catch (ex) {
Logger.error(ex, cc);
return undefined;
}
}
}
// eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion
const clientCapabilities: ClientCapabilities = {
experimental: {
progress: 'True'
}
};
class WorkspaceLspConnection implements Disposable {
public readonly rootUri: Uri;
private _capabilities: ServerCapabilities | undefined;
private _connection: LSPConnection | undefined;
constructor(
folder: WorkspaceFolder,
public readonly languageId: string | undefined,
public readonly revision: string | undefined
) {
this.rootUri = toSourcegraphUri(folder.uri, revision, true);
}
dispose() {
this.disconnect();
}
@debug()
async connect() {
const cc = Logger.getCorrelationContext();
try {
this._connection = await webSocketTransport({
serverUrl: `https://${this.languageId}.sourcegraph.com/`,
logger: new NoopLogger()
})();
// TODO: Reconnect?
// this._connection.closeEvent.subscribe();
const response = await this._connection.sendRequest(InitializeRequest.type, {
processId: 0,
rootUri: this.rootUri.toString(true),
capabilities: clientCapabilities,
workspaceFolders: [
{
name: '',
uri: this.rootUri.toString(true)
}
],
initializationOptions: {
configuration: {
[`${this.languageId}.sourcegraphUrl`]: 'https://sourcegraph.com/',
[`${this.languageId}.serverUrl`]: `wss://${this.languageId}.sourcegraph.com`,
[`${this.languageId}.progress`]: false
}
}
});
this._capabilities = response.capabilities;
}
catch (ex) {
Logger.error(ex, cc);
}
}
@debug()
disconnect() {
if (this._connection === undefined) return;
try {
this._connection.unsubscribe();
this._connection = undefined;
}
catch {}
}
ensureCapability<RT extends RequestType<any, any, any, any>>(type: RT) {
if (this._capabilities === undefined) return false;
switch (type.method) {
case DefinitionRequest.type.method:
if (this._capabilities.definitionProvider) return true;
break;
case DocumentSymbolRequest.type.method:
if (this._capabilities.documentSymbolProvider) return true;
break;
case HoverRequest.type.method:
if (this._capabilities.hoverProvider) return true;
break;
case ImplementationRequest.type.method:
if (this._capabilities.implementationProvider) return true;
break;
case ReferencesRequest.type.method:
if (this._capabilities.referencesProvider) return true;
break;
case WorkspaceSymbolRequest.type.method:
if (this._capabilities.workspaceSymbolProvider) return true;
break;
}
return false;
}
@debug({
args: {
0: type => type.method,
2: () => false
}
})
async sendRequest<RT extends RequestType<any, any, any, any>>(
type: RT,
params: RequestParamsOf<RT>,
token?: CancellationToken
): Promise<RequestResponseOf<RT>> {
const cc = Logger.getCorrelationContext();
if (this._connection === undefined) throw new Error('Must call connect before trying to send a request');
if (!this.ensureCapability(type)) throw new Error(`${type.method} isn't supported by the LSP server`);
let retries = 0;
while (true) {
if (this._connection.closed) {
this.disconnect();
await this.connect();
}
try {
const response = await this._connection.sendRequest(type, params);
return response;
}
catch (ex) {
Logger.error(ex, cc);
if (/connection/.test(ex.message) || this._connection.closed) {
this.disconnect();
retries++;
if (retries < 3) {
Logger.debug(cc, `Retrying... #${retries}`);
continue;
}
}
throw ex;
}
}
}
}
export class NoopLogger {
// eslint-disable-next-line no-empty-function
log(...values: any[]) {}
// eslint-disable-next-line no-empty-function
info(...values: any[]) {}
// eslint-disable-next-line no-empty-function
warn(...values: any[]) {}
// eslint-disable-next-line no-empty-function
error(...values: any[]) {}
}
function toRange(range: LspRange): Range {
return new Range(range.start.line, range.start.character, range.end.line, range.end.character);
} | the_stack |
import {Class, AnyTiming, Timing} from "@swim/util";
import {MemberFastenerClass, Property} from "@swim/component";
import type {Trait} from "@swim/model";
import {ViewRef} from "@swim/view";
import type {GraphicsView} from "@swim/graphics";
import {Controller, TraitViewRef, TraitViewControllerSet} from "@swim/controller";
import type {SliceView} from "../slice/SliceView";
import type {SliceTrait} from "../slice/SliceTrait";
import {SliceController} from "../slice/SliceController";
import {PieView} from "./PieView";
import {PieTitle, PieTrait} from "./PieTrait";
import type {PieControllerObserver} from "./PieControllerObserver";
/** @public */
export interface PieControllerSliceExt {
attachSliceTrait(sliceTrait: SliceTrait, sliceController: SliceController): void;
detachSliceTrait(sliceTrait: SliceTrait, sliceController: SliceController): void;
attachSliceView(sliceView: SliceView, sliceController: SliceController): void;
detachSliceView(sliceView: SliceView, sliceController: SliceController): void;
attachSliceLabelView(labelView: GraphicsView, sliceController: SliceController): void;
detachSliceLabelView(labelView: GraphicsView, sliceController: SliceController): void;
attachSliceLegendView(legendView: GraphicsView, sliceController: SliceController): void;
detachSliceLegendView(legendView: GraphicsView, sliceController: SliceController): void;
}
/** @public */
export class PieController extends Controller {
override readonly observerType?: Class<PieControllerObserver>;
protected createTitleView(title: PieTitle, pieTrait: PieTrait): GraphicsView | string | null {
if (typeof title === "function") {
return title(pieTrait);
} else {
return title;
}
}
protected setTitleView(title: PieTitle | null, pieTrait: PieTrait): void {
const pieView = this.pie.view;
if (pieView !== null) {
const titleView = title !== null ? this.createTitleView(title, pieTrait) : null;
pieView.title.setView(titleView);
}
}
@TraitViewRef<PieController, PieTrait, PieView>({
traitType: PieTrait,
observesTrait: true,
willAttachTrait(pieTrait: PieTrait): void {
this.owner.callObservers("controllerWillAttachPieTrait", pieTrait, this.owner);
},
didAttachTrait(pieTrait: PieTrait): void {
const sliceTraits = pieTrait.slices.traits;
for (const traitId in sliceTraits) {
const sliceTrait = sliceTraits[traitId]!;
this.owner.slices.addTraitController(sliceTrait);
}
const pieView = this.view;
if (pieView !== null) {
this.owner.setTitleView(pieTrait.title.value, pieTrait);
}
},
willDetachTrait(pieTrait: PieTrait): void {
const pieView = this.view;
if (pieView !== null) {
this.owner.setTitleView(pieTrait.title.value, pieTrait);
}
const sliceTraits = pieTrait.slices.traits;
for (const traitId in sliceTraits) {
const sliceTrait = sliceTraits[traitId]!;
this.owner.slices.deleteTraitController(sliceTrait);
}
},
didDetachTrait(pieTrait: PieTrait): void {
this.owner.callObservers("controllerDidDetachPieTrait", pieTrait, this.owner);
},
traitDidSetPieTitle(newTitle: PieTitle | null, oldTitle: PieTitle | null, pieTrait: PieTrait): void {
this.owner.setTitleView(newTitle, pieTrait);
},
traitWillAttachSlice(sliceTrait: SliceTrait, targetTrait: Trait): void {
this.owner.slices.addTraitController(sliceTrait);
},
traitDidDetachSlice(sliceTrait: SliceTrait): void {
this.owner.slices.deleteTraitController(sliceTrait);
},
viewType: PieView,
observesView: true,
initView(pieView: PieView): void {
const sliceControllers = this.owner.slices.controllers;
for (const controllerId in sliceControllers) {
const sliceController = sliceControllers[controllerId]!;
const sliceView = sliceController.slice.view;
if (sliceView !== null && sliceView.parent === null) {
sliceController.slice.insertView(pieView);
}
}
this.owner.title.setView(pieView.title.view);
const pieTrait = this.trait;
if (pieTrait !== null) {
this.owner.setTitleView(pieTrait.title.value, pieTrait);
}
},
deinitView(pieView: PieView): void {
this.owner.title.setView(null);
},
willAttachView(pieView: PieView): void {
this.owner.callObservers("controllerWillAttachPieView", pieView, this.owner);
},
didDetachView(pieView: PieView): void {
this.owner.callObservers("controllerDidDetachPieView", pieView, this.owner);
},
viewWillAttachPieTitle(titleView: GraphicsView): void {
this.owner.title.setView(titleView);
},
viewDidDetachPieTitle(titleView: GraphicsView): void {
this.owner.title.setView(titleView);
},
})
readonly pie!: TraitViewRef<this, PieTrait, PieView>;
static readonly pie: MemberFastenerClass<PieController, "pie">;
@ViewRef<PieController, GraphicsView>({
key: true,
willAttachView(titleView: GraphicsView): void {
this.owner.callObservers("controllerWillAttachPieTitleView", titleView, this.owner);
},
didDetachView(titleView: GraphicsView): void {
this.owner.callObservers("controllerDidDetachPieTitleView", titleView, this.owner);
},
})
readonly title!: ViewRef<this, GraphicsView>;
static readonly title: MemberFastenerClass<PieController, "title">;
@Property({type: Timing, value: true})
readonly sliceTiming!: Property<this, Timing | boolean | undefined, AnyTiming>;
@TraitViewControllerSet<PieController, SliceTrait, SliceView, SliceController, PieControllerSliceExt>({
implements: true,
type: SliceController,
binds: true,
observes: true,
get parentView(): PieView | null {
return this.owner.pie.view;
},
getTraitViewRef(sliceController: SliceController): TraitViewRef<unknown, SliceTrait, SliceView> {
return sliceController.slice;
},
willAttachController(sliceController: SliceController): void {
this.owner.callObservers("controllerWillAttachSlice", sliceController, this.owner);
},
didAttachController(sliceController: SliceController): void {
const sliceTrait = sliceController.slice.trait;
if (sliceTrait !== null) {
this.attachSliceTrait(sliceTrait, sliceController);
}
const sliceView = sliceController.slice.view;
if (sliceView !== null) {
this.attachSliceView(sliceView, sliceController);
}
},
willDetachController(sliceController: SliceController): void {
const sliceView = sliceController.slice.view;
if (sliceView !== null) {
this.detachSliceView(sliceView, sliceController);
}
const sliceTrait = sliceController.slice.trait;
if (sliceTrait !== null) {
this.detachSliceTrait(sliceTrait, sliceController);
}
},
didDetachController(sliceController: SliceController): void {
this.owner.callObservers("controllerDidDetachSlice", sliceController, this.owner);
},
controllerWillAttachSliceTrait(sliceTrait: SliceTrait, sliceController: SliceController): void {
this.owner.callObservers("controllerWillAttachSliceTrait", sliceTrait, sliceController, this.owner);
this.attachSliceTrait(sliceTrait, sliceController);
},
controllerDidDetachSliceTrait(sliceTrait: SliceTrait, sliceController: SliceController): void {
this.detachSliceTrait(sliceTrait, sliceController);
this.owner.callObservers("controllerDidDetachSliceTrait", sliceTrait, sliceController, this.owner);
},
attachSliceTrait(sliceTrait: SliceTrait, sliceController: SliceController): void {
// hook
},
detachSliceTrait(sliceTrait: SliceTrait, sliceController: SliceController): void {
// hook
},
controllerWillAttachSliceView(sliceView: SliceView, sliceController: SliceController): void {
this.owner.callObservers("controllerWillAttachSliceView", sliceView, sliceController, this.owner);
this.attachSliceView(sliceView, sliceController);
},
controllerDidDetachSliceView(sliceView: SliceView, sliceController: SliceController): void {
this.detachSliceView(sliceView, sliceController);
this.owner.callObservers("controllerDidDetachSliceView", sliceView, sliceController, this.owner);
},
attachSliceView(sliceView: SliceView, sliceController: SliceController): void {
const labelView = sliceView.label.view;
if (labelView !== null) {
this.attachSliceLabelView(labelView, sliceController);
}
const legendView = sliceView.legend.view;
if (legendView !== null) {
this.attachSliceLegendView(legendView, sliceController);
}
},
detachSliceView(sliceView: SliceView, sliceController: SliceController): void {
const legendView = sliceView.legend.view;
if (legendView !== null) {
this.detachSliceLegendView(legendView, sliceController);
}
const labelView = sliceView.label.view;
if (labelView !== null) {
this.detachSliceLabelView(labelView, sliceController);
}
sliceView.remove();
},
controllerWillSetSliceValue(newValue: number, oldValue: number, sliceController: SliceController): void {
this.owner.callObservers("controllerWillSetSliceValue", newValue, oldValue, sliceController, this.owner);
},
controllerDidSetSliceValue(newValue: number, oldValue: number, sliceController: SliceController): void {
this.owner.callObservers("controllerDidSetSliceValue", newValue, oldValue, sliceController, this.owner);
},
controllerWillAttachSliceLabelView(labelView: GraphicsView, sliceController: SliceController): void {
this.owner.callObservers("controllerWillAttachSliceLabelView", labelView, sliceController, this.owner);
this.attachSliceLabelView(labelView, sliceController);
},
controllerDidDetachSliceLabelView(labelView: GraphicsView, sliceController: SliceController): void {
this.detachSliceLabelView(labelView, sliceController);
this.owner.callObservers("controllerDidDetachSliceLabelView", labelView, sliceController, this.owner);
},
attachSliceLabelView(labelView: GraphicsView, sliceController: SliceController): void {
// hook
},
detachSliceLabelView(labelView: GraphicsView, sliceController: SliceController): void {
// hook
},
controllerWillAttachSliceLegendView(legendView: GraphicsView, sliceController: SliceController): void {
this.owner.callObservers("controllerWillAttachSliceLegendView", legendView, sliceController, this.owner);
this.attachSliceLegendView(legendView, sliceController);
},
controllerDidDetachSliceLegendView(legendView: GraphicsView, sliceController: SliceController): void {
this.detachSliceLegendView(legendView, sliceController);
this.owner.callObservers("controllerDidDetachSliceLegendView", legendView, sliceController, this.owner);
},
attachSliceLegendView(legendView: GraphicsView, sliceController: SliceController): void {
// hook
},
detachSliceLegendView(legendView: GraphicsView, sliceController: SliceController): void {
// hook
},
})
readonly slices!: TraitViewControllerSet<this, SliceTrait, SliceView, SliceController> & PieControllerSliceExt;
static readonly slices: MemberFastenerClass<PieController, "slices">;
} | the_stack |
import { Ad } from "../ad";
import { ScraperType } from "../helpers";
import * as scraper from "../scraper";
describe("Kijiji Ad", () => {
const scraperSpy = jest.spyOn(scraper, "scrape");
const validateAdValues = (ad: Ad, expected: scraper.AdInfo) => {
for (const [key, value] of Object.entries(expected)) {
// Special checking for invalid dates since NaN != NaN
if (value instanceof Date && Number.isNaN(value.getTime())) {
expect(Number.isNaN((ad as any)[key].getTime())).toBe(true);
} else {
expect((ad as any)[key]).toEqual(value);
}
}
};
afterEach(() => {
jest.resetAllMocks();
});
describe("initialization", () => {
it("should use default values when none are provided", () => {
const ad = new Ad("http://example.com");
validateAdValues(ad, {
...new scraper.AdInfo(),
url: "http://example.com"
});
expect(ad.isScraped()).toBe(false);
});
it.each`
property | value
${"title"} | ${"a title"}
${"description"} | ${"a description"}
${"date"} | ${new Date()}
${"image"} | ${"http://example.com/someimage"}
${"images"} | ${["http://example.com/image1", "http://example.com/image2"]}
${"attributes"} | ${{ key1: "val1", key2: 123 }}
${"id"} | ${"456"}
`("should accept user-provided ad properties ($property=$value)", ({ property, value }) => {
const ad = new Ad("http://example.com", { [property]: value });
validateAdValues(ad, {
...new scraper.AdInfo(),
url: "http://example.com",
[property]: value
});
expect(ad.isScraped()).toBe(false);
});
it("should ignore invalid user-provided ad property", () => {
const ad = new Ad("http://example.com", { invalid: 123 } as any as scraper.AdInfo);
validateAdValues(ad, {
...new scraper.AdInfo(),
url: "http://example.com"
});
expect(ad.isScraped()).toBe(false);
});
it("should allow overriding the isScraped flag", () => {
const ad = new Ad("http://example.com", {}, true);
expect(ad.isScraped()).toBe(true);
});
it("should not allow overriding isScraped function", () => {
const ad = new Ad("http://example.com", { isScraped: 123 } as any as scraper.AdInfo);
expect(ad.isScraped).toBeInstanceOf(Function);
});
it("should not allow overriding scrape function", () => {
const ad = new Ad("http://example.com", { scrape: 123 } as any as scraper.AdInfo);
expect(ad.scrape).toBeInstanceOf(Function);
});
it("should not allow overriding URL", () => {
const ad = new Ad("http://example.com", { url: "http://example.org" } as any as scraper.AdInfo);
expect(ad.url).toBe("http://example.com");
});
});
describe("string representation", () => {
it("should display only URL if ad has no properties", () => {
const ad = new Ad("http://example.com");
expect(ad.toString()).toBe("http://example.com\r\n");
});
it("should include date if present", () => {
// The date printing is locale-specific, so use the setX() functions
const date = new Date();
date.setMonth(8);
date.setDate(5);
date.setFullYear(2020);
date.setHours(20);
date.setMinutes(5);
const ad = new Ad("http://example.com", { date });
expect(ad.toString()).toBe("[09/05/2020 @ 20:05] http://example.com\r\n");
});
it("should include title if present", () => {
const ad = new Ad("http://example.com", { title: "My ad" });
expect(ad.toString()).toBe("My ad\r\nhttp://example.com\r\n");
});
it("should include attributes if present", () => {
const ad = new Ad("http://example.com", {
attributes: {
mileage: 125864,
bedrooms: 4
}
});
expect(ad.toString()).toBe("http://example.com\r\n* mileage: 125864\r\n* bedrooms: 4\r\n");
});
it("should handle malformed location attribute", () => {
const ad = new Ad("http://example.com", {
attributes: {
location: 7
}
});
expect(ad.toString()).toBe("http://example.com\r\n* location: 7\r\n");
});
it("should include correct location attribute if present", () => {
const ad = new Ad("http://example.com", {
attributes: {
location: { mapAddress: "123 Main Street" }
}
});
expect(ad.toString()).toBe("http://example.com\r\n* location: 123 Main Street\r\n");
});
});
describe.each`
test | scraperOptions
${"without scraper options"} | ${undefined}
${"with scraper options"} | ${{ scraperType: ScraperType.HTML }}
`("scrape of existing ad object ($test)", ({ scraperOptions }) => {
it.each`
withCallback
${true}
${false}
`("should return error on scrape failure and leave ad unmodified (withCallback=$withCallback)", async ({ withCallback }) => {
const error = new Error("Bad response");
scraperSpy.mockRejectedValue(error);
const ad = new Ad("http://example.com");
const callback = jest.fn();
expect(ad.isScraped()).toBe(false);
try {
await ad.scrape(scraperOptions, withCallback ? callback : undefined);
fail("Expected error on scrape");
} catch (err) {
expect(err).toBe(error);
expect(scraperSpy).toBeCalledWith(ad.url, scraperOptions);
expect(ad.isScraped()).toBe(false);
if (withCallback) {
expect(callback).toBeCalledWith(error);
}
}
});
it.each`
withCallback
${true}
${false}
`("should update ad details on successful scrape (withCallback=$withCallback)", async ({ withCallback }) => {
// Of course this could only ever exist as a fake ad :(
const mockAdInfo: scraper.AdInfo = {
title: "Unlimited network requests",
description: "No IP bans at all!",
date: new Date(),
image: "main image",
images: ["dark room", "stock photo"],
attributes: {
type: "Offer",
price: "Free",
seller: "Kijiji"
},
url: "http://example.com",
id: "123"
};
scraperSpy.mockResolvedValue(mockAdInfo as scraper.AdInfo);
const ad = new Ad("http://example.com");
const callback = jest.fn();
expect(ad.isScraped()).toBe(false);
await ad.scrape(scraperOptions, withCallback ? callback : undefined);
expect(scraperSpy).toBeCalledWith(ad.url, scraperOptions);
expect(ad.isScraped()).toBe(true);
validateAdValues(ad, mockAdInfo);
if (withCallback) {
expect(callback).toBeCalledWith(null);
}
});
});
describe.each`
test | scraperOptions
${"without scraper options"} | ${undefined}
${"with scraper options"} | ${{ scraperType: ScraperType.HTML }}
`("get new ad object ($test)", ({ scraperOptions }) => {
it.each`
withCallback
${true}
${false}
`("should return error on scrape failure (withCallback=$withCallback)", async ({ withCallback }) => {
const error = new Error("Bad response");
const callback = jest.fn();
scraperSpy.mockRejectedValue(error);
try {
await Ad.Get("http://example.com", scraperOptions, withCallback ? callback : undefined);
fail("Expected error on scrape");
} catch (err) {
expect(err).toBe(error);
expect(scraperSpy).toBeCalledWith("http://example.com", scraperOptions);
if (withCallback) {
expect(callback).toBeCalledWith(error, expect.any(Ad));
}
}
});
it.each`
withCallback
${true}
${false}
`("should return ad on successful scrape (withCallback=$withCallback)", async ({ withCallback }) => {
const mockAdInfo: scraper.AdInfo = {
title: "Looking for free stuff",
description: "You just need to bring it to me. I'm doing you a favor",
date: new Date(),
image: "an image",
images: ["supplemental image"],
attributes: { type: "Wanted" },
url: "http://example.com",
id: "123"
};
const callback = jest.fn();
scraperSpy.mockResolvedValue(mockAdInfo);
const ad = await Ad.Get("http://example.com", scraperOptions, withCallback ? callback : undefined);
expect(scraperSpy).toBeCalledWith("http://example.com", scraperOptions);
expect(ad).toBeInstanceOf(Ad);
expect(ad.url).toBe("http://example.com");
expect(ad.isScraped()).toBe(true);
validateAdValues(ad, mockAdInfo);
if (withCallback) {
expect(callback).toBeCalledWith(null, ad);
}
});
});
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.