text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import merge from 'lodash.merge'; import * as os from 'os'; import R from 'ramda'; import { Client as Ssh2Client } from 'ssh2'; import { Analytics } from '../../../analytics/analytics'; import { getSync } from '../../../api/consumer/lib/global-config'; import * as globalConfig from '../../../api/consumer/lib/global-config'; import { BitId } from '../../../bit-id'; import globalFlags from '../../../cli/global-flags'; import { CFG_SSH_NO_COMPRESS, CFG_USER_TOKEN_KEY, DEFAULT_SSH_READY_TIMEOUT } from '../../../constants'; import ConsumerComponent from '../../../consumer/component'; import { ListScopeResult } from '../../../consumer/component/components-list'; import GeneralError from '../../../error/general-error'; import logger from '../../../logger/logger'; import { userpass as promptUserpass } from '../../../prompts'; import { buildCommandMessage, packCommand, toBase64, unpackCommand } from '../../../utils'; import ComponentObjects from '../../component-objects'; import DependencyGraph from '../../graph/scope-graph'; import { LaneData } from '../../lanes/lanes'; import { ComponentLog } from '../../models/model-component'; import RemovedObjects from '../../removed-components'; import { ScopeDescriptor } from '../../scope'; import checkVersionCompatibilityFunction from '../check-version-compatibility'; import { AuthenticationFailed, RemoteScopeNotFound, SSHInvalidResponse } from '../exceptions'; import { Network } from '../network'; import keyGetter from './key-getter'; import { FETCH_FORMAT_OBJECT_LIST, ObjectItemsStream, ObjectList } from '../../objects/object-list'; import CompsAndLanesObjects from '../../comps-and-lanes-objects'; import { FETCH_OPTIONS } from '../../../api/scope/lib/fetch'; import { remoteErrorHandler } from '../remote-error-handler'; import { PushOptions } from '../../../api/scope/lib/put'; const checkVersionCompatibility = R.once(checkVersionCompatibilityFunction); const AUTH_FAILED_MESSAGE = 'All configured authentication methods failed'; const PASSPHRASE_POSSIBLY_MISSING_MESSAGE = 'Cannot parse privateKey: Unsupported key format'; function absolutePath(path: string) { if (!path.startsWith('/')) return `~/${path}`; return path; } function clean(str: string) { return str.replace('\n', ''); } export type SSHProps = { path: string; username: string; port: number; host: string; }; export type SSHConnectionStrategyName = 'token' | 'ssh-agent' | 'ssh-key' | 'user-password' | 'anonymous'; class AuthenticationStrategyFailed extends Error {} export const DEFAULT_STRATEGIES: SSHConnectionStrategyName[] = ['token', 'ssh-agent', 'ssh-key', 'user-password']; export const DEFAULT_READ_STRATEGIES: SSHConnectionStrategyName[] = [ 'token', 'ssh-agent', 'ssh-key', 'anonymous', 'user-password', ]; export default class SSH implements Network { connection: Ssh2Client | null | undefined; path: string; username: string; port: number; host: string; _sshUsername?: string; // Username entered by the user on the prompt user/pass process constructor({ path, username, port, host }: SSHProps) { this.path = path; this.username = username; this.port = port; this.host = host || ''; } /** * Network strategies: * 1) token (generated by bit-login command) * 2) ssh-agent (public-key should be saved on bit.dev, user needs to enable ssh-agent in its os. the agent saves the passphrase, so no need to enter) * 3) ssh-key. (user can specify location by `bit config`, if not, the default one is used. doesn't support passphrase) * 4) anonymous. (for read operations only) - trying to do the action as anonymous user * 5) prompt of user/password */ async connect(strategiesNames: SSHConnectionStrategyName[] = DEFAULT_STRATEGIES): Promise<SSH> { const strategies: { [key: string]: Function } = { token: this._tokenAuthentication, anonymous: this._anonymousAuthentication, 'ssh-agent': this._sshAgentAuthentication, 'ssh-key': this._sshKeyAuthentication, 'user-password': this._userPassAuthentication, }; const strategiesFailures: string[] = []; for (const strategyName of strategiesNames) { logger.debug(`ssh, trying to connect using ${strategyName}`); const strategyFunc = strategies[strategyName].bind(this); try { const strategyResult = await strategyFunc(); // eslint-disable-line if (strategyResult) return strategyResult as SSH; } catch (err: any) { logger.debug(`ssh, failed to connect using ${strategyName}. ${err.message}`); if (err instanceof AuthenticationStrategyFailed) { strategiesFailures.push(err.message); } else { throw err; } } } logger.errorAndAddBreadCrumb('ssh', 'all connection strategies have been failed!'); strategiesFailures.unshift('The following strategies were failed'); throw new AuthenticationFailed(strategiesFailures.join('\n[-] ')); } async _tokenAuthentication(): Promise<SSH> { const sshConfig = this._composeTokenAuthObject(); if (!sshConfig) { throw new AuthenticationStrategyFailed( 'user token not defined in bit-config. please run `bit login` to authenticate.' ); } const authFailedMsg = 'failed to authenticate with user token. generate a new token by running `bit logout && bit login`.'; return this._connectWithConfig(sshConfig, 'token', authFailedMsg); } async _anonymousAuthentication(): Promise<SSH> { const sshConfig = this._composeAnonymousAuthObject(); if (!sshConfig) { throw new AuthenticationStrategyFailed('could not create the anonymous ssh configuration.'); } const authFailedMsg = 'collection might be private.'; return this._connectWithConfig(sshConfig, 'anonymous', authFailedMsg); } async _sshAgentAuthentication(): Promise<SSH> { if (!this._hasAgentSocket()) { throw new AuthenticationStrategyFailed( 'unable to get SSH keys from ssh-agent to. perhaps service is down or disabled.' ); } const sshConfig = merge(this._composeBaseObject(), { agent: process.env.SSH_AUTH_SOCK }); const authFailedMsg = 'no matching private key found in ssh-agent to authenticate to remote server.'; return this._connectWithConfig(sshConfig, 'ssh-agent', authFailedMsg); } async _sshKeyAuthentication(): Promise<SSH> { const keyBuffer = await keyGetter(); if (!keyBuffer) { throw new AuthenticationStrategyFailed( 'SSH key not found in `~/.ssh/id_rsa` or `ssh_key_file` config in `bit config` either not configured or refers to wrong path.' ); } const sshConfig = merge(this._composeBaseObject(), { privateKey: keyBuffer }); const authFailedMsg = 'failed connecting to remote server using `~/.ssh/id_rsa` or `ssh_key_file` in `bit config`.'; return this._connectWithConfig(sshConfig, 'ssh-key', authFailedMsg); } async _userPassAuthentication(): Promise<SSH> { const sshConfig = await this._composeUserPassObject(); const authFailedMsg = 'unable to connect using provided username and password combination.'; return this._connectWithConfig(sshConfig, 'user-password', authFailedMsg); } close() { this.connection.end(); return this; } _composeBaseObject(passphrase?: string) { return { username: this.username, host: this.host, port: this.port, passphrase, readyTimeout: DEFAULT_SSH_READY_TIMEOUT, }; } _composeTokenAuthObject(): Record<string, any> | null | undefined { const processToken = globalFlags.token; const token = processToken || getSync(CFG_USER_TOKEN_KEY); if (token) { this._sshUsername = 'token'; return merge(this._composeBaseObject(), { username: 'token', password: token }); } return null; } _composeAnonymousAuthObject(): Record<string, any> | null | undefined { this._sshUsername = 'anonymous'; return merge(this._composeBaseObject(), { username: 'anonymous', password: '' }); } _composeUserPassObject() { // @ts-ignore return promptUserpass().then(({ username, password }) => { Analytics.setExtraData('authentication_method', 'user_password'); this._sshUsername = username; return merge(this._composeBaseObject(), { username, password }); }); } _hasAgentSocket() { return !!process.env.SSH_AUTH_SOCK; } async _connectWithConfig( sshConfig: Record<string, any>, authenticationType: string, authFailedMsg: string ): Promise<SSH> { const connectWithConfigP = () => { const conn = new Ssh2Client(); return new Promise((resolve, reject) => { conn .on('error', (err) => { reject(err); }) .on('ready', () => { resolve(conn); }) .connect(sshConfig); }); }; try { this.connection = await connectWithConfigP(); Analytics.setExtraData('authentication_method', authenticationType); logger.debug(`ssh, authenticated successfully using ${authenticationType}`); return this; } catch (err: any) { if (err.message === AUTH_FAILED_MESSAGE) { throw new AuthenticationStrategyFailed(authFailedMsg); } logger.error('ssh', err); if (err.code === 'ENOTFOUND') { throw new GeneralError( `unable to find the SSH server. host: ${err.host}, port: ${err.port}. Original error message: ${err.message}` ); } if (err.message === PASSPHRASE_POSSIBLY_MISSING_MESSAGE) { const macMojaveOs = process.platform === 'darwin' && os.release() === '18.2.0'; let passphrasePossiblyMissing = 'error connecting with private ssh key. in case passphrase is used, use ssh-agent.'; if (macMojaveOs) { passphrasePossiblyMissing += ' for macOS Mojave users, use `-m PEM` for `ssh-keygen` command to generate a valid SSH key'; } throw new AuthenticationStrategyFailed(passphrasePossiblyMissing); } throw new AuthenticationStrategyFailed(`${authFailedMsg} due to an error "${err.message}"`); } } buildCmd(commandName: string, path: string, payload: any, context: any): string { const compress = globalConfig.getSync(CFG_SSH_NO_COMPRESS) !== 'true'; return `bit ${commandName} ${toBase64(path)} ${packCommand( buildCommandMessage(payload, context, compress), true, compress )}`; } exec(commandName: string, payload?: any, context?: Record<string, any>, dataToStream?: string): Promise<any> { logger.debug(`ssh: going to run a remote command ${commandName}, path: ${this.path}`); // Add the entered username to context if (this._sshUsername) { context = context || {}; context.sshUsername = this._sshUsername; } // eslint-disable-next-line consistent-return return new Promise((resolve, reject) => { let res = ''; let err; const cmd = this.buildCmd(commandName, absolutePath(this.path || ''), payload, context); if (!this.connection) { err = 'ssh connection is not defined'; logger.error('ssh', err); return reject(err); } // eslint-disable-next-line consistent-return this.connection.exec(cmd, (error, stream) => { if (error) { logger.error('ssh, exec returns an error: ', error); return reject(error); } if (dataToStream) { stream.stdin.write(dataToStream); stream.stdin.end(); } stream .on('data', (response) => { res += response.toString(); }) .on('exit', (code) => { logger.debug(`ssh: exit. Exit code: ${code}`); const promiseExit = () => { return code && code !== 0 ? reject(this.errorHandler(code, err)) : resolve(clean(res)); }; // sometimes the connection 'exit' before 'close' and then it doesn't have the data (err) ready yet. // in that case, we prefer to wait until the onClose will terminate the promise. // sometimes though, the connection only 'exit' and never 'close' (happened when _put command sent back // more than 1MB of data), in that case, the following setTimeout will terminate the promise. setTimeout(promiseExit, 2000); }) .on('close', (code, signal) => { // @todo: not sure why the next line was needed. if commenting it doesn't create any bug, please remove. // otherwise, replace payload with dataToStream // if (commandName === '_put') res = res.replace(payload, ''); logger.debug(`ssh: returned with code: ${code}, signal: ${signal}.`); // DO NOT CLOSE THE CONNECTION (using this.connection.end()), it causes bugs when there are several open // connections. Same bugs occur when running "this.connection.end()" on "end" or "exit" events. return code && code !== 0 ? reject(this.errorHandler(code, err)) : resolve(clean(res)); }) .stderr.on('data', (response) => { err = response.toString(); logger.error(`ssh: got an error, ${err}`); }); }); }); } errorHandler(code: number, err: string) { let parsedError; let remoteIsLegacy = false; try { const { headers, payload } = this._unpack(err, false); checkVersionCompatibility(headers.version); parsedError = payload; remoteIsLegacy = headers.version === '14.8.8' && parsedError.message.includes('Please update your Bit client'); } catch (e: any) { // be graceful when can't parse error message logger.error(`ssh: failed parsing error as JSON, error: ${err}`); } if (remoteIsLegacy) { return new GeneralError(`fatal: unable to connect to a remote legacy SSH server from Harmony client`); } return remoteErrorHandler(code, parsedError, `${this.host}:${this.path}`, err); } _unpack(data, base64 = true) { try { const unpacked = unpackCommand(data, base64); return unpacked; } catch (err: any) { logger.error(`unpackCommand found on error "${err}", while parsing the following string: ${data}`); throw new SSHInvalidResponse(data); } } async pushMany(objectList: ObjectList, pushOptions: PushOptions, context?: Record<string, any>): Promise<string[]> { // This ComponentObjects.manyToString will handle all the base64 stuff so we won't send this payload // to the pack command (to prevent duplicate base64) const data = await this.exec('_put', pushOptions, context, objectList.toJsonString()); const { payload, headers } = this._unpack(data); checkVersionCompatibility(headers.version); return payload.ids; } async action<Options, Result>(name: string, options: Options): Promise<Result> { const args = { name, options }; const result = await this.exec(`_action`, args); const { payload, headers } = this._unpack(result); checkVersionCompatibility(headers.version); return payload; } deleteMany( ids: string[], force: boolean, context?: Record<string, any>, idsAreLanes?: boolean ): Promise<ComponentObjects[] | RemovedObjects> { return this.exec( '_delete', { bitIds: ids, force, lanes: idsAreLanes, }, context ).then((data: string) => { const { payload } = this._unpack(data); return RemovedObjects.fromObjects(payload); }); } deprecateMany(ids: string[], context?: Record<string, any>): Promise<ComponentObjects[]> { return this.exec( '_deprecate', { ids, }, context ).then((data: string) => { const { payload } = this._unpack(data); return payload; }); } undeprecateMany(ids: string[], context?: Record<string, any>): Promise<ComponentObjects[]> { return this.exec( '_undeprecate', { ids, }, context ).then((data: string) => { const { payload } = this._unpack(data); return payload; }); } describeScope(): Promise<ScopeDescriptor> { return this.exec('_scope') .then((data) => { const { payload, headers } = this._unpack(data); checkVersionCompatibility(headers.version); return payload; }) .catch(() => { throw new RemoteScopeNotFound(this.path); }); } async list(namespacesUsingWildcards?: string): Promise<ListScopeResult[]> { return this.exec('_list', namespacesUsingWildcards).then(async (str: string) => { const { payload, headers } = this._unpack(str); checkVersionCompatibility(headers.version); payload.forEach((result) => { result.id = new BitId(result.id); }); return payload; }); } async listLanes(name?: string, mergeData?: boolean): Promise<LaneData[]> { const options = mergeData ? '--merge-data' : ''; const str = await this.exec(`_lanes ${options}`, name); const { payload, headers } = this._unpack(str); checkVersionCompatibility(headers.version); return payload.map((result) => ({ ...result, components: result.components.map((component) => ({ id: new BitId(component.id), head: component.head })), })); } latestVersions(componentIds: BitId[]): Promise<string[]> { const componentIdsStr = componentIds.map((componentId) => componentId.toString()); return this.exec('_latest', componentIdsStr).then((str: string) => { const { payload, headers } = this._unpack(str); checkVersionCompatibility(headers.version); return payload; }); } search(query: string, reindex: boolean) { return this.exec('_search', { query, reindex: reindex.toString() }).then((data) => { const { payload, headers } = this._unpack(data); checkVersionCompatibility(headers.version); return payload; }); } show(id: BitId): Promise<ConsumerComponent | null | undefined> { return this.exec('_show', id.toString()).then((str: string) => { const { payload, headers } = this._unpack(str); checkVersionCompatibility(headers.version); return str ? ConsumerComponent.fromString(payload) : null; }); } log(id: BitId): Promise<ComponentLog[]> { return this.exec('_log', id.toString()).then((str: string) => { const { payload, headers } = this._unpack(str); checkVersionCompatibility(headers.version); return str ? JSON.parse(payload) : null; }); } graph(bitId?: BitId): Promise<DependencyGraph> { const idStr = bitId ? bitId.toString() : ''; return this.exec('_graph', idStr).then((str: string) => { const { payload, headers } = this._unpack(str); checkVersionCompatibility(headers.version); return DependencyGraph.loadFromString(payload); }); } async fetch( idsStr: string[], fetchOptions: FETCH_OPTIONS, context?: Record<string, any> ): Promise<ObjectItemsStream> { let options = ''; const { type, withoutDependencies, includeArtifacts } = fetchOptions; if (type !== 'component') options = ` --type ${type}`; if (withoutDependencies) options += ' --no-dependencies'; if (includeArtifacts) options += ' --include-artifacts'; const str = await this.exec(`_fetch ${options}`, idsStr, context); const parseResponse = () => { try { const results = JSON.parse(str); return results; } catch (err: any) { throw new SSHInvalidResponse(str); } }; const { payload, headers } = parseResponse(); checkVersionCompatibility(headers.version); const format = headers.format; if (!format) { // this is an old version that doesn't have the "format" header const componentObjects = CompsAndLanesObjects.fromString(payload); return componentObjects.toObjectList().toReadableStream(); } if (format === FETCH_FORMAT_OBJECT_LIST) { return ObjectList.fromJsonString(payload).toReadableStream(); } throw new Error(`ssh.fetch, format "${format}" is not supported`); } }
the_stack
import * as cfnspec from '@aws-cdk/cfnspec'; import { IamChanges } from '../iam/iam-changes'; import { SecurityGroupChanges } from '../network/security-group-changes'; export declare type PropertyMap = { [key: string]: any; }; /** Semantic differences between two CloudFormation templates. */ export declare class TemplateDiff implements ITemplateDiff { awsTemplateFormatVersion?: Difference<string>; description?: Difference<string>; transform?: Difference<string>; conditions: DifferenceCollection<Condition, ConditionDifference>; mappings: DifferenceCollection<Mapping, MappingDifference>; metadata: DifferenceCollection<Metadata, MetadataDifference>; outputs: DifferenceCollection<Output, OutputDifference>; parameters: DifferenceCollection<Parameter, ParameterDifference>; resources: DifferenceCollection<Resource, ResourceDifference>; /** The differences in unknown/unexpected parts of the template */ unknown: DifferenceCollection<any, Difference<any>>; /** * Changes to IAM policies */ readonly iamChanges: IamChanges; /** * Changes to Security Group ingress and egress rules */ readonly securityGroupChanges: SecurityGroupChanges; constructor(args: ITemplateDiff); get differenceCount(): number; get isEmpty(): boolean; /** * Return true if any of the permissions objects involve a broadening of permissions */ get permissionsBroadened(): boolean; /** * Return true if any of the permissions objects have changed */ get permissionsAnyChanges(): boolean; /** * Return all property changes of a given scrutiny type * * We don't just look at property updates; we also look at resource additions and deletions (in which * case there is no further detail on property values), and resource type changes. */ private scrutinizablePropertyChanges; /** * Return all resource changes of a given scrutiny type * * We don't just look at resource updates; we also look at resource additions and deletions (in which * case there is no further detail on property values), and resource type changes. */ private scrutinizableResourceChanges; } /** * A change in property values * * Not necessarily an update, it could be that there used to be no value there * because there was no resource, and now there is (or vice versa). * * Therefore, we just contain plain values and not a PropertyDifference<any>. */ export interface PropertyChange { /** * Logical ID of the resource where this property change was found */ resourceLogicalId: string; /** * Type of the resource */ resourceType: string; /** * Scrutiny type for this property change */ scrutinyType: cfnspec.schema.PropertyScrutinyType; /** * Name of the property that is changing */ propertyName: string; /** * The old property value */ oldValue?: any; /** * The new property value */ newValue?: any; } /** * A resource change * * Either a creation, deletion or update. */ export interface ResourceChange { /** * Logical ID of the resource where this property change was found */ resourceLogicalId: string; /** * Scrutiny type for this resource change */ scrutinyType: cfnspec.schema.ResourceScrutinyType; /** * The type of the resource */ resourceType: string; /** * The old properties value (might be undefined in case of creation) */ oldProperties?: PropertyMap; /** * The new properties value (might be undefined in case of deletion) */ newProperties?: PropertyMap; } export interface IDifference<ValueType> { readonly oldValue: ValueType | undefined; readonly newValue: ValueType | undefined; readonly isDifferent: boolean; readonly isAddition: boolean; readonly isRemoval: boolean; readonly isUpdate: boolean; } /** * Models an entity that changed between two versions of a CloudFormation template. */ export declare class Difference<ValueType> implements IDifference<ValueType> { readonly oldValue: ValueType | undefined; readonly newValue: ValueType | undefined; /** * Whether this is an actual different or the values are actually the same * * isDifferent => (isUpdate | isRemoved | isUpdate) */ readonly isDifferent: boolean; /** * @param oldValue the old value, cannot be equal (to the sense of +deepEqual+) to +newValue+. * @param newValue the new value, cannot be equal (to the sense of +deepEqual+) to +oldValue+. */ constructor(oldValue: ValueType | undefined, newValue: ValueType | undefined); /** @returns +true+ if the element is new to the template. */ get isAddition(): boolean; /** @returns +true+ if the element was removed from the template. */ get isRemoval(): boolean; /** @returns +true+ if the element was already in the template and is updated. */ get isUpdate(): boolean; } export declare class PropertyDifference<ValueType> extends Difference<ValueType> { readonly changeImpact?: ResourceImpact; constructor(oldValue: ValueType | undefined, newValue: ValueType | undefined, args: { changeImpact?: ResourceImpact; }); } export declare class DifferenceCollection<V, T extends IDifference<V>> { private readonly diffs; constructor(diffs: { [logicalId: string]: T; }); get changes(): { [logicalId: string]: T; }; get differenceCount(): number; get(logicalId: string): T; get logicalIds(): string[]; /** * Returns a new TemplateDiff which only contains changes for which `predicate` * returns `true`. */ filter(predicate: (diff: T | undefined) => boolean): DifferenceCollection<V, T>; /** * Invokes `cb` for all changes in this collection. * * Changes will be sorted as follows: * - Removed * - Added * - Updated * - Others * * @param cb */ forEachDifference(cb: (logicalId: string, change: T) => any): void; } /** * Arguments expected by the constructor of +TemplateDiff+, extracted as an interface for the sake * of (relative) conciseness of the constructor's signature. */ export interface ITemplateDiff { awsTemplateFormatVersion?: IDifference<string>; description?: IDifference<string>; transform?: IDifference<string>; conditions?: DifferenceCollection<Condition, ConditionDifference>; mappings?: DifferenceCollection<Mapping, MappingDifference>; metadata?: DifferenceCollection<Metadata, MetadataDifference>; outputs?: DifferenceCollection<Output, OutputDifference>; parameters?: DifferenceCollection<Parameter, ParameterDifference>; resources?: DifferenceCollection<Resource, ResourceDifference>; unknown?: DifferenceCollection<any, IDifference<any>>; } export declare type Condition = any; export declare class ConditionDifference extends Difference<Condition> { } export declare type Mapping = any; export declare class MappingDifference extends Difference<Mapping> { } export declare type Metadata = any; export declare class MetadataDifference extends Difference<Metadata> { } export declare type Output = any; export declare class OutputDifference extends Difference<Output> { } export declare type Parameter = any; export declare class ParameterDifference extends Difference<Parameter> { } export declare enum ResourceImpact { /** The existing physical resource will be updated */ WILL_UPDATE = "WILL_UPDATE", /** A new physical resource will be created */ WILL_CREATE = "WILL_CREATE", /** The existing physical resource will be replaced */ WILL_REPLACE = "WILL_REPLACE", /** The existing physical resource may be replaced */ MAY_REPLACE = "MAY_REPLACE", /** The existing physical resource will be destroyed */ WILL_DESTROY = "WILL_DESTROY", /** The existing physical resource will be removed from CloudFormation supervision */ WILL_ORPHAN = "WILL_ORPHAN", /** There is no change in this resource */ NO_CHANGE = "NO_CHANGE" } export interface Resource { Type: string; Properties?: { [name: string]: any; }; [key: string]: any; } /** * Change to a single resource between two CloudFormation templates * * This class can be mutated after construction. */ export declare class ResourceDifference implements IDifference<Resource> { readonly oldValue: Resource | undefined; readonly newValue: Resource | undefined; /** * Whether this resource was added */ readonly isAddition: boolean; /** * Whether this resource was removed */ readonly isRemoval: boolean; /** Property-level changes on the resource */ private readonly propertyDiffs; /** Changes to non-property level attributes of the resource */ private readonly otherDiffs; /** The resource type (or old and new type if it has changed) */ private readonly resourceTypes; constructor(oldValue: Resource | undefined, newValue: Resource | undefined, args: { resourceType: { oldType?: string; newType?: string; }; propertyDiffs: { [key: string]: PropertyDifference<any>; }; otherDiffs: { [key: string]: Difference<any>; }; }); get oldProperties(): PropertyMap | undefined; get newProperties(): PropertyMap | undefined; /** * Whether this resource was modified at all */ get isDifferent(): boolean; /** * Whether the resource was updated in-place */ get isUpdate(): boolean; get oldResourceType(): string | undefined; get newResourceType(): string | undefined; /** * All actual property updates */ get propertyUpdates(): { [key: string]: PropertyDifference<any>; }; /** * All actual "other" updates */ get otherChanges(): { [key: string]: Difference<any>; }; /** * Return whether the resource type was changed in this diff * * This is not a valid operation in CloudFormation but to be defensive we're going * to be aware of it anyway. */ get resourceTypeChanged(): boolean; /** * Return the resource type if it was unchanged * * If the resource type was changed, it's an error to call this. */ get resourceType(): string; /** * Replace a PropertyChange in this object * * This affects the property diff as it is summarized to users, but it DOES * NOT affect either the "oldValue" or "newValue" values; those still contain * the actual template values as provided by the user (they might still be * used for downstream processing). */ setPropertyChange(propertyName: string, change: PropertyDifference<any>): void; get changeImpact(): ResourceImpact; /** * Count of actual differences (not of elements) */ get differenceCount(): number; /** * Invoke a callback for each actual difference */ forEachDifference(cb: (type: 'Property' | 'Other', name: string, value: Difference<any> | PropertyDifference<any>) => any): void; } export declare function isPropertyDifference<T>(diff: Difference<T>): diff is PropertyDifference<T>;
the_stack
import { DeepPartial, Service } from "@bluelibs/core"; import { ObjectId } from "@bluelibs/ejson"; import { Collection, MONGO_BUNDLE_COLLECTION } from "./Collection"; import { Linker, LINK_STORAGE } from "@bluelibs/nova"; import * as MongoDB from "mongodb"; /** * This represents ObjectId from @bluelibs/ejson or from "mongodb"; */ export type ID = ObjectId | MongoDB.ObjectId; export type DocumentWithID = { _id?: ID }; type GenericObject = { [key: string]: any; }; type Linkable<T extends DocumentWithID = null> = | ID | (T extends null ? GenericObject : DeepPartial<T>); type CleanOptionsType = { /** * Delete the objects from the database as well. */ delete?: boolean; }; type LinkOptionsType = { /** * Only makes sense for relationships which are of type "many" and "direct". */ override?: boolean; /** * This applies to direct relationships, if true, the elements removed will be deleted from database. */ deleteOrphans?: boolean; }; type UnlinkOptionsType = { /** * Deletes the unlinked objects */ delete?: boolean; }; export type Unpacked<T> = T extends (infer U)[] ? U : T; /** * This class allows you to properly play with relationships */ export class LinkOperatorModel<T extends DocumentWithID = null> { protected relatedCollection: Collection<any>; protected linker: Linker; constructor( protected readonly collection: Collection<any>, protected readonly linkName: string ) { this.linker = collection.collection[LINK_STORAGE][linkName] as Linker; if (!this.linker) { throw new Error( `There's no link named: "${linkName}" inside "${collection.collectionName}"` ); } this.relatedCollection = this.linker.getLinkedCollection()[MONGO_BUNDLE_COLLECTION]; } /** * Use this function to clean all related links, with the ability to also delete them. * * @param rootId * @param options */ async clean(rootId: ID, options: CleanOptionsType = {}) { if (this.linker.isVirtual()) { await this.cleanVirtualLink(rootId, options); } else { await this.cleanDirectLink(rootId, options); } } /** * Create links between collections, it will automatically persist them as well. * * @param rootId * @param valueIds * @param options */ async link( rootId: ID, valueIds: Linkable<T> | Linkable<T>[], options: LinkOptionsType = {} ) { if (!Array.isArray(valueIds)) { valueIds = [valueIds]; } const ids = await this.getValueIdsObjects(valueIds as Linkable<T>[]); if (this.linker.isVirtual()) { await this.linkVirtual(ids, rootId); } else { await this.linkDirect(options, rootId, ids); } } /** * Unlink collections and optionally apply a deletion * @param fromId * @param valueIds * @param options */ async unlink( fromId: ID, valueIds: Linkable<T> | Linkable<T>[], options: UnlinkOptionsType = {} ) { if (!Array.isArray(valueIds)) { valueIds = [valueIds]; } const ids = await this.getValueIdsObjects(valueIds as Linkable<T>[]); if (this.linker.isVirtual()) { await this.unlinkVirtual(fromId, ids, options); } else { await this.unlinkDirect(fromId, ids, options); } } protected async unlinkDirect( rootId: ID, ids: ID[], options: UnlinkOptionsType ) { let orphanedIds = null; if (options.delete) { await this.relatedCollection.deleteMany({ _id: { $in: ids }, }); } if (this.linker.isMany()) { await this.collection.updateOne( { _id: rootId, }, { // @ts-ignore $pull: { [this.linker.linkStorageField]: ids, }, } ); } else { // TODO: throw error if specific unlink info? await this.collection.updateOne( { _id: rootId, }, { $set: { [this.linker.linkStorageField]: null }, } ); } } protected async unlinkVirtual( rootId: ID, ids: ID[], options: UnlinkOptionsType ) { if (options.delete) { await this.relatedCollection.deleteMany({ _id: { $in: ids }, }); } if (this.linker.isMany()) { await this.relatedCollection.updateMany( { _id: { $in: ids }, }, { // @ts-ignore $pull: { [this.linker.linkStorageField]: rootId, }, } ); } else { // TODO: delete? await this.relatedCollection.updateMany( { _id: { $in: ids }, }, { $set: { [this.linker.linkStorageField]: null, }, } ); } } protected async linkDirect(options: LinkOptionsType, rootId: ID, ids: ID[]) { let orphanedIds = null; if (options.deleteOrphans) { orphanedIds = await this.getOrphanedIds(rootId, ids); // array of ids } if (this.linker.isMany()) { await this.collection.updateOne( { _id: rootId, }, { [options.override ? "$set" : "$addToSet"]: { [this.linker.linkStorageField]: ids, }, } ); } else { await this.collection.updateOne( { _id: rootId, }, { $set: { [this.linker.linkStorageField]: ids[0] }, } ); // throw if valueIds > 0, will not work } if (orphanedIds) { await this.relatedCollection.deleteMany({ _id: { $in: orphanedIds }, }); } } protected async linkVirtual(ids: ID[], rootId: ID) { if (this.linker.isMany()) { await this.relatedCollection.updateMany( { _id: { $in: ids }, }, { // @ts-ignore $addToSet: { [this.linker.linkStorageField]: rootId, }, } ); } else { await this.relatedCollection.updateMany( { _id: { $in: ids }, }, { $set: { [this.linker.linkStorageField]: rootId, }, } ); } } private async getOrphanedIds(rootId: ID, ids: ID[]): Promise<ID[]> { const result = await this.collection.findOne( { _id: rootId }, { projection: { [this.linker.linkStorageField]: 1, }, } ); const orphanedIds = ids.filter((_id) => { let found = false; for (const id of result[this.linker.linkStorageField]) { if (id.toString() === _id.toString()) { found = true; break; } } // if it's not found in the new set it's orphaned will be deleted after return !found; }); // array of ids return orphanedIds; } /** * Since objects can be ids or objects, we can transform non-persisted objects into persisted ones and link them properly * @param linkables * @returns */ protected async getValueIdsObjects( linkables: Linkable<T>[] ): Promise<Array<ID>> { const result: Array<ID> = []; for (const linkable of linkables) { if (this.isID(linkable)) { result.push(linkable); } else { if (linkable._id) { result.push(linkable._id as ID); } else { const linkableInsertResult = await this.relatedCollection.insertOne( linkable ); linkable._id = linkableInsertResult.insertedId; result.push(linkableInsertResult.insertedId); } } } return result; } /** * Cleans the related data for direct links and optionally deletes the related elements in a cascade-like fashion. * * @param rootId * @param options */ protected async cleanDirectLink(rootId: ID, options: CleanOptionsType) { const linkStorage: string = this.linker.linkStorageField; if (this.linker.isMany()) { if (options.delete) { const result = await this.collection.findOne( { _id: rootId }, { projection: { [linkStorage]: 1 } } ); if (result[linkStorage]) { await this.relatedCollection.deleteMany({ _id: { $in: result[linkStorage] }, }); } } await this.collection.updateOne( { _id: rootId }, { $set: { [linkStorage]: [], }, } ); } else { if (options.delete) { const result = await this.collection.findOne( { _id: rootId }, { projection: { [linkStorage]: 1 } } ); if (result[linkStorage]) { await this.relatedCollection.deleteOne({ _id: result[linkStorage], }); } } await this.collection.updateOne( { _id: rootId }, { $set: { [linkStorage]: null, }, } ); } } /** * Cleans the related data for virtual/inversed links and optionally deletes the related elements in a cascade-like fashion. * * @param rootId * @param options */ protected async cleanVirtualLink(rootId: ID, options: CleanOptionsType) { const linkStorage: string = this.linker.linkStorageField; if (this.linker.isMany()) { if (options.delete) { await this.relatedCollection.deleteMany({ [this.linker.linkStorageField]: { $in: [rootId], }, }); } else { await this.relatedCollection.updateMany( { [this.linker.linkStorageField]: { $in: [rootId], }, }, { // @ts-ignore $pull: { [linkStorage]: { $in: [rootId] }, }, } ); } } else { if (options.delete) { await this.relatedCollection.deleteOne({ [this.linker.linkStorageField]: rootId, }); } else { await this.relatedCollection.updateOne( { [this.linker.linkStorageField]: rootId, }, { $set: { [this.linker.linkStorageField]: null, }, } ); } } } protected isID(id: ID | GenericObject): id is ID { return id instanceof ObjectId || id instanceof MongoDB.ObjectId; } }
the_stack
import { clone, groupBy } from '@antv/util'; import Graph from '../implement-graph'; const div = document.createElement('div'); div.id = 'combo-shape'; document.body.appendChild(div); const graphCfg = { container: div, width: 500, height: 600, groupByTypes: false, }; describe('simple data', () => { const simpleData = { nodes: [ { id: '0', x: 50, y: 20, comboId: 'a' }, { id: '1', x: 100, y: 20, comboId: 'a' }, { id: '2', x: 150, y: 30, comboId: 'b' }, { id: '3', x: 200, y: 30, comboId: 'b' } ], combos: [ { id: 'a', label: 'a', x: 100, y: 400 }, // initially collapsed { id: 'b', label: 'b-initially-collapsed', collapsed: true, x: 400, y: 400 }, // empty { id: 'c', label: 'c-empty', x: 300, y: 300 } ] } simpleData.nodes.forEach(node => { node.label = node.id }); let graph = new Graph(graphCfg); graph.read(clone(simpleData)); // 加几个测试标记圆点 const group = graph.getGroup(); const poses = [{ x: 100, y: 400 }, { x: 400, y: 400 }, { x: 300, y: 300 }]; poses.forEach(pos => { group.addShape('circle', { attrs: { r: 3, x: pos.x, y: pos.y, fill: '#f00' } }); group.addShape('text', { attrs: { text: `(${pos.x}, ${pos.y})`, fill: '#666', fontSize: 10, x: pos.x, y: pos.y + 14, textAlign: 'center' } }); }) it('render: combos and nodes with pos', () => { const comboModels = graph.getCombos().map(combo => combo.getModel()); expect(comboModels[0].x).toBe(100); expect(comboModels[0].y).toBe(400); expect(comboModels[1].x).toBe(400); expect(comboModels[1].y).toBe(400); expect(comboModels[2].x).toBe(300); expect(comboModels[2].y).toBe(300); const nodeModels = graph.getNodes().map(node => node.getModel()); expect(nodeModels[0].x).toBe(100 - 75 + 50); expect(nodeModels[0].y).toBe(400 - 20 + 20); expect(nodeModels[1].x).toBe(100 - 75 + 100); expect(nodeModels[1].y).toBe(400 - 20 + 20); expect(nodeModels[2].x).toBe(400 - 175 + 150); expect(nodeModels[2].y).toBe(400 - 30 + 30); expect(nodeModels[3].x).toBe(400 - 175 + 200); expect(nodeModels[3].y).toBe(400 - 30 + 30); }); it('render: combos without pos, nodes with pos', () => { graph.destroy(); const testData = clone(simpleData); testData.combos.forEach(combo => { delete combo.x; delete combo.y; }); graph = new Graph(graphCfg); graph.read(testData); const comboModels = graph.getCombos().map(combo => combo.getModel()); expect(comboModels[0].x).toBe(75); expect(comboModels[0].y).toBe(20); expect(comboModels[1].x).toBe(175); expect(comboModels[1].y).toBe(30); expect(comboModels[2].x).not.toBe(undefined); expect(comboModels[2].y).not.toBe(undefined); const nodeModels = graph.getNodes().map(node => node.getModel()); expect(nodeModels[0].x).toBe(50); expect(nodeModels[0].y).toBe(20); expect(nodeModels[1].x).toBe(100); expect(nodeModels[1].y).toBe(20); expect(nodeModels[2].x).toBe(150); expect(nodeModels[2].y).toBe(30); expect(nodeModels[3].x).toBe(200); expect(nodeModels[3].y).toBe(30); }); it('updateItem: combos from no pos update to pos', () => { const testData = clone(simpleData); testData.combos.forEach(combo => { delete combo.x; delete combo.y; }); graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); graph.updateItem('a', { ...poses[0] }) graph.updateItem('b', { ...poses[1] }) graph.updateItem('c', { ...poses[2] }) const comboModels = graph.getCombos().map(combo => combo.getModel()); expect(comboModels[0].x).toBe(100); expect(comboModels[0].y).toBe(400); expect(comboModels[1].x).toBe(400); expect(comboModels[1].y).toBe(400); expect(comboModels[2].x).toBe(300); expect(comboModels[2].y).toBe(300); const nodeModels = graph.getNodes().map(node => node.getModel()); expect(nodeModels[0].x).toBe(100 - 75 + 50); expect(nodeModels[0].y).toBe(400 - 20 + 20); expect(nodeModels[1].x).toBe(100 - 75 + 100); expect(nodeModels[1].y).toBe(400 - 20 + 20); expect(nodeModels[2].x).toBe(400 - 175 + 150); expect(nodeModels[2].y).toBe(400 - 30 + 30); expect(nodeModels[3].x).toBe(400 - 175 + 200); expect(nodeModels[3].y).toBe(400 - 30 + 30); }); it('updateItem: update the nodes inside expanded/collapsed combo', () => { const nodes = graph.getNodes(); const newNodePoses = [{ x: 50, y: 50 }, { x: 150, y: 150 }, { x: 450, y: 450 }, { x: 450, y: 400 }]; graph.updateItem(nodes[0], newNodePoses[0]); graph.updateItem(nodes[1], newNodePoses[1]); graph.updateItem(nodes[2], newNodePoses[2]); graph.updateItem(nodes[3], newNodePoses[3]); // 上面手动更新单个节点是不会触发相关 combo 更新的,需要调用下面方法。但是下面方法是根据数据绘制的位置,如何控制根据内部元素位置还是 combo 数据位置 // 是否加参数,内部更新 combo 或渲染 combo 时才用 combo 数据位置 graph.updateCombos(); const expectComboPoses = [ { x: (newNodePoses[0].x + newNodePoses[1].x) / 2, y: (newNodePoses[0].y + newNodePoses[1].y) / 2, }, { // x: (newNodePoses[2].x + newNodePoses[3].x) / 2, // y: (newNodePoses[2].y + newNodePoses[3].y) / 2, // 该 combo 是 collapsed,因此不受节点位置影响 x: 400, y: 400 } ] const comboModels = graph.getCombos().map(combo => combo.getModel()); expect(comboModels[0].x).toBe(expectComboPoses[0].x); expect(comboModels[0].y).toBe(expectComboPoses[0].y); expect(comboModels[1].x).toBe(expectComboPoses[1].x); expect(comboModels[1].y).toBe(expectComboPoses[1].y); }); it('1 initial collapsed with pos, 2 expand, 3 move combo, 4 move node, 5 collapse, 6 move combo, 7 move node', (done) => { graph.destroy(); const testData = clone(simpleData); graph = new Graph(graphCfg); graph.read(testData); // initial collapsed with pos const combo = graph.findById('b'); const model = combo.getModel(); expect(model.x).toBe(400); expect(model.y).toBe(400); setTimeout(() => { // 2 epxand graph.collapseExpandCombo('b'); expect(model.x).toBe(400); expect(model.y).toBe(400); // 3 move combo graph.updateItem(combo, { x: 200, y: 100 }); expect(model.x).toBe(200); expect(model.y).toBe(100); // 4 move node const node = graph.findById('2'); graph.updateItem(node, { x: 300, y: 200 }); graph.updateCombos(); expect(node.getModel().x).toBe(300); expect(node.getModel().y).toBe(200); expect(model.x).toBe(262.5); expect(model.y).toBe(150); setTimeout(() => { expect(Math.abs(combo.getKeyShape().attr('r') - 102) < 1).toBe(true); // 5 collapse graph.collapseExpandCombo('b'); expect(model.x).toBe(262.5); expect(model.y).toBe(150); setTimeout(() => { expect(Math.abs(combo.getKeyShape().attr('r') - 35) < 1).toBe(true); // 6 move combo graph.updateItem(combo, { x: 400, y: 50 }); expect(model.x).toBe(400); expect(model.y).toBe(50); expect(Math.abs(combo.getKeyShape().attr('r') - 35) < 1).toBe(true); // 7 move node const node = graph.findById('3'); graph.updateItem(node, { x: 150, y: 400 }); graph.updateCombos(); expect(node.getModel().x).toBe(150); expect(node.getModel().y).toBe(400); // 收起状态下移动内部节点,combo 不会更新位置,因为计算 bbox 的时候忽略了隐藏元素 expect(model.x).toBe(400); expect(model.y).toBe(50); graph.collapseExpandCombo('b'); setTimeout(() => { expect(model.x).toBe(293.75); expect(model.y).toBe(250); done(); }, 500) }, 500) }, 500) }, 500) }); it('1 initial collapsed without pos, 2 expand, 3 move combo, 4 move node, 5 collapse, 6 move combo, 7 move node', (done) => { const testData = clone(simpleData); testData.combos.forEach(combo => { delete combo.x; delete combo.y; }); graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); // initial collapsed with pos const combo = graph.findById('b'); const model = combo.getModel(); expect(model.x).toBe(175); expect(model.y).toBe(30); setTimeout(() => { // 2 epxand graph.collapseExpandCombo('b'); setTimeout(() => { expect(model.x).toBe(175); expect(model.y).toBe(30); // 3 move combo graph.updateItem(combo, { x: 200, y: 100 }); expect(model.x).toBe(200); expect(model.y).toBe(100); // 4 move node const node = graph.findById('2'); graph.updateItem(node, { x: 300, y: 200 }); graph.updateCombos(); expect(node.getModel().x).toBe(300); expect(node.getModel().y).toBe(200); expect(model.x).toBe(262.5); expect(model.y).toBe(150); setTimeout(() => { expect(Math.abs(combo.getKeyShape().attr('r') - 102) < 1).toBe(true); // 5 collapse graph.collapseExpandCombo('b'); setTimeout(() => { expect(model.x).toBe(262.5); expect(model.y).toBe(150); expect(Math.abs(combo.getKeyShape().attr('r') - 35) < 1).toBe(true); // 6 7 与上一个 it 内容相同,不再重复 done(); }, 500); }, 500); }, 500); }, 500); }); it('1 initial expand with pos, 2 move node, 3 move combo, 4 collapse, 5 move node, 6 expand', (done) => { graph.destroy(); const testData = clone(simpleData); graph = new Graph(graphCfg); graph.read(testData); // 1 initial expand with pos const combo = graph.findById('a'); const model = combo.getModel(); expect(model.x).toBe(100); expect(model.y).toBe(400); // 2 move node const node = graph.findById('1'); const node1Model = node.getModel(); const node0Model = graph.findById('0').getModel(); graph.updateItem(node, { x: 100, y: 100 }); graph.updateCombos(); expect(node.getModel().x).toBe(100); expect(node.getModel().y).toBe(100); expect(model.x).toBe(87.5); expect(model.y).toBe(250); setTimeout(() => { expect(Math.abs(combo.getKeyShape().attr('r') - 187) < 1).toBe(true); // 3 move combo graph.updateItem(combo, { x: 300, y: 400 }); expect(model.x).toBe(300); expect(model.y).toBe(400); expect(node1Model.x).toBe(300 - 87.5 + 100); expect(node1Model.y).toBe(400 - 250 + 100); expect(node0Model.x).toBe(287.5); expect(node0Model.y).toBe(550); // 4 collapse graph.collapseExpandCombo('a'); setTimeout(() => { expect(Math.abs(combo.getKeyShape().attr('r') - 35) < 1).toBe(true); expect(model.x).toBe(300); expect(model.y).toBe(400); // 5 move node, collapse 状态下移动节点,combo 位置不变 graph.updateItem('0', { x: 50, y: 50 }); expect(node0Model.x).toBe(50); expect(node0Model.y).toBe(50); expect(model.x).toBe(300); expect(model.y).toBe(400); // 6 expand graph.collapseExpandCombo('a'); setTimeout(() => { expect(Math.abs(combo.getKeyShape().attr('r') - 204) < 1).toBe(true); expect(model.x).toBe(181.25); expect(model.y).toBe(150); done(); }, 500) }, 500) }, 500); }); it('1 initial expand without pos, 2 move node, 3 move combo, 4 collapse, 5 move node, 6 expand', (done) => { const testData = clone(simpleData); testData.combos.forEach(combo => { delete combo.x; delete combo.y; }); graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); // 1 initial collapsed without pos const combo = graph.findById('a'); const model = combo.getModel(); expect(model.x).toBe(75); expect(model.y).toBe(20); setTimeout(() => { // 2 move node const node = graph.findById('1'); const node1Model = node.getModel(); const node0Model = graph.findById('0').getModel(); graph.updateItem(node, { x: 300, y: 200 }); graph.updateCombos(); expect(node1Model.x).toBe(300); expect(node1Model.y).toBe(200); expect(model.x).toBe(175); expect(model.y).toBe(110); setTimeout(() => { expect(Math.abs(combo.getKeyShape().attr('r') - 193) < 1).toBe(true); // 3 move combo graph.updateItem(combo, { x: 50, y: 350 }); expect(model.x).toBe(50); expect(model.y).toBe(350); expect(node1Model.x).toBe(50 - 175 + 300); expect(node1Model.y).toBe(350 - 110 + 200); expect(node0Model.x).toBe(-75); expect(node0Model.y).toBe(260); // 4 collapse graph.collapseExpandCombo('a'); setTimeout(() => { expect(Math.abs(combo.getKeyShape().attr('r') - 35) < 1).toBe(true); expect(model.x).toBe(50); expect(model.y).toBe(350); // 5 expand graph.collapseExpandCombo('a'); setTimeout(() => { expect(Math.abs(combo.getKeyShape().attr('r') - 193) < 1).toBe(true); expect(model.x).toBe(50); expect(model.y).toBe(350); graph.destroy(); done(); }, 500); }, 500); }, 500); }, 500); }); }); describe('hierarchy data 1: combo A has one child: an empty combo B', () => { const data = { combos: [ { id: 'A', x: 100, y: 200, label: 'A' }, { id: 'B', x: 300, y: 400, label: 'B', parentId: 'A' }, ] } let graph = new Graph(graphCfg); graph.read(clone(data)); let comboA = graph.findById('A'); let comboAModel = comboA.getModel(); let comboB = graph.findById('B'); let comboBModel = comboB.getModel(); it('nested combo has different initial pos', () => { expect(comboAModel.x).toBe(100); expect(comboAModel.y).toBe(200); // the child combo follow the parent expect(comboBModel.x).toBe(100); expect(comboBModel.y).toBe(200); }); it('move child empty combo B', (done) => { graph.updateItem('B', { x: 330, y: 120 }); expect(comboBModel.x).toBe(330); expect(comboBModel.y).toBe(120); // the parent combo follow the child graph.updateCombos(); expect(comboAModel.x).toBe(330); expect(comboAModel.y).toBe(120); // collpase combo B graph.collapseExpandCombo('B'); setTimeout(() => { // move combo B graph.updateItem('B', { x: 430, y: 200 }); expect(comboBModel.x).toBe(430); expect(comboBModel.y).toBe(200); // the parrent follow the child graph.updateCombos(); expect(comboAModel.x).toBe(430); expect(comboAModel.y).toBe(200); done() }, 500); }); it('move parent combo A', (done) => { graph.updateItem('A', { x: 50, y: 50 }); expect(comboAModel.x).toBe(50); expect(comboAModel.y).toBe(50); // the child follow the parent expect(comboBModel.x).toBe(50); expect(comboBModel.y).toBe(50); // expand B graph.collapseExpandCombo('B'); setTimeout(() => { // no changes expect(comboAModel.x).toBe(50); expect(comboAModel.y).toBe(50); expect(comboBModel.x).toBe(50); expect(comboBModel.y).toBe(50); done(); }, 500); }); it('parent combo without pos, child combo with pos', () => { const testData = clone(data); delete testData.combos[0].x; delete testData.combos[0].y; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); comboA = graph.findById('A'); comboAModel = comboA.getModel(); comboB = graph.findById('B'); comboBModel = comboB.getModel(); expect(comboBModel.x).toBe(300); expect(comboBModel.y).toBe(400); // A has no position, follows the child expect(comboAModel.x).toBe(300); expect(comboAModel.y).toBe(400); // move B graph.updateItem('B', { x: 300, y: 100 }); expect(comboBModel.x).toBe(300); expect(comboBModel.y).toBe(100); // A follows the child graph.updateCombos(); expect(comboAModel.x).toBe(300); expect(comboAModel.y).toBe(100); // move A graph.updateItem('A', { x: 400, y: 120 }); expect(comboBModel.x).toBe(400); expect(comboBModel.y).toBe(120); // B follows the parent expect(comboAModel.x).toBe(400); expect(comboAModel.y).toBe(120); }); it('parent combo with pos, child combo without', () => { const testData = clone(data); delete testData.combos[1].x; delete testData.combos[1].y; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); comboA = graph.findById('A'); comboAModel = comboA.getModel(); comboB = graph.findById('B'); comboBModel = comboB.getModel(); expect(comboBModel.x).toBe(100); expect(comboBModel.y).toBe(200); // A has no position, follows the child expect(comboAModel.x).toBe(100); expect(comboAModel.y).toBe(200); }); it('parent combo collapsed with pos, child combo with pos', (done) => { const testData = clone(data); testData.combos[0].collapsed = true; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); comboA = graph.findById('A'); comboAModel = comboA.getModel(); comboB = graph.findById('B'); comboBModel = comboB.getModel(); expect(comboBModel.x).toBe(100); expect(comboBModel.y).toBe(200); // A has no position, follows the child expect(comboAModel.x).toBe(100); expect(comboAModel.y).toBe(200); // move A graph.updateItem('A', { x: 300, y: 350 }); expect(comboAModel.x).toBe(300); expect(comboAModel.y).toBe(350); // child follows A expect(comboBModel.x).toBe(300); expect(comboBModel.y).toBe(350); // expand A graph.collapseExpandCombo('A'); setTimeout(() => { expect(comboAModel.x).toBe(300); expect(comboAModel.y).toBe(350); // child follows A expect(comboBModel.x).toBe(300); expect(comboBModel.y).toBe(350); graph.destroy(); done() }, 500); }); }); describe('hierarchy data 2: combo A has 2 children: an empty combo B, a node', () => { const data = { nodes: [{ id: '0', x: 10, y: 20, comboId: 'A' }], combos: [ { id: 'A', x: 100, y: 200, label: 'A' }, { id: 'B', x: 300, y: 400, label: 'B', parentId: 'A' }, ] } let graph = new Graph(graphCfg); graph.read(clone(data)); let comboA = graph.findById('A'); let comboAModel = comboA.getModel(); let comboB = graph.findById('B'); let comboBModel = comboB.getModel(); let node = graph.findById('0'); let nodeModel = node.getModel(); it('nested combo has different initial pos', () => { expect(comboAModel.x).toBe(100); expect(comboAModel.y).toBe(200); // the child combo follow the parent expect(comboBModel.x).toBe(232.75); expect(comboBModel.y).toBe(377.75); expect(nodeModel.x).toBe(-57.25); expect(nodeModel.y).toBe(-2.25); }); it('move child empty combo B', () => { graph.updateItem('B', { x: 330, y: 120 }); expect(comboBModel.x).toBe(330); expect(comboBModel.y).toBe(120); // the sibling node is not changed expect(nodeModel.x).toBe(-57.25); expect(nodeModel.y).toBe(-2.25); // the parent combo follows the children graph.updateCombos(); expect(comboAModel.x).toBe(148.625); expect(comboAModel.y).toBe(71.125); }); it('move parent combo A', () => { // done graph.updateItem('A', { x: 450, y: 350 }); expect(comboAModel.x).toBe(450); expect(comboAModel.y).toBe(350); // the child follow the parent expect(comboBModel.x).toBe(450 - 148.625 + 330); expect(comboBModel.y).toBe(350 - 71.125 + 120); expect(nodeModel.x).toBe(450 - 148.625 - 57.25); expect(nodeModel.y).toBe(350 - 71.125 - 2.25); }); it('parent combo without pos, children with pos', () => { const testData = clone(data); delete testData.combos[0].x; delete testData.combos[0].y; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); comboA = graph.findById('A'); comboAModel = comboA.getModel(); comboB = graph.findById('B'); comboBModel = comboB.getModel(); node = graph.findById('0'); nodeModel = node.getModel(); expect(comboBModel.x).toBe(300); expect(comboBModel.y).toBe(400); expect(nodeModel.x).toBe(10); expect(nodeModel.y).toBe(20); // A has no position, follows the child expect(comboAModel.x).toBe(167.25); expect(comboAModel.y).toBe(222.25); }); it('parent combo with pos, child combo without pos', () => { const testData = clone(data); delete testData.combos[1].x; delete testData.combos[1].y; delete testData.nodes[0].x; delete testData.nodes[0].y; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); comboA = graph.findById('A'); comboAModel = comboA.getModel(); comboB = graph.findById('B'); comboBModel = comboB.getModel(); node = graph.findById('0'); nodeModel = node.getModel(); expect(comboAModel.x).toBe(100); expect(comboAModel.y).toBe(200); // B and 0 have no position, follow the parent // the position is randomed, but inside the parent parent expect(comboBModel.x).not.toBe(NaN); expect(comboBModel.y).not.toBe(NaN); expect(nodeModel.x).not.toBe(NaN); expect(nodeModel.y).not.toBe(NaN); }); it('parent combo collapsed with pos, child combo with pos', () => { const testData = clone(data); testData.combos[0].collapsed = true; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); comboA = graph.findById('A'); comboAModel = comboA.getModel(); comboB = graph.findById('B'); comboBModel = comboB.getModel(); expect(comboAModel.x).toBe(100); expect(comboAModel.y).toBe(200); expect(comboBModel.x).not.toBe(NaN); expect(comboBModel.y).not.toBe(NaN); expect(nodeModel.x).not.toBe(NaN); expect(nodeModel.y).not.toBe(NaN); graph.destroy(); }); }); describe('hierarchy data3: combo A has 2 children: combo B with 2 nodes, 2 nodes', () => { const data = { nodes: [ { id: '0', x: 140, y: 120, comboId: 'A' }, { id: '1', x: 150, y: 130, comboId: 'A' }, { id: '2', x: 180, y: 220, comboId: 'B' }, { id: '3', x: 190, y: 230, comboId: 'B' } ], combos: [ { id: 'A', x: 100, y: 200, label: 'A' }, { id: 'B', x: 300, y: 400, label: 'B', parentId: 'A' }, ] } data.nodes.forEach(node => node.label = node.id); let graph = new Graph(graphCfg); graph.read(clone(data)); let comboA = graph.findById('A'); let comboAModel = comboA.getModel(); let comboB = graph.findById('B'); let comboBModel = comboB.getModel(); let nodes = graph.getNodes(); let nodeModels = nodes.map(node => node.getModel()); it('nested combo has different initial pos', () => { expect(comboAModel.x).toBe(100); expect(comboAModel.y).toBe(200); // the child combo follow the parent expect(comboBModel.x).toBe(161.7898448916085); expect(comboBModel.y).toBe(321.7898448916085); expect(nodeModels[0].x).toBe(1.7898448916085101); expect(nodeModels[0].y).toBe(41.78984489160848); expect(nodeModels[1].x).toBe(11.78984489160851); expect(nodeModels[1].y).toBe(51.78984489160848); expect(nodeModels[2].x).toBe(156.7898448916085); expect(nodeModels[2].y).toBe(316.7898448916085); expect(nodeModels[3].x).toBe(166.7898448916085); expect(nodeModels[3].y).toBe(326.7898448916085); }); it('move child combo B', () => { graph.updateItem('B', { x: 330, y: 120 }); graph.updateCombos(); expect(comboBModel.x).toBe(330); expect(comboBModel.y).toBe(120); // the sibling node is not changed expect(nodeModels[0].x).toBe(1.7898448916085101); expect(nodeModels[0].y).toBe(41.78984489160848); expect(nodeModels[1].x).toBe(11.78984489160851); expect(nodeModels[1].y).toBe(51.78984489160848); // the children nodes of combo B follow B expect(nodeModels[2].x).toBe(325); expect(nodeModels[2].y).toBe(115); expect(nodeModels[3].x).toBe(335); expect(nodeModels[3].y).toBe(125); // the parent combo follows the children expect(comboAModel.x).toBe(184.10507755419576); expect(comboAModel.y).toBe(99.10507755419573); }); it('move parent combo A', (done) => { graph.updateItem('A', { x: 150, y: 150 }); expect(comboAModel.x).toBe(150); expect(comboAModel.y).toBe(150); // the child follow the parent const dx = 150 - 184.10507755419576, dy = 150 - 99.10507755419573; expect(comboBModel.x).toBe(dx + 330); expect(comboBModel.y).toBe(dy + 120); expect(nodeModels[0].x).toBe(dx + 1.7898448916085101); expect(nodeModels[0].y).toBe(dy + 41.78984489160848); expect(nodeModels[1].x).toBe(dx + 11.78984489160851); expect(nodeModels[1].y).toBe(dy + 51.78984489160848); expect(nodeModels[2].x).toBe(dx + 325); expect(nodeModels[2].y).toBe(dy + 115); expect(nodeModels[3].x).toBe(dx + 335); expect(nodeModels[3].y).toBe(dy + 125); // collapse B graph.collapseExpandCombo('B'); setTimeout(() => { // move B graph.updateItem('B', { x: 50, y: 50 }); expect(comboBModel.x).toBe(50); expect(comboBModel.y).toBe(50); graph.updateCombos(); setTimeout(() => { expect(Math.abs(comboA.getKeyShape().attr('r') - 105) < 1).toBe(true); expect(comboAModel.x).toBe(21.092383668706375); expect(comboAModel.y).toBe(64.09238366870638); done(); }, 500); }, 500); }); it('parent combo without pos, children with pos', () => { const testData = clone(data); delete testData.combos[0].x; delete testData.combos[0].y; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); comboA = graph.findById('A'); comboAModel = comboA.getModel(); comboB = graph.findById('B'); comboBModel = comboB.getModel(); nodes = graph.getNodes(); nodeModels = nodes.map(node => node.getModel()); expect(comboBModel.x).toBe(300); expect(comboBModel.y).toBe(400); expect(nodeModels[0].x).toBe(data.nodes[0].x); expect(nodeModels[0].y).toBe(data.nodes[0].y); expect(nodeModels[1].x).toBe(data.nodes[1].x); expect(nodeModels[1].y).toBe(data.nodes[1].y); // 2 3 follows B expect(nodeModels[2].x).toBe(295); expect(nodeModels[2].y).toBe(395); expect(nodeModels[3].x).toBe(305); expect(nodeModels[3].y).toBe(405); // A has no position, follows the child expect(comboAModel.x).toBe(238.2101551083915); expect(comboAModel.y).toBe(278.2101551083915); }); it('parent combo with pos, child combo without pos', () => { const testData = clone(data); delete testData.combos[1].x; delete testData.combos[1].y; testData.nodes.forEach(node => { delete node.x; delete node.y; }); graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); comboA = graph.findById('A'); comboAModel = comboA.getModel(); comboB = graph.findById('B'); comboBModel = comboB.getModel(); nodes = graph.getNodes(); nodeModels = nodes.map(node => node.getModel()); expect(comboAModel.x).toBe(100); expect(comboAModel.y).toBe(200); // B and nodes have no position, follow the parent expect(comboBModel.x).toBe(100); expect(comboBModel.y).toBe(200); nodeModels.forEach(nodeModel => { expect(nodeModel.x).toBe(100); expect(nodeModel.y).toBe(200); }); // move node 3 graph.updateItem('3', { x: 300, y: 400 }); expect(nodeModels[3].x).toBe(300); expect(nodeModels[3].y).toBe(400); graph.updateCombos(); // B and A follow the change expect(comboBModel.x).toBe((100 + 300) / 2); expect(comboBModel.y).toBe((200 + 400) / 2); expect(comboAModel.x).toBe((100 + 300) / 2); expect(comboAModel.y).toBe((200 + 400) / 2); }); it('parent combo collapsed with pos, child combo with pos', (done) => { const testData = clone(data); testData.combos[0].collapsed = true; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); comboA = graph.findById('A'); comboAModel = comboA.getModel(); comboB = graph.findById('B'); comboBModel = comboB.getModel(); nodes = graph.getNodes(); nodeModels = nodes.map(node => node.getModel()); expect(comboAModel.x).toBe(100); expect(comboAModel.y).toBe(200); setTimeout(() => { // expand A graph.collapseExpandCombo('A'); setTimeout(() => { expect(comboB.isVisible()).toBe(true); // the child combo follow the parent expect(comboBModel.x).toBe(161.7898448916085); expect(comboBModel.y).toBe(321.7898448916085); expect(nodeModels[0].x).toBe(1.7898448916085101); expect(nodeModels[0].y).toBe(41.78984489160848); expect(nodeModels[1].x).toBe(11.78984489160851); expect(nodeModels[1].y).toBe(51.78984489160848); expect(nodeModels[2].x).toBe(156.7898448916085); expect(nodeModels[2].y).toBe(316.7898448916085); expect(nodeModels[3].x).toBe(166.7898448916085); expect(nodeModels[3].y).toBe(326.7898448916085); graph.destroy(); done() }, 500) }, 500); }); }); describe('hierarchy data4: combo A has 2 children: combo B with 2 nodes, 2 nodes', () => { const data = { combos: [ { id: 'A', x: 100, y: 200, label: 'A' }, { id: 'B', x: 300, y: 400, label: 'B', parentId: 'A' }, { id: 'C', x: 150, y: 100, label: 'C', parentId: 'A' }, ] } let graph = new Graph(graphCfg); graph.read(clone(data)); let combos = [graph.findById('A'), graph.findById('B'), graph.findById('C')]; // graph.getCombos 返回的不是数据顺序 let comboModels = combos.map(combo => combo.getModel()); it('nested combo has different initial pos', () => { expect(comboModels[0].x).toBe(100); expect(comboModels[0].y).toBe(200); // the child combo follow the parent expect(comboModels[1].x).toBe(175); expect(comboModels[1].y).toBe(350); expect(comboModels[2].x).toBe(25); expect(comboModels[2].y).toBe(50); }); it('move child combo B', () => { graph.updateItem('B', { x: 130, y: 120 }); graph.updateCombos(); expect(comboModels[1].x).toBe(130); expect(comboModels[1].y).toBe(120); // the sibling node is not changed expect(comboModels[2].x).toBe(25); expect(comboModels[2].y).toBe(50); // the parent combo follows the children expect(comboModels[0].x).toBe(77.5); expect(comboModels[0].y).toBe(85); expect(Math.abs(combos[0].getKeyShape().attr('r') - 240) < 1).toBe(true); }); it('move parent combo A', () => { graph.updateItem('A', { x: 150, y: 150 }); expect(comboModels[0].x).toBe(150); expect(comboModels[0].y).toBe(150); // the child follow the parent const dx = 150 - 77.5, dy = 150 - 85; expect(comboModels[1].x).toBe(dx + 130); expect(comboModels[1].y).toBe(dy + 120); expect(comboModels[2].x).toBe(dx + 25); expect(comboModels[2].y).toBe(dy + 50); }); it('parent combo without pos, children with pos', () => { const testData = clone(data); delete testData.combos[0].x; delete testData.combos[0].y; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); combos = [graph.findById('A'), graph.findById('B'), graph.findById('C')]; comboModels = combos.map(combo => combo.getModel()); expect(comboModels[1].x).toBe(300); expect(comboModels[1].y).toBe(400); expect(comboModels[2].x).toBe(150); expect(comboModels[2].y).toBe(100); // A has no position, follows the child expect(comboModels[0].x).toBe((300 + 150) / 2); expect(comboModels[0].y).toBe((400 + 100) / 2); }); it('parent combo with pos, child combo without pos', () => { const testData = clone(data); delete testData.combos[1].x; delete testData.combos[1].y; delete testData.combos[2].x; delete testData.combos[2].y; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); combos = [graph.findById('A'), graph.findById('B'), graph.findById('C')]; comboModels = combos.map(combo => combo.getModel()); expect(comboModels[0].x).toBe(100); expect(comboModels[0].y).toBe(200); expect(comboModels[1].x).not.toBe(NaN); expect(comboModels[1].y).not.toBe(NaN); expect(comboModels[2].x).not.toBe(NaN); expect(comboModels[2].y).not.toBe(NaN); // move node B and C graph.updateItem('B', { x: 300, y: 400 }); graph.updateItem('C', { x: 200, y: 400 }); expect(comboModels[1].x).toBe(300); expect(comboModels[1].y).toBe(400); expect(comboModels[2].x).toBe(200); expect(comboModels[2].y).toBe(400); graph.updateCombos(); expect(comboModels[0].x).toBe((300 + 200) / 2); expect(comboModels[0].y).toBe((400 + 400) / 2); }); it('parent combo collapsed with pos, child combo with pos', (done) => { const testData = clone(data); testData.combos[0].collapsed = true; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); combos = [graph.findById('A'), graph.findById('B'), graph.findById('C')]; comboModels = combos.map(combo => combo.getModel()); expect(comboModels[0].x).toBe(100); expect(comboModels[0].y).toBe(200); setTimeout(() => { // expand A graph.collapseExpandCombo('A'); setTimeout(() => { expect(combos[1].isVisible()).toBe(true); expect(combos[2].isVisible()).toBe(true); // the child combo follow the parent expect(comboModels[1].x).toBe(175); expect(comboModels[1].y).toBe(350); expect(comboModels[2].x).toBe(25); expect(comboModels[2].y).toBe(50); graph.destroy(); done(); }, 500) }, 500); }); }); describe('hierarchy data5: combo A has 2 children: combo B with 2 nodes, 2 nodes', () => { const data = { nodes: [ { id: '0', x: 50, y: 50, label: '0', comboId: 'B' }, { id: '1', x: 150, y: 50, label: '1', comboId: 'B' }, ], combos: [ { id: 'A', x: 100, y: 200, label: 'A' }, { id: 'B', x: 300, y: 400, label: 'B', parentId: 'A' }, { id: 'C', x: 250, y: 300, label: 'C', parentId: 'A' }, ] } let graph = new Graph(graphCfg); graph.read(clone(data)); let combos = [graph.findById('A'), graph.findById('B'), graph.findById('C')]; // graph.getCombos 返回的不是数据顺序 let comboModels = combos.map(combo => combo.getModel()); let node0Model = graph.findById('0').getModel(); let node1Model = graph.findById('1').getModel(); it('nested combo has different initial pos', () => { expect(comboModels[0].x).toBe(100); expect(comboModels[0].y).toBe(200); // the child combo follow the parent expect(comboModels[1].x).toBe(100); expect(comboModels[1].y).toBe(224.29780138165995); expect(comboModels[2].x).toBe(50); expect(comboModels[2].y).toBe(124.29780138165995); expect(node0Model.x).toBe(50); expect(node0Model.y).toBe(224.29780138165995); expect(node1Model.x).toBe(150); expect(node1Model.y).toBe(224.29780138165995); }); it('move child combo B', (done) => { graph.updateItem('B', { x: 130, y: 120 }); graph.updateCombos(); expect(comboModels[1].x).toBe(130); expect(comboModels[1].y).toBe(120); // the sibling node is not changed expect(comboModels[2].x).toBe(50); expect(comboModels[2].y).toBe(124.29780138165995); // the parent combo follows the children setTimeout(() => { expect(comboModels[0].x).toBe(115.70219861834002); expect(comboModels[0].y).toBe(120); expect(Math.abs(combos[0].getKeyShape().attr('r') - 157) < 1).toBe(true); done(); }, 500) }); it('move parent combo A', () => { graph.updateItem('A', { x: 150, y: 150 }); expect(comboModels[0].x).toBe(150); expect(comboModels[0].y).toBe(150); // the child follow the parent const dx = 150 - 115.70219861834002, dy = 150 - 120; expect(comboModels[1].x).toBe(dx + 130); expect(comboModels[1].y).toBe(dy + 120); expect(comboModels[2].x).toBe(dx + 50); expect(comboModels[2].y).toBe(dy + 124.29780138165995); }); it('parent combo without pos, children with pos', () => { const testData = clone(data); delete testData.combos[0].x; delete testData.combos[0].y; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); combos = [graph.findById('A'), graph.findById('B'), graph.findById('C')]; comboModels = combos.map(combo => combo.getModel()); expect(comboModels[1].x).toBe(300); expect(comboModels[1].y).toBe(400); expect(comboModels[2].x).toBe(250); expect(comboModels[2].y).toBe(300); // A has no position, follows the child expect(comboModels[0].x).toBe(300); expect(comboModels[0].y).toBe(375.70219861834005); }); it('parent combo with pos, child combo without pos', () => { const testData = clone(data); delete testData.combos[1].x; delete testData.combos[1].y; delete testData.combos[2].x; delete testData.combos[2].y; testData.nodes.forEach(node => { delete node.x; delete node.y; }) graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); combos = [graph.findById('A'), graph.findById('B'), graph.findById('C')]; comboModels = combos.map(combo => combo.getModel()); expect(comboModels[0].x).toBe(100); expect(comboModels[0].y).toBe(200); expect(comboModels[1].x).not.toBe(NaN); expect(comboModels[1].y).not.toBe(NaN); expect(comboModels[2].x).not.toBe(NaN); expect(comboModels[2].y).not.toBe(NaN); // move node B and C graph.updateItem('B', { x: 300, y: 400 }); graph.updateItem('C', { x: 200, y: 400 }); expect(comboModels[1].x).toBe(300); expect(comboModels[1].y).toBe(400); expect(comboModels[2].x).toBe(200); expect(comboModels[2].y).toBe(400); graph.updateCombos(); expect(comboModels[0].x).toBe(252.42462120245875); expect(comboModels[0].y).toBe(400); }); it('parent combo collapsed with pos, child combo with pos', (done) => { const testData = clone(data); testData.combos[0].collapsed = true; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); combos = [graph.findById('A'), graph.findById('B'), graph.findById('C')]; comboModels = combos.map(combo => combo.getModel()); expect(comboModels[0].x).toBe(100); expect(comboModels[0].y).toBe(200); setTimeout(() => { // expand A graph.collapseExpandCombo('A'); setTimeout(() => { expect(combos[1].isVisible()).toBe(true); expect(combos[2].isVisible()).toBe(true); // the child combo follow the parent expect(comboModels[1].x).toBe(100); expect(comboModels[1].y).toBe(224.29780138165995); expect(comboModels[2].x).toBe(50); expect(comboModels[2].y).toBe(124.29780138165995); graph.destroy(); done() }, 500); }, 500); }); }); describe('hierarchy data6: combo A has 2 children: combo B with 2 nodes, 2 nodes', () => { const data = { combos: [ { id: 'A', x: 100, y: 200, label: 'A' }, { id: 'B', x: 300, y: 400, label: 'B', parentId: 'A' }, { id: 'C', x: 400, y: 500, label: 'C', parentId: 'B' }, ] } let graph = new Graph(graphCfg); graph.read(clone(data)); let combos = [graph.findById('A'), graph.findById('B'), graph.findById('C')]; // graph.getCombos 返回的不是数据顺序 let comboModels = combos.map(combo => combo.getModel()); it('nested combo has different initial pos', () => { expect(comboModels[0].x).toBe(100); expect(comboModels[0].y).toBe(200); // the child combo follow the parent expect(comboModels[1].x).toBe(100); expect(comboModels[1].y).toBe(200); expect(comboModels[2].x).toBe(100); expect(comboModels[2].y).toBe(200); }); it('move child combo B', (done) => { graph.updateItem('B', { x: 130, y: 120 }); graph.updateCombos(); expect(comboModels[1].x).toBe(130); expect(comboModels[1].y).toBe(120); // child follows expect(comboModels[2].x).toBe(130); expect(comboModels[2].y).toBe(120); // the parent combo follows the children setTimeout(() => { expect(comboModels[0].x).toBe(130); expect(comboModels[0].y).toBe(120); expect(Math.abs(combos[0].getKeyShape().attr('r') - 130) < 1).toBe(true); done(); }, 500) }); it('move parent combo A', () => { graph.updateItem('A', { x: 150, y: 150 }); expect(comboModels[0].x).toBe(150); expect(comboModels[0].y).toBe(150); // the child follow the parent expect(comboModels[1].x).toBe(150); expect(comboModels[1].y).toBe(150); expect(comboModels[2].x).toBe(150); expect(comboModels[2].y).toBe(150); }); it('parent combo without pos, B and C has position', () => { const testData = clone(data); delete testData.combos[0].x; delete testData.combos[0].y; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); combos = [graph.findById('A'), graph.findById('B'), graph.findById('C')]; comboModels = combos.map(combo => combo.getModel()); // follow B expect(comboModels[1].x).toBe(300); expect(comboModels[1].y).toBe(400); expect(comboModels[2].x).toBe(300); expect(comboModels[2].y).toBe(400); // A has no position, follows the child expect(comboModels[0].x).toBe(300); expect(comboModels[0].y).toBe(400); }); it('A and B combo without pos, C has position', () => { const testData = clone(data); delete testData.combos[0].x; delete testData.combos[0].y; delete testData.combos[1].x; delete testData.combos[1].y; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); combos = [graph.findById('A'), graph.findById('B'), graph.findById('C')]; comboModels = combos.map(combo => combo.getModel()); // follow C expect(comboModels[1].x).toBe(400); expect(comboModels[1].y).toBe(500); expect(comboModels[2].x).toBe(400); expect(comboModels[2].y).toBe(500); // A has no position, follows the child expect(comboModels[0].x).toBe(400); expect(comboModels[0].y).toBe(500); }); it('parent combo collapsed with pos, child combo with pos', (done) => { const testData = clone(data); testData.combos[0].collapsed = true; graph.destroy(); graph = new Graph(graphCfg); graph.read(testData); combos = [graph.findById('A'), graph.findById('B'), graph.findById('C')]; comboModels = combos.map(combo => combo.getModel()); expect(comboModels[0].x).toBe(100); expect(comboModels[0].y).toBe(200); setTimeout(() => { // expand A graph.collapseExpandCombo('A'); setTimeout(() => { expect(combos[1].isVisible()).toBe(true); expect(combos[2].isVisible()).toBe(true); // the child combo follow the parent expect(comboModels[1].x).toBe(100); expect(comboModels[1].y).toBe(200); expect(comboModels[2].x).toBe(100); expect(comboModels[2].y).toBe(200); graph.destroy(); done(); }, 500); }, 500); }); }); describe('placea grid combo and nodes', () => { const data = { nodes: [ { id: '0', comboId: 'a', }, { id: '1', comboId: 'a', }, { id: '2', comboId: 'b', }, { id: '3', comboId: 'b', }, { id: '4', comboId: 'b', }, { id: '5', comboId: 'c', }, { id: '6', comboId: 'c', }, ], edges: [ { source: '0', target: '1', }, { source: '1', target: '2', }, { source: '0', target: '3', }, { source: '0', target: '4', }, { source: '6', target: '5', } ], combos: [ { id: 'a', label: 'Combo A', }, { id: 'b', label: 'Combo B', parentId: 'a' }, { id: 'c', label: 'Combo C', style: { fill: '#f00', opacity: 0.4 } }, { id: 'd', label: 'empty D' } ] } let graph = new Graph({ ...graphCfg, defaultCombo: { type: 'rect' } }); it('grid', () => { const testData = clone(data); const groupNodes = groupBy(testData.nodes, node => node.comboId); Object.keys(groupNodes).forEach(key => { groupNodes[key].forEach((node, i) => { node.x = i * 50; node.y = 0; }); }); testData.combos[0].x = 250; testData.combos[0].y = 250; testData.combos[1].x = 0; testData.combos[1].y = 100; testData.combos[2].x = 250; testData.combos[2].y = 450; testData.combos[3].x = 250; testData.combos[3].y = 550; graph.read(testData); const combos = testData.combos.map(cdata => graph.findById(cdata.id)); const comboModels = combos.map(combo => combo.getModel()); expect(comboModels[2].x).toBe(comboModels[0].x); expect(comboModels[2].x).toBe(comboModels[1].x); expect(comboModels[2].x).toBe(comboModels[3].x); graph.destroy(); }) });
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class AutoScalingPlans extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: AutoScalingPlans.Types.ClientConfiguration) config: Config & AutoScalingPlans.Types.ClientConfiguration; /** * Creates a scaling plan. */ createScalingPlan(params: AutoScalingPlans.Types.CreateScalingPlanRequest, callback?: (err: AWSError, data: AutoScalingPlans.Types.CreateScalingPlanResponse) => void): Request<AutoScalingPlans.Types.CreateScalingPlanResponse, AWSError>; /** * Creates a scaling plan. */ createScalingPlan(callback?: (err: AWSError, data: AutoScalingPlans.Types.CreateScalingPlanResponse) => void): Request<AutoScalingPlans.Types.CreateScalingPlanResponse, AWSError>; /** * Deletes the specified scaling plan. Deleting a scaling plan deletes the underlying ScalingInstruction for all of the scalable resources that are covered by the plan. If the plan has launched resources or has scaling activities in progress, you must delete those resources separately. */ deleteScalingPlan(params: AutoScalingPlans.Types.DeleteScalingPlanRequest, callback?: (err: AWSError, data: AutoScalingPlans.Types.DeleteScalingPlanResponse) => void): Request<AutoScalingPlans.Types.DeleteScalingPlanResponse, AWSError>; /** * Deletes the specified scaling plan. Deleting a scaling plan deletes the underlying ScalingInstruction for all of the scalable resources that are covered by the plan. If the plan has launched resources or has scaling activities in progress, you must delete those resources separately. */ deleteScalingPlan(callback?: (err: AWSError, data: AutoScalingPlans.Types.DeleteScalingPlanResponse) => void): Request<AutoScalingPlans.Types.DeleteScalingPlanResponse, AWSError>; /** * Describes the scalable resources in the specified scaling plan. */ describeScalingPlanResources(params: AutoScalingPlans.Types.DescribeScalingPlanResourcesRequest, callback?: (err: AWSError, data: AutoScalingPlans.Types.DescribeScalingPlanResourcesResponse) => void): Request<AutoScalingPlans.Types.DescribeScalingPlanResourcesResponse, AWSError>; /** * Describes the scalable resources in the specified scaling plan. */ describeScalingPlanResources(callback?: (err: AWSError, data: AutoScalingPlans.Types.DescribeScalingPlanResourcesResponse) => void): Request<AutoScalingPlans.Types.DescribeScalingPlanResourcesResponse, AWSError>; /** * Describes one or more of your scaling plans. */ describeScalingPlans(params: AutoScalingPlans.Types.DescribeScalingPlansRequest, callback?: (err: AWSError, data: AutoScalingPlans.Types.DescribeScalingPlansResponse) => void): Request<AutoScalingPlans.Types.DescribeScalingPlansResponse, AWSError>; /** * Describes one or more of your scaling plans. */ describeScalingPlans(callback?: (err: AWSError, data: AutoScalingPlans.Types.DescribeScalingPlansResponse) => void): Request<AutoScalingPlans.Types.DescribeScalingPlansResponse, AWSError>; /** * Retrieves the forecast data for a scalable resource. Capacity forecasts are represented as predicted values, or data points, that are calculated using historical data points from a specified CloudWatch load metric. Data points are available for up to 56 days. */ getScalingPlanResourceForecastData(params: AutoScalingPlans.Types.GetScalingPlanResourceForecastDataRequest, callback?: (err: AWSError, data: AutoScalingPlans.Types.GetScalingPlanResourceForecastDataResponse) => void): Request<AutoScalingPlans.Types.GetScalingPlanResourceForecastDataResponse, AWSError>; /** * Retrieves the forecast data for a scalable resource. Capacity forecasts are represented as predicted values, or data points, that are calculated using historical data points from a specified CloudWatch load metric. Data points are available for up to 56 days. */ getScalingPlanResourceForecastData(callback?: (err: AWSError, data: AutoScalingPlans.Types.GetScalingPlanResourceForecastDataResponse) => void): Request<AutoScalingPlans.Types.GetScalingPlanResourceForecastDataResponse, AWSError>; /** * Updates the specified scaling plan. You cannot update a scaling plan if it is in the process of being created, updated, or deleted. */ updateScalingPlan(params: AutoScalingPlans.Types.UpdateScalingPlanRequest, callback?: (err: AWSError, data: AutoScalingPlans.Types.UpdateScalingPlanResponse) => void): Request<AutoScalingPlans.Types.UpdateScalingPlanResponse, AWSError>; /** * Updates the specified scaling plan. You cannot update a scaling plan if it is in the process of being created, updated, or deleted. */ updateScalingPlan(callback?: (err: AWSError, data: AutoScalingPlans.Types.UpdateScalingPlanResponse) => void): Request<AutoScalingPlans.Types.UpdateScalingPlanResponse, AWSError>; } declare namespace AutoScalingPlans { export interface ApplicationSource { /** * The Amazon Resource Name (ARN) of a AWS CloudFormation stack. */ CloudFormationStackARN?: XmlString; /** * A set of tags (up to 50). */ TagFilters?: TagFilters; } export type ApplicationSources = ApplicationSource[]; export type Cooldown = number; export interface CreateScalingPlanRequest { /** * The name of the scaling plan. Names cannot contain vertical bars, colons, or forward slashes. */ ScalingPlanName: ScalingPlanName; /** * A CloudFormation stack or set of tags. You can create one scaling plan per application source. */ ApplicationSource: ApplicationSource; /** * The scaling instructions. */ ScalingInstructions: ScalingInstructions; } export interface CreateScalingPlanResponse { /** * The version number of the scaling plan. This value is always 1. Currently, you cannot specify multiple scaling plan versions. */ ScalingPlanVersion: ScalingPlanVersion; } export interface CustomizedLoadMetricSpecification { /** * The name of the metric. */ MetricName: MetricName; /** * The namespace of the metric. */ Namespace: MetricNamespace; /** * The dimensions of the metric. Conditional: If you published your metric with dimensions, you must specify the same dimensions in your customized load metric specification. */ Dimensions?: MetricDimensions; /** * The statistic of the metric. Currently, the value must always be Sum. */ Statistic: MetricStatistic; /** * The unit of the metric. */ Unit?: MetricUnit; } export interface CustomizedScalingMetricSpecification { /** * The name of the metric. */ MetricName: MetricName; /** * The namespace of the metric. */ Namespace: MetricNamespace; /** * The dimensions of the metric. Conditional: If you published your metric with dimensions, you must specify the same dimensions in your customized scaling metric specification. */ Dimensions?: MetricDimensions; /** * The statistic of the metric. */ Statistic: MetricStatistic; /** * The unit of the metric. */ Unit?: MetricUnit; } export interface Datapoint { /** * The time stamp for the data point in UTC format. */ Timestamp?: TimestampType; /** * The value of the data point. */ Value?: MetricScale; } export type Datapoints = Datapoint[]; export interface DeleteScalingPlanRequest { /** * The name of the scaling plan. */ ScalingPlanName: ScalingPlanName; /** * The version number of the scaling plan. */ ScalingPlanVersion: ScalingPlanVersion; } export interface DeleteScalingPlanResponse { } export interface DescribeScalingPlanResourcesRequest { /** * The name of the scaling plan. */ ScalingPlanName: ScalingPlanName; /** * The version number of the scaling plan. */ ScalingPlanVersion: ScalingPlanVersion; /** * The maximum number of scalable resources to return. The value must be between 1 and 50. The default value is 50. */ MaxResults?: MaxResults; /** * The token for the next set of results. */ NextToken?: NextToken; } export interface DescribeScalingPlanResourcesResponse { /** * Information about the scalable resources. */ ScalingPlanResources?: ScalingPlanResources; /** * The token required to get the next set of results. This value is null if there are no more results to return. */ NextToken?: NextToken; } export interface DescribeScalingPlansRequest { /** * The names of the scaling plans (up to 10). If you specify application sources, you cannot specify scaling plan names. */ ScalingPlanNames?: ScalingPlanNames; /** * The version number of the scaling plan. If you specify a scaling plan version, you must also specify a scaling plan name. */ ScalingPlanVersion?: ScalingPlanVersion; /** * The sources for the applications (up to 10). If you specify scaling plan names, you cannot specify application sources. */ ApplicationSources?: ApplicationSources; /** * The maximum number of scalable resources to return. This value can be between 1 and 50. The default value is 50. */ MaxResults?: MaxResults; /** * The token for the next set of results. */ NextToken?: NextToken; } export interface DescribeScalingPlansResponse { /** * Information about the scaling plans. */ ScalingPlans?: ScalingPlans; /** * The token required to get the next set of results. This value is null if there are no more results to return. */ NextToken?: NextToken; } export type DisableDynamicScaling = boolean; export type DisableScaleIn = boolean; export type ForecastDataType = "CapacityForecast"|"LoadForecast"|"ScheduledActionMinCapacity"|"ScheduledActionMaxCapacity"|string; export interface GetScalingPlanResourceForecastDataRequest { /** * The name of the scaling plan. */ ScalingPlanName: ScalingPlanName; /** * The version number of the scaling plan. */ ScalingPlanVersion: ScalingPlanVersion; /** * The namespace of the AWS service. */ ServiceNamespace: ServiceNamespace; /** * The ID of the resource. This string consists of the resource type and unique identifier. Auto Scaling group - The resource type is autoScalingGroup and the unique identifier is the name of the Auto Scaling group. Example: autoScalingGroup/my-asg. ECS service - The resource type is service and the unique identifier is the cluster name and service name. Example: service/default/sample-webapp. Spot Fleet request - The resource type is spot-fleet-request and the unique identifier is the Spot Fleet request ID. Example: spot-fleet-request/sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE. DynamoDB table - The resource type is table and the unique identifier is the resource ID. Example: table/my-table. DynamoDB global secondary index - The resource type is index and the unique identifier is the resource ID. Example: table/my-table/index/my-table-index. Aurora DB cluster - The resource type is cluster and the unique identifier is the cluster name. Example: cluster:my-db-cluster. */ ResourceId: XmlString; /** * The scalable dimension for the resource. */ ScalableDimension: ScalableDimension; /** * The type of forecast data to get. LoadForecast: The load metric forecast. CapacityForecast: The capacity forecast. ScheduledActionMinCapacity: The minimum capacity for each scheduled scaling action. This data is calculated as the larger of two values: the capacity forecast or the minimum capacity in the scaling instruction. ScheduledActionMaxCapacity: The maximum capacity for each scheduled scaling action. The calculation used is determined by the predictive scaling maximum capacity behavior setting in the scaling instruction. */ ForecastDataType: ForecastDataType; /** * The inclusive start time of the time range for the forecast data to get. The date and time can be at most 56 days before the current date and time. */ StartTime: TimestampType; /** * The exclusive end time of the time range for the forecast data to get. The maximum time duration between the start and end time is seven days. Although this parameter can accept a date and time that is more than two days in the future, the availability of forecast data has limits. AWS Auto Scaling only issues forecasts for periods of two days in advance. */ EndTime: TimestampType; } export interface GetScalingPlanResourceForecastDataResponse { /** * The data points to return. */ Datapoints: Datapoints; } export type LoadMetricType = "ASGTotalCPUUtilization"|"ASGTotalNetworkIn"|"ASGTotalNetworkOut"|"ALBTargetGroupRequestCount"|string; export type MaxResults = number; export interface MetricDimension { /** * The name of the dimension. */ Name: MetricDimensionName; /** * The value of the dimension. */ Value: MetricDimensionValue; } export type MetricDimensionName = string; export type MetricDimensionValue = string; export type MetricDimensions = MetricDimension[]; export type MetricName = string; export type MetricNamespace = string; export type MetricScale = number; export type MetricStatistic = "Average"|"Minimum"|"Maximum"|"SampleCount"|"Sum"|string; export type MetricUnit = string; export type NextToken = string; export type PolicyName = string; export type PolicyType = "TargetTrackingScaling"|string; export interface PredefinedLoadMetricSpecification { /** * The metric type. */ PredefinedLoadMetricType: LoadMetricType; /** * Identifies the resource associated with the metric type. You can't specify a resource label unless the metric type is ALBRequestCountPerTarget and there is a target group for an Application Load Balancer attached to the Auto Scaling group. The format is app/&lt;load-balancer-name&gt;/&lt;load-balancer-id&gt;/targetgroup/&lt;target-group-name&gt;/&lt;target-group-id&gt;, where: app/&lt;load-balancer-name&gt;/&lt;load-balancer-id&gt; is the final portion of the load balancer ARN. targetgroup/&lt;target-group-name&gt;/&lt;target-group-id&gt; is the final portion of the target group ARN. */ ResourceLabel?: ResourceLabel; } export interface PredefinedScalingMetricSpecification { /** * The metric type. The ALBRequestCountPerTarget metric type applies only to Auto Scaling groups, Spot Fleet requests, and ECS services. */ PredefinedScalingMetricType: ScalingMetricType; /** * Identifies the resource associated with the metric type. You can't specify a resource label unless the metric type is ALBRequestCountPerTarget and there is a target group for an Application Load Balancer attached to the Auto Scaling group, Spot Fleet request, or ECS service. The format is app/&lt;load-balancer-name&gt;/&lt;load-balancer-id&gt;/targetgroup/&lt;target-group-name&gt;/&lt;target-group-id&gt;, where: app/&lt;load-balancer-name&gt;/&lt;load-balancer-id&gt; is the final portion of the load balancer ARN. targetgroup/&lt;target-group-name&gt;/&lt;target-group-id&gt; is the final portion of the target group ARN. */ ResourceLabel?: ResourceLabel; } export type PredictiveScalingMaxCapacityBehavior = "SetForecastCapacityToMaxCapacity"|"SetMaxCapacityToForecastCapacity"|"SetMaxCapacityAboveForecastCapacity"|string; export type PredictiveScalingMode = "ForecastAndScale"|"ForecastOnly"|string; export type ResourceCapacity = number; export type ResourceIdMaxLen1600 = string; export type ResourceLabel = string; export type ScalableDimension = "autoscaling:autoScalingGroup:DesiredCapacity"|"ecs:service:DesiredCount"|"ec2:spot-fleet-request:TargetCapacity"|"rds:cluster:ReadReplicaCount"|"dynamodb:table:ReadCapacityUnits"|"dynamodb:table:WriteCapacityUnits"|"dynamodb:index:ReadCapacityUnits"|"dynamodb:index:WriteCapacityUnits"|string; export interface ScalingInstruction { /** * The namespace of the AWS service. */ ServiceNamespace: ServiceNamespace; /** * The ID of the resource. This string consists of the resource type and unique identifier. Auto Scaling group - The resource type is autoScalingGroup and the unique identifier is the name of the Auto Scaling group. Example: autoScalingGroup/my-asg. ECS service - The resource type is service and the unique identifier is the cluster name and service name. Example: service/default/sample-webapp. Spot Fleet request - The resource type is spot-fleet-request and the unique identifier is the Spot Fleet request ID. Example: spot-fleet-request/sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE. DynamoDB table - The resource type is table and the unique identifier is the resource ID. Example: table/my-table. DynamoDB global secondary index - The resource type is index and the unique identifier is the resource ID. Example: table/my-table/index/my-table-index. Aurora DB cluster - The resource type is cluster and the unique identifier is the cluster name. Example: cluster:my-db-cluster. */ ResourceId: ResourceIdMaxLen1600; /** * The scalable dimension associated with the resource. autoscaling:autoScalingGroup:DesiredCapacity - The desired capacity of an Auto Scaling group. ecs:service:DesiredCount - The desired task count of an ECS service. ec2:spot-fleet-request:TargetCapacity - The target capacity of a Spot Fleet request. dynamodb:table:ReadCapacityUnits - The provisioned read capacity for a DynamoDB table. dynamodb:table:WriteCapacityUnits - The provisioned write capacity for a DynamoDB table. dynamodb:index:ReadCapacityUnits - The provisioned read capacity for a DynamoDB global secondary index. dynamodb:index:WriteCapacityUnits - The provisioned write capacity for a DynamoDB global secondary index. rds:cluster:ReadReplicaCount - The count of Aurora Replicas in an Aurora DB cluster. Available for Aurora MySQL-compatible edition and Aurora PostgreSQL-compatible edition. */ ScalableDimension: ScalableDimension; /** * The minimum capacity of the resource. */ MinCapacity: ResourceCapacity; /** * The maximum capacity of the resource. The exception to this upper limit is if you specify a non-default setting for PredictiveScalingMaxCapacityBehavior. */ MaxCapacity: ResourceCapacity; /** * The structure that defines new target tracking configurations (up to 10). Each of these structures includes a specific scaling metric and a target value for the metric, along with various parameters to use with dynamic scaling. With predictive scaling and dynamic scaling, the resource scales based on the target tracking configuration that provides the largest capacity for both scale in and scale out. Condition: The scaling metric must be unique across target tracking configurations. */ TargetTrackingConfigurations: TargetTrackingConfigurations; /** * The predefined load metric to use for predictive scaling. This parameter or a CustomizedLoadMetricSpecification is required when configuring predictive scaling, and cannot be used otherwise. */ PredefinedLoadMetricSpecification?: PredefinedLoadMetricSpecification; /** * The customized load metric to use for predictive scaling. This parameter or a PredefinedLoadMetricSpecification is required when configuring predictive scaling, and cannot be used otherwise. */ CustomizedLoadMetricSpecification?: CustomizedLoadMetricSpecification; /** * The amount of time, in seconds, to buffer the run time of scheduled scaling actions when scaling out. For example, if the forecast says to add capacity at 10:00 AM, and the buffer time is 5 minutes, then the run time of the corresponding scheduled scaling action will be 9:55 AM. The intention is to give resources time to be provisioned. For example, it can take a few minutes to launch an EC2 instance. The actual amount of time required depends on several factors, such as the size of the instance and whether there are startup scripts to complete. The value must be less than the forecast interval duration of 3600 seconds (60 minutes). The default is 300 seconds. Only valid when configuring predictive scaling. */ ScheduledActionBufferTime?: ScheduledActionBufferTime; /** * Defines the behavior that should be applied if the forecast capacity approaches or exceeds the maximum capacity specified for the resource. The default value is SetForecastCapacityToMaxCapacity. The following are possible values: SetForecastCapacityToMaxCapacity - AWS Auto Scaling cannot scale resource capacity higher than the maximum capacity. The maximum capacity is enforced as a hard limit. SetMaxCapacityToForecastCapacity - AWS Auto Scaling may scale resource capacity higher than the maximum capacity to equal but not exceed forecast capacity. SetMaxCapacityAboveForecastCapacity - AWS Auto Scaling may scale resource capacity higher than the maximum capacity by a specified buffer value. The intention is to give the target tracking scaling policy extra capacity if unexpected traffic occurs. Only valid when configuring predictive scaling. */ PredictiveScalingMaxCapacityBehavior?: PredictiveScalingMaxCapacityBehavior; /** * The size of the capacity buffer to use when the forecast capacity is close to or exceeds the maximum capacity. The value is specified as a percentage relative to the forecast capacity. For example, if the buffer is 10, this means a 10 percent buffer, such that if the forecast capacity is 50, and the maximum capacity is 40, then the effective maximum capacity is 55. Only valid when configuring predictive scaling. Required if the PredictiveScalingMaxCapacityBehavior is set to SetMaxCapacityAboveForecastCapacity, and cannot be used otherwise. The range is 1-100. */ PredictiveScalingMaxCapacityBuffer?: ResourceCapacity; /** * The predictive scaling mode. The default value is ForecastAndScale. Otherwise, AWS Auto Scaling forecasts capacity but does not create any scheduled scaling actions based on the capacity forecast. */ PredictiveScalingMode?: PredictiveScalingMode; /** * Controls whether a resource's externally created scaling policies are kept or replaced. The default value is KeepExternalPolicies. If the parameter is set to ReplaceExternalPolicies, any scaling policies that are external to AWS Auto Scaling are deleted and new target tracking scaling policies created. Only valid when configuring dynamic scaling. Condition: The number of existing policies to be replaced must be less than or equal to 50. If there are more than 50 policies to be replaced, AWS Auto Scaling keeps all existing policies and does not create new ones. */ ScalingPolicyUpdateBehavior?: ScalingPolicyUpdateBehavior; /** * Controls whether dynamic scaling by AWS Auto Scaling is disabled. When dynamic scaling is enabled, AWS Auto Scaling creates target tracking scaling policies based on the specified target tracking configurations. The default is enabled (false). */ DisableDynamicScaling?: DisableDynamicScaling; } export type ScalingInstructions = ScalingInstruction[]; export type ScalingMetricType = "ASGAverageCPUUtilization"|"ASGAverageNetworkIn"|"ASGAverageNetworkOut"|"DynamoDBReadCapacityUtilization"|"DynamoDBWriteCapacityUtilization"|"ECSServiceAverageCPUUtilization"|"ECSServiceAverageMemoryUtilization"|"ALBRequestCountPerTarget"|"RDSReaderAverageCPUUtilization"|"RDSReaderAverageDatabaseConnections"|"EC2SpotFleetRequestAverageCPUUtilization"|"EC2SpotFleetRequestAverageNetworkIn"|"EC2SpotFleetRequestAverageNetworkOut"|string; export interface ScalingPlan { /** * The name of the scaling plan. */ ScalingPlanName: ScalingPlanName; /** * The version number of the scaling plan. */ ScalingPlanVersion: ScalingPlanVersion; /** * The application source. */ ApplicationSource: ApplicationSource; /** * The scaling instructions. */ ScalingInstructions: ScalingInstructions; /** * The status of the scaling plan. Active - The scaling plan is active. ActiveWithProblems - The scaling plan is active, but the scaling configuration for one or more resources could not be applied. CreationInProgress - The scaling plan is being created. CreationFailed - The scaling plan could not be created. DeletionInProgress - The scaling plan is being deleted. DeletionFailed - The scaling plan could not be deleted. UpdateInProgress - The scaling plan is being updated. UpdateFailed - The scaling plan could not be updated. */ StatusCode: ScalingPlanStatusCode; /** * A simple message about the current status of the scaling plan. */ StatusMessage?: XmlString; /** * The Unix time stamp when the scaling plan entered the current status. */ StatusStartTime?: TimestampType; /** * The Unix time stamp when the scaling plan was created. */ CreationTime?: TimestampType; } export type ScalingPlanName = string; export type ScalingPlanNames = ScalingPlanName[]; export interface ScalingPlanResource { /** * The name of the scaling plan. */ ScalingPlanName: ScalingPlanName; /** * The version number of the scaling plan. */ ScalingPlanVersion: ScalingPlanVersion; /** * The namespace of the AWS service. */ ServiceNamespace: ServiceNamespace; /** * The ID of the resource. This string consists of the resource type and unique identifier. Auto Scaling group - The resource type is autoScalingGroup and the unique identifier is the name of the Auto Scaling group. Example: autoScalingGroup/my-asg. ECS service - The resource type is service and the unique identifier is the cluster name and service name. Example: service/default/sample-webapp. Spot Fleet request - The resource type is spot-fleet-request and the unique identifier is the Spot Fleet request ID. Example: spot-fleet-request/sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE. DynamoDB table - The resource type is table and the unique identifier is the resource ID. Example: table/my-table. DynamoDB global secondary index - The resource type is index and the unique identifier is the resource ID. Example: table/my-table/index/my-table-index. Aurora DB cluster - The resource type is cluster and the unique identifier is the cluster name. Example: cluster:my-db-cluster. */ ResourceId: ResourceIdMaxLen1600; /** * The scalable dimension for the resource. autoscaling:autoScalingGroup:DesiredCapacity - The desired capacity of an Auto Scaling group. ecs:service:DesiredCount - The desired task count of an ECS service. ec2:spot-fleet-request:TargetCapacity - The target capacity of a Spot Fleet request. dynamodb:table:ReadCapacityUnits - The provisioned read capacity for a DynamoDB table. dynamodb:table:WriteCapacityUnits - The provisioned write capacity for a DynamoDB table. dynamodb:index:ReadCapacityUnits - The provisioned read capacity for a DynamoDB global secondary index. dynamodb:index:WriteCapacityUnits - The provisioned write capacity for a DynamoDB global secondary index. rds:cluster:ReadReplicaCount - The count of Aurora Replicas in an Aurora DB cluster. Available for Aurora MySQL-compatible edition and Aurora PostgreSQL-compatible edition. */ ScalableDimension: ScalableDimension; /** * The scaling policies. */ ScalingPolicies?: ScalingPolicies; /** * The scaling status of the resource. Active - The scaling configuration is active. Inactive - The scaling configuration is not active because the scaling plan is being created or the scaling configuration could not be applied. Check the status message for more information. PartiallyActive - The scaling configuration is partially active because the scaling plan is being created or deleted or the scaling configuration could not be fully applied. Check the status message for more information. */ ScalingStatusCode: ScalingStatusCode; /** * A simple message about the current scaling status of the resource. */ ScalingStatusMessage?: XmlString; } export type ScalingPlanResources = ScalingPlanResource[]; export type ScalingPlanStatusCode = "Active"|"ActiveWithProblems"|"CreationInProgress"|"CreationFailed"|"DeletionInProgress"|"DeletionFailed"|"UpdateInProgress"|"UpdateFailed"|string; export type ScalingPlanVersion = number; export type ScalingPlans = ScalingPlan[]; export type ScalingPolicies = ScalingPolicy[]; export interface ScalingPolicy { /** * The name of the scaling policy. */ PolicyName: PolicyName; /** * The type of scaling policy. */ PolicyType: PolicyType; /** * The target tracking scaling policy. Includes support for predefined or customized metrics. */ TargetTrackingConfiguration?: TargetTrackingConfiguration; } export type ScalingPolicyUpdateBehavior = "KeepExternalPolicies"|"ReplaceExternalPolicies"|string; export type ScalingStatusCode = "Inactive"|"PartiallyActive"|"Active"|string; export type ScheduledActionBufferTime = number; export type ServiceNamespace = "autoscaling"|"ecs"|"ec2"|"rds"|"dynamodb"|string; export interface TagFilter { /** * The tag key. */ Key?: XmlStringMaxLen128; /** * The tag values (0 to 20). */ Values?: TagValues; } export type TagFilters = TagFilter[]; export type TagValues = XmlStringMaxLen256[]; export interface TargetTrackingConfiguration { /** * A predefined metric. You can specify either a predefined metric or a customized metric. */ PredefinedScalingMetricSpecification?: PredefinedScalingMetricSpecification; /** * A customized metric. You can specify either a predefined metric or a customized metric. */ CustomizedScalingMetricSpecification?: CustomizedScalingMetricSpecification; /** * The target value for the metric. The range is 8.515920e-109 to 1.174271e+108 (Base 10) or 2e-360 to 2e360 (Base 2). */ TargetValue: MetricScale; /** * Indicates whether scale in by the target tracking scaling policy is disabled. If the value is true, scale in is disabled and the target tracking scaling policy doesn't remove capacity from the scalable resource. Otherwise, scale in is enabled and the target tracking scaling policy can remove capacity from the scalable resource. The default value is false. */ DisableScaleIn?: DisableScaleIn; /** * The amount of time, in seconds, after a scale-out activity completes before another scale-out activity can start. This value is not used if the scalable resource is an Auto Scaling group. While the cooldown period is in effect, the capacity that has been added by the previous scale-out event that initiated the cooldown is calculated as part of the desired capacity for the next scale out. The intention is to continuously (but not excessively) scale out. */ ScaleOutCooldown?: Cooldown; /** * The amount of time, in seconds, after a scale in activity completes before another scale in activity can start. This value is not used if the scalable resource is an Auto Scaling group. The cooldown period is used to block subsequent scale in requests until it has expired. The intention is to scale in conservatively to protect your application's availability. However, if another alarm triggers a scale-out policy during the cooldown period after a scale-in, AWS Auto Scaling scales out your scalable target immediately. */ ScaleInCooldown?: Cooldown; /** * The estimated time, in seconds, until a newly launched instance can contribute to the CloudWatch metrics. This value is used only if the resource is an Auto Scaling group. */ EstimatedInstanceWarmup?: Cooldown; } export type TargetTrackingConfigurations = TargetTrackingConfiguration[]; export type TimestampType = Date; export interface UpdateScalingPlanRequest { /** * The name of the scaling plan. */ ScalingPlanName: ScalingPlanName; /** * The version number of the scaling plan. */ ScalingPlanVersion: ScalingPlanVersion; /** * A CloudFormation stack or set of tags. */ ApplicationSource?: ApplicationSource; /** * The scaling instructions. */ ScalingInstructions?: ScalingInstructions; } export interface UpdateScalingPlanResponse { } export type XmlString = string; export type XmlStringMaxLen128 = string; export type XmlStringMaxLen256 = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2018-01-06"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the AutoScalingPlans client. */ export import Types = AutoScalingPlans; } export = AutoScalingPlans;
the_stack
import React from "react"; import styled, { css } from "styled-components"; import { Link } from "gatsby"; import { WindowLocation } from "@reach/router"; import { Stack, Button, Hide, Portal, ModalHeader, ModalSection, Badge, Modal, mediaQueries as mq, } from "@kiwicom/orbit-components"; import { MenuHamburger, StarEmpty, Logout } from "@kiwicom/orbit-components/icons"; import GitHubButton from "react-github-btn"; import Logo from "../images/orbit-logo.svg"; import Glyph from "../images/orbit-glyph.svg"; import Bookmarks from "./Bookmarks"; import Search from "./Search"; import { useBookmarks } from "../services/bookmarks"; import { MAX_CONTENT_WIDTH, CONTENT_PADDING } from "../consts"; import { useKeyboard } from "../services/KeyboardProvider"; import SearchNavbarButton from "./Search/SearchNavbarButton"; import { isLoggedIn, logout } from "../services/auth"; const StyledWrapper = styled.header` position: relative; z-index: 10; padding: 0.5rem 0; background: rgba(255, 255, 255, 0.9); backdrop-filter: blur(5px); ${mq.tablet(css` padding: 1rem 0; `)} ${mq.desktop(css` padding: 1.5rem 0; `)} `; const StyledInner = styled.div` max-width: ${MAX_CONTENT_WIDTH}; padding: 0 ${CONTENT_PADDING}; box-sizing: content-box; height: 52px; margin: 0 auto; display: flex; align-items: center; justify-content: space-between; `; const StyledLogo = styled(Logo)` display: none; ${mq.mediumMobile(css` display: block; `)}; `; const StyledLogoGlyph = styled(Glyph)` display: block; ${mq.mediumMobile(css` display: none; `)}; `; const StyledRight = styled.div` display: flex; align-items: center; `; const StyledTabList = styled.div` ${({ theme }) => ` font-size: 1rem; /* hack back to regular size because it's in ModalHeader title */ display: flex; height: 44px; border-radius: 22px; padding: 2px; background: ${theme.orbit.paletteCloudLight}; box-shadow: 0px 1px 4px 0px #252A311F inset, 0px 0px 2px 0px #252A3129 inset; `} `; const StyledTab = styled.button` ${({ theme }) => ` flex: 1; display: block; height: 100%; &[aria-selected=true] { border-radius: 22px; background: ${theme.orbit.paletteWhite}; box-shadow: 0px 4px 8px 0px #252A311F, 0px 1px 4px 0px #252A3129; } `}; `; interface Props { location: WindowLocation; docNavigation?: React.ReactNode; } const Navbar = ({ location, docNavigation }: Props) => { const [isSearchOpen, setSearchOpen] = useKeyboard(); const [menuOpen, setMenuOpen] = React.useState<boolean>(false); const [activeTab, setActiveTab] = React.useState<"navigation" | "bookmarks">("navigation"); const isHome = location && location.pathname === "/"; const { bookmarks } = useBookmarks(); return ( <StyledWrapper> <StyledInner> <Stack inline shrink align="center"> <Link to="/" aria-label="Back to home page"> <StyledLogo width={192} height={44} /> <StyledLogoGlyph width={44} height={44} /> </Link> <span>&sdot;</span> <div css={css` height: 22px; `} > <GitHubButton href="https://github.com/kiwicom/orbit" data-show-count data-icon="star" title="kiwicom/orbit" aria-label="orbit github" /> </div> </Stack> <StyledRight> <Stack inline spacing="XXSmall"> {!isHome && <SearchNavbarButton onClick={() => setSearchOpen(true)} />} {isSearchOpen && !isHome && <Search onClose={() => setSearchOpen(false)} />} {docNavigation ? ( <> <Hide block on={["largeDesktop"]}> <Button type="white" circled title="Menu" iconLeft={<MenuHamburger />} onClick={() => setMenuOpen(true)} /> </Hide> <Hide block on={["smallMobile", "mediumMobile", "largeMobile", "tablet", "desktop"]} > <Button type="white" iconLeft={<StarEmpty />} circled title="Open bookmarks" onClick={() => setMenuOpen(true)} /> </Hide> </> ) : ( <> <Button type="white" iconLeft={<StarEmpty />} circled title="Open bookmarks" onClick={() => setMenuOpen(true)} /> </> )} {isLoggedIn() && ( <Button title="logout" iconLeft={<Logout />} type="white" circled onClick={logout} /> )} </Stack> {menuOpen && ( <Portal> <div css={css` > * > * > * { /* keep modal at full width between tabs */ height: 100%; } ${mq.largeMobile(css` /* align modal to the top */ > * > * { align-items: flex-start; } > * > * > * { height: auto; align-self: stretch; } `)} ${mq.desktop(css` > * > * > * { align-self: auto; } `)} `} > <Modal fixedFooter onClose={() => setMenuOpen(false)}> {docNavigation ? ( <> <ModalHeader title={ <> <Hide block on={["largeDesktop"]}> <Stack flex direction="column" align="stretch" spacing="large"> {/* TODO: ensure that tabs are accessible, code below is just guesswork */} <StyledTabList role="tablist"> <StyledTab role="tab" aria-selected={activeTab === "navigation"} aria-controls="navbar-tabpanel-navigation" // eslint-disable-next-line orbit-components/unique-id id="navbar-tab-navigation" type="button" onClick={() => setActiveTab("navigation")} > Navigation </StyledTab> <StyledTab role="tab" aria-selected={activeTab === "bookmarks"} aria-controls="navbar-tabpanel-bookmarks" // eslint-disable-next-line orbit-components/unique-id id="navbar-tab-bookmarks" type="button" onClick={() => setActiveTab("bookmarks")} > Bookmarks </StyledTab> </StyledTabList> {activeTab === "bookmarks" && ( <Stack flex align="center"> <div>Your bookmarks</div> <Badge type="infoInverted"> {bookmarks ? Object.keys(bookmarks).length : 0} </Badge> </Stack> )} </Stack> </Hide> <Hide block on={[ "smallMobile", "mediumMobile", "largeMobile", "tablet", "desktop", ]} > <Stack flex align="center"> <div>Your bookmarks</div> <Badge type="infoInverted"> {bookmarks ? Object.keys(bookmarks).length : 0} </Badge> </Stack> </Hide> </> } /> <ModalSection> <Hide block on={["largeDesktop"]}> {activeTab === "navigation" && ( <div tabIndex={0} role="tabpanel" // eslint-disable-next-line orbit-components/unique-id id="navbar-tabpanel-navigation" aria-labelledby="navbar-tab-navigation" > {docNavigation} </div> )} {activeTab === "bookmarks" && ( <div tabIndex={0} role="tabpanel" // eslint-disable-next-line orbit-components/unique-id id="navbar-tabpanel-navigation" aria-labelledby="navbar-tab-navigation" > <Bookmarks /> </div> )} </Hide> <Hide block on={["smallMobile", "mediumMobile", "largeMobile", "tablet", "desktop"]} > <Bookmarks /> </Hide> </ModalSection> </> ) : ( <> <ModalHeader title={ <Stack flex align="center"> <div>Your bookmarks</div> <Badge type="infoInverted"> {bookmarks ? Object.keys(bookmarks).length : 0} </Badge> </Stack> } /> <ModalSection> <Bookmarks /> </ModalSection> </> )} {/* hiding this feature for now, we'll fully implement it later according to the design */} {/* <ModalFooter> <Hide block on={["largeDesktop"]}> {activeTab === "bookmarks" && editingBookmarks ? ( <> <Button type="secondary" onClick={() => setEditingBookmarks(false)}> Cancel </Button> {selectedBookmarks.length > 0 && ( <Button type="primarySubtle" onClick={() => { // delete bookmarks... setEditingBookmarks(false); }} > Remove selected ({selectedBookmarks.length}) </Button> )} </> ) : ( <Button type="secondary" onClick={() => setMenuOpen(false)}> Close </Button> )} </Hide> <Hide block on={["smallMobile", "mediumMobile", "largeMobile", "tablet", "desktop"]} > {!editingBookmarks && ( <Button type="secondary" onClick={() => setEditingBookmarks(true)}> Edit bookmarks </Button> )} {editingBookmarks && selectedBookmarks.length === 0 && ( <Stack flex align="center" justify="between" spacing="XLarge"> <p>Select the bookmarks you would like to remove.</p> <Button type="secondary" onClick={() => setEditingBookmarks(false)}> Cancel </Button> </Stack> )} {editingBookmarks && selectedBookmarks.length > 0 && ( <Stack flex justify="end"> <Button type="secondary" onClick={() => setEditingBookmarks(false)}> Cancel </Button> <Button type="criticalSubtle" onClick={() => { // delete bookmarks... setEditingBookmarks(false); }} > Remove selected </Button> </Stack> )} </Hide> </ModalFooter> */} </Modal> </div> </Portal> )} </StyledRight> </StyledInner> </StyledWrapper> ); }; export default Navbar;
the_stack
/* eslint-disable @typescript-eslint/class-name-casing */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-empty-interface */ /* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable no-irregular-whitespace */ import { OAuth2Client, JWT, Compute, UserRefreshClient, BaseExternalAccountClient, GaxiosPromise, GoogleConfigurable, createAPIRequest, MethodOptions, StreamMethodOptions, GlobalOptions, GoogleAuth, BodyResponseCallback, APIRequestContext, } from 'googleapis-common'; import {Readable} from 'stream'; export namespace webrisk_v1 { export interface Options extends GlobalOptions { version: 'v1'; } interface StandardParameters { /** * Auth client or API Key for the request */ auth?: | string | OAuth2Client | JWT | Compute | UserRefreshClient | BaseExternalAccountClient | GoogleAuth; /** * V1 error format. */ '$.xgafv'?: string; /** * OAuth access token. */ access_token?: string; /** * Data format for response. */ alt?: string; /** * JSONP */ callback?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; } /** * Web Risk API * * * * @example * ```js * const {google} = require('googleapis'); * const webrisk = google.webrisk('v1'); * ``` */ export class Webrisk { context: APIRequestContext; hashes: Resource$Hashes; projects: Resource$Projects; threatLists: Resource$Threatlists; uris: Resource$Uris; constructor(options: GlobalOptions, google?: GoogleConfigurable) { this.context = { _options: options || {}, google, }; this.hashes = new Resource$Hashes(this.context); this.projects = new Resource$Projects(this.context); this.threatLists = new Resource$Threatlists(this.context); this.uris = new Resource$Uris(this.context); } } export interface Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponse { /** * A set of entries to add to a local threat type's list. */ additions?: Schema$GoogleCloudWebriskV1ThreatEntryAdditions; /** * The expected SHA256 hash of the client state; that is, of the sorted list of all hashes present in the database after applying the provided diff. If the client state doesn't match the expected state, the client must discard this diff and retry later. */ checksum?: Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponseChecksum; /** * The new opaque client version token. This should be retained by the client and passed into the next call of ComputeThreatListDiff as 'version_token'. A separate version token should be stored and used for each threatList. */ newVersionToken?: string | null; /** * The soonest the client should wait before issuing any diff request. Querying sooner is unlikely to produce a meaningful diff. Waiting longer is acceptable considering the use case. If this field is not set clients may update as soon as they want. */ recommendedNextDiff?: string | null; /** * A set of entries to remove from a local threat type's list. This field may be empty. */ removals?: Schema$GoogleCloudWebriskV1ThreatEntryRemovals; /** * The type of response. This may indicate that an action must be taken by the client when the response is received. */ responseType?: string | null; } /** * The expected state of a client's local database. */ export interface Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponseChecksum { /** * The SHA256 hash of the client state; that is, of the sorted list of all hashes present in the database. */ sha256?: string | null; } /** * The uncompressed threat entries in hash format. Hashes can be anywhere from 4 to 32 bytes in size. A large majority are 4 bytes, but some hashes are lengthened if they collide with the hash of a popular URI. Used for sending ThreatEntryAdditons to clients that do not support compression, or when sending non-4-byte hashes to clients that do support compression. */ export interface Schema$GoogleCloudWebriskV1RawHashes { /** * The number of bytes for each prefix encoded below. This field can be anywhere from 4 (shortest prefix) to 32 (full SHA256 hash). In practice this is almost always 4, except in exceptional circumstances. */ prefixSize?: number | null; /** * The hashes, in binary format, concatenated into one long string. Hashes are sorted in lexicographic order. For JSON API users, hashes are base64-encoded. */ rawHashes?: string | null; } /** * A set of raw indices to remove from a local list. */ export interface Schema$GoogleCloudWebriskV1RawIndices { /** * The indices to remove from a lexicographically-sorted local list. */ indices?: number[] | null; } /** * The Rice-Golomb encoded data. Used for sending compressed 4-byte hashes or compressed removal indices. */ export interface Schema$GoogleCloudWebriskV1RiceDeltaEncoding { /** * The encoded deltas that are encoded using the Golomb-Rice coder. */ encodedData?: string | null; /** * The number of entries that are delta encoded in the encoded data. If only a single integer was encoded, this will be zero and the single value will be stored in `first_value`. */ entryCount?: number | null; /** * The offset of the first entry in the encoded data, or, if only a single integer was encoded, that single integer's value. If the field is empty or missing, assume zero. */ firstValue?: string | null; /** * The Golomb-Rice parameter, which is a number between 2 and 28. This field is missing (that is, zero) if `num_entries` is zero. */ riceParameter?: number | null; } export interface Schema$GoogleCloudWebriskV1SearchHashesResponse { /** * For requested entities that did not match the threat list, how long to cache the response until. */ negativeExpireTime?: string | null; /** * The full hashes that matched the requested prefixes. The hash will be populated in the key. */ threats?: Schema$GoogleCloudWebriskV1SearchHashesResponseThreatHash[]; } /** * Contains threat information on a matching hash. */ export interface Schema$GoogleCloudWebriskV1SearchHashesResponseThreatHash { /** * The cache lifetime for the returned match. Clients must not cache this response past this timestamp to avoid false positives. */ expireTime?: string | null; /** * A 32 byte SHA256 hash. This field is in binary format. For JSON requests, hashes are base64-encoded. */ hash?: string | null; /** * The ThreatList this threat belongs to. This must contain at least one entry. */ threatTypes?: string[] | null; } export interface Schema$GoogleCloudWebriskV1SearchUrisResponse { /** * The threat list matches. This may be empty if the URI is on no list. */ threat?: Schema$GoogleCloudWebriskV1SearchUrisResponseThreatUri; } /** * Contains threat information on a matching uri. */ export interface Schema$GoogleCloudWebriskV1SearchUrisResponseThreatUri { /** * The cache lifetime for the returned match. Clients must not cache this response past this timestamp to avoid false positives. */ expireTime?: string | null; /** * The ThreatList this threat belongs to. */ threatTypes?: string[] | null; } /** * Wraps a URI that might be displaying malicious content. */ export interface Schema$GoogleCloudWebriskV1Submission { /** * ThreatTypes found to be associated with the submitted URI after reviewing it. This may be empty if the URI was not added to any list. */ threatTypes?: string[] | null; /** * Required. The URI that is being reported for malicious content to be analyzed. */ uri?: string | null; } /** * Metadata for the Submit URI long-running operation. */ export interface Schema$GoogleCloudWebriskV1SubmitUriMetadata { /** * Creation time of the operation. */ createTime?: string | null; /** * The state of the operation. */ state?: string | null; /** * Latest update time of the operation. */ updateTime?: string | null; } /** * Request to send a potentially malicious URI to WebRisk. */ export interface Schema$GoogleCloudWebriskV1SubmitUriRequest { /** * Required. The submission that contains the URI to be scanned. */ submission?: Schema$GoogleCloudWebriskV1Submission; } /** * Contains the set of entries to add to a local database. May contain a combination of compressed and raw data in a single response. */ export interface Schema$GoogleCloudWebriskV1ThreatEntryAdditions { /** * The raw SHA256-formatted entries. Repeated to allow returning sets of hashes with different prefix sizes. */ rawHashes?: Schema$GoogleCloudWebriskV1RawHashes[]; /** * The encoded 4-byte prefixes of SHA256-formatted entries, using a Golomb-Rice encoding. The hashes are converted to uint32, sorted in ascending order, then delta encoded and stored as encoded_data. */ riceHashes?: Schema$GoogleCloudWebriskV1RiceDeltaEncoding; } /** * Contains the set of entries to remove from a local database. */ export interface Schema$GoogleCloudWebriskV1ThreatEntryRemovals { /** * The raw removal indices for a local list. */ rawIndices?: Schema$GoogleCloudWebriskV1RawIndices; /** * The encoded local, lexicographically-sorted list indices, using a Golomb-Rice encoding. Used for sending compressed removal indices. The removal indices (uint32) are sorted in ascending order, then delta encoded and stored as encoded_data. */ riceIndices?: Schema$GoogleCloudWebriskV1RiceDeltaEncoding; } /** * The request message for Operations.CancelOperation. */ export interface Schema$GoogleLongrunningCancelOperationRequest {} /** * The response message for Operations.ListOperations. */ export interface Schema$GoogleLongrunningListOperationsResponse { /** * The standard List next-page token. */ nextPageToken?: string | null; /** * A list of operations that matches the specified filter in the request. */ operations?: Schema$GoogleLongrunningOperation[]; } /** * This resource represents a long-running operation that is the result of a network API call. */ export interface Schema$GoogleLongrunningOperation { /** * If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ done?: boolean | null; /** * The error result of the operation in case of failure or cancellation. */ error?: Schema$GoogleRpcStatus; /** * Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ metadata?: {[key: string]: any} | null; /** * The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id\}`. */ name?: string | null; /** * The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. */ response?: {[key: string]: any} | null; } /** * A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); \} The JSON representation for `Empty` is empty JSON object `{\}`. */ export interface Schema$GoogleProtobufEmpty {} /** * The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */ export interface Schema$GoogleRpcStatus { /** * The status code, which should be an enum value of google.rpc.Code. */ code?: number | null; /** * A list of messages that carry the error details. There is a common set of message types for APIs to use. */ details?: Array<{[key: string]: any}> | null; /** * A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ message?: string | null; } export class Resource$Hashes { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the full hashes that match the requested hash prefix. This is used after a hash prefix is looked up in a threatList and there is a match. The client side threatList only holds partial hashes so the client must query this method to determine if there is a full hash match of a threat. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/webrisk.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const webrisk = google.webrisk('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await webrisk.hashes.search({ * // A hash prefix, consisting of the most significant 4-32 bytes of a SHA256 hash. For JSON requests, this field is base64-encoded. Note that if this parameter is provided by a URI, it must be encoded using the web safe base64 variant (RFC 4648). * hashPrefix: 'placeholder-value', * // Required. The ThreatLists to search in. Multiple ThreatLists may be specified. * threatTypes: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "negativeExpireTime": "my_negativeExpireTime", * // "threats": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ search( params: Params$Resource$Hashes$Search, options: StreamMethodOptions ): GaxiosPromise<Readable>; search( params?: Params$Resource$Hashes$Search, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudWebriskV1SearchHashesResponse>; search( params: Params$Resource$Hashes$Search, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; search( params: Params$Resource$Hashes$Search, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchHashesResponse>, callback: BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchHashesResponse> ): void; search( params: Params$Resource$Hashes$Search, callback: BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchHashesResponse> ): void; search( callback: BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchHashesResponse> ): void; search( paramsOrCallback?: | Params$Resource$Hashes$Search | BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchHashesResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchHashesResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchHashesResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudWebriskV1SearchHashesResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Hashes$Search; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Hashes$Search; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://webrisk.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/hashes:search').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudWebriskV1SearchHashesResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudWebriskV1SearchHashesResponse>( parameters ); } } } export interface Params$Resource$Hashes$Search extends StandardParameters { /** * A hash prefix, consisting of the most significant 4-32 bytes of a SHA256 hash. For JSON requests, this field is base64-encoded. Note that if this parameter is provided by a URI, it must be encoded using the web safe base64 variant (RFC 4648). */ hashPrefix?: string; /** * Required. The ThreatLists to search in. Multiple ThreatLists may be specified. */ threatTypes?: string[]; } export class Resource$Projects { context: APIRequestContext; operations: Resource$Projects$Operations; submissions: Resource$Projects$Submissions; uris: Resource$Projects$Uris; constructor(context: APIRequestContext) { this.context = context; this.operations = new Resource$Projects$Operations(this.context); this.submissions = new Resource$Projects$Submissions(this.context); this.uris = new Resource$Projects$Uris(this.context); } } export class Resource$Projects$Operations { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/webrisk.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const webrisk = google.webrisk('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await webrisk.projects.operations.cancel({ * // The name of the operation resource to be cancelled. * name: 'projects/my-project/operations/my-operation', * * // Request body metadata * requestBody: { * // request body parameters * // {} * }, * }); * console.log(res.data); * * // Example response * // {} * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ cancel( params: Params$Resource$Projects$Operations$Cancel, options: StreamMethodOptions ): GaxiosPromise<Readable>; cancel( params?: Params$Resource$Projects$Operations$Cancel, options?: MethodOptions ): GaxiosPromise<Schema$GoogleProtobufEmpty>; cancel( params: Params$Resource$Projects$Operations$Cancel, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; cancel( params: Params$Resource$Projects$Operations$Cancel, options: MethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty>, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; cancel( params: Params$Resource$Projects$Operations$Cancel, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; cancel(callback: BodyResponseCallback<Schema$GoogleProtobufEmpty>): void; cancel( paramsOrCallback?: | Params$Resource$Projects$Operations$Cancel | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleProtobufEmpty> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Operations$Cancel; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Operations$Cancel; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://webrisk.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}:cancel').replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleProtobufEmpty>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleProtobufEmpty>(parameters); } } /** * Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/webrisk.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const webrisk = google.webrisk('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await webrisk.projects.operations.delete({ * // The name of the operation resource to be deleted. * name: 'projects/my-project/operations/my-operation', * }); * console.log(res.data); * * // Example response * // {} * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Projects$Operations$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Projects$Operations$Delete, options?: MethodOptions ): GaxiosPromise<Schema$GoogleProtobufEmpty>; delete( params: Params$Resource$Projects$Operations$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Projects$Operations$Delete, options: MethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty>, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; delete( params: Params$Resource$Projects$Operations$Delete, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; delete(callback: BodyResponseCallback<Schema$GoogleProtobufEmpty>): void; delete( paramsOrCallback?: | Params$Resource$Projects$Operations$Delete | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleProtobufEmpty> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Operations$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Operations$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://webrisk.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleProtobufEmpty>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleProtobufEmpty>(parameters); } } /** * Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/webrisk.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const webrisk = google.webrisk('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await webrisk.projects.operations.get({ * // The name of the operation resource. * name: 'projects/my-project/operations/my-operation', * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Operations$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Operations$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleLongrunningOperation>; get( params: Params$Resource$Projects$Operations$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Operations$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleLongrunningOperation>, callback: BodyResponseCallback<Schema$GoogleLongrunningOperation> ): void; get( params: Params$Resource$Projects$Operations$Get, callback: BodyResponseCallback<Schema$GoogleLongrunningOperation> ): void; get( callback: BodyResponseCallback<Schema$GoogleLongrunningOperation> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Operations$Get | BodyResponseCallback<Schema$GoogleLongrunningOperation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleLongrunningOperation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleLongrunningOperation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleLongrunningOperation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Operations$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Operations$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://webrisk.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleLongrunningOperation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleLongrunningOperation>(parameters); } } /** * Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/x/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/x\}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/webrisk.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const webrisk = google.webrisk('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await webrisk.projects.operations.list({ * // The standard list filter. * filter: 'placeholder-value', * // The name of the operation's parent resource. * name: 'projects/my-project', * // The standard list page size. * pageSize: 'placeholder-value', * // The standard list page token. * pageToken: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "operations": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Operations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Operations$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleLongrunningListOperationsResponse>; list( params: Params$Resource$Projects$Operations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Operations$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleLongrunningListOperationsResponse>, callback: BodyResponseCallback<Schema$GoogleLongrunningListOperationsResponse> ): void; list( params: Params$Resource$Projects$Operations$List, callback: BodyResponseCallback<Schema$GoogleLongrunningListOperationsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleLongrunningListOperationsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Projects$Operations$List | BodyResponseCallback<Schema$GoogleLongrunningListOperationsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleLongrunningListOperationsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleLongrunningListOperationsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleLongrunningListOperationsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Operations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Operations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://webrisk.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}/operations').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleLongrunningListOperationsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleLongrunningListOperationsResponse>( parameters ); } } } export interface Params$Resource$Projects$Operations$Cancel extends StandardParameters { /** * The name of the operation resource to be cancelled. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleLongrunningCancelOperationRequest; } export interface Params$Resource$Projects$Operations$Delete extends StandardParameters { /** * The name of the operation resource to be deleted. */ name?: string; } export interface Params$Resource$Projects$Operations$Get extends StandardParameters { /** * The name of the operation resource. */ name?: string; } export interface Params$Resource$Projects$Operations$List extends StandardParameters { /** * The standard list filter. */ filter?: string; /** * The name of the operation's parent resource. */ name?: string; /** * The standard list page size. */ pageSize?: number; /** * The standard list page token. */ pageToken?: string; } export class Resource$Projects$Submissions { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Creates a Submission of a URI suspected of containing phishing content to be reviewed. If the result verifies the existence of malicious phishing content, the site will be added to the [Google's Social Engineering lists](https://support.google.com/webmasters/answer/6350487/) in order to protect users that could get exposed to this threat in the future. Only allowlisted projects can use this method during Early Access. Please reach out to Sales or your customer engineer to obtain access. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/webrisk.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const webrisk = google.webrisk('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await webrisk.projects.submissions.create({ * // Required. The name of the project that is making the submission. This string is in the format "projects/{project_number\}". * parent: 'projects/my-project', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "threatTypes": [], * // "uri": "my_uri" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "threatTypes": [], * // "uri": "my_uri" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Projects$Submissions$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Projects$Submissions$Create, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudWebriskV1Submission>; create( params: Params$Resource$Projects$Submissions$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Projects$Submissions$Create, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudWebriskV1Submission>, callback: BodyResponseCallback<Schema$GoogleCloudWebriskV1Submission> ): void; create( params: Params$Resource$Projects$Submissions$Create, callback: BodyResponseCallback<Schema$GoogleCloudWebriskV1Submission> ): void; create( callback: BodyResponseCallback<Schema$GoogleCloudWebriskV1Submission> ): void; create( paramsOrCallback?: | Params$Resource$Projects$Submissions$Create | BodyResponseCallback<Schema$GoogleCloudWebriskV1Submission> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudWebriskV1Submission> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudWebriskV1Submission> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudWebriskV1Submission> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Submissions$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Submissions$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://webrisk.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/submissions').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudWebriskV1Submission>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudWebriskV1Submission>( parameters ); } } } export interface Params$Resource$Projects$Submissions$Create extends StandardParameters { /** * Required. The name of the project that is making the submission. This string is in the format "projects/{project_number\}". */ parent?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudWebriskV1Submission; } export class Resource$Projects$Uris { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Submits a URI suspected of containing malicious content to be reviewed. Returns a google.longrunning.Operation which, once the review is complete, is updated with its result. You can use the [Pub/Sub API] (https://cloud.google.com/pubsub) to receive notifications for the returned Operation. If the result verifies the existence of malicious content, the site will be added to the [Google's Social Engineering lists] (https://support.google.com/webmasters/answer/6350487/) in order to protect users that could get exposed to this threat in the future. Only allowlisted projects can use this method during Early Access. Please reach out to Sales or your customer engineer to obtain access. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/webrisk.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const webrisk = google.webrisk('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await webrisk.projects.uris.submit({ * // Required. The name of the project that is making the submission. This string is in the format "projects/{project_number\}". * parent: 'projects/my-project', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "submission": {} * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ submit( params: Params$Resource$Projects$Uris$Submit, options: StreamMethodOptions ): GaxiosPromise<Readable>; submit( params?: Params$Resource$Projects$Uris$Submit, options?: MethodOptions ): GaxiosPromise<Schema$GoogleLongrunningOperation>; submit( params: Params$Resource$Projects$Uris$Submit, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; submit( params: Params$Resource$Projects$Uris$Submit, options: | MethodOptions | BodyResponseCallback<Schema$GoogleLongrunningOperation>, callback: BodyResponseCallback<Schema$GoogleLongrunningOperation> ): void; submit( params: Params$Resource$Projects$Uris$Submit, callback: BodyResponseCallback<Schema$GoogleLongrunningOperation> ): void; submit( callback: BodyResponseCallback<Schema$GoogleLongrunningOperation> ): void; submit( paramsOrCallback?: | Params$Resource$Projects$Uris$Submit | BodyResponseCallback<Schema$GoogleLongrunningOperation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleLongrunningOperation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleLongrunningOperation> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleLongrunningOperation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Uris$Submit; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Uris$Submit; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://webrisk.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/uris:submit').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleLongrunningOperation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleLongrunningOperation>(parameters); } } } export interface Params$Resource$Projects$Uris$Submit extends StandardParameters { /** * Required. The name of the project that is making the submission. This string is in the format "projects/{project_number\}". */ parent?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudWebriskV1SubmitUriRequest; } export class Resource$Threatlists { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the most recent threat list diffs. These diffs should be applied to a local database of hashes to keep it up-to-date. If the local database is empty or excessively out-of-date, a complete snapshot of the database will be returned. This Method only updates a single ThreatList at a time. To update multiple ThreatList databases, this method needs to be called once for each list. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/webrisk.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const webrisk = google.webrisk('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await webrisk.threatLists.computeDiff({ * // Sets the maximum number of entries that the client is willing to have in the local database. This should be a power of 2 between 2**10 and 2**20. If zero, no database size limit is set. * 'constraints.maxDatabaseEntries': 'placeholder-value', * // The maximum size in number of entries. The diff will not contain more entries than this value. This should be a power of 2 between 2**10 and 2**20. If zero, no diff size limit is set. * 'constraints.maxDiffEntries': 'placeholder-value', * // The compression types supported by the client. * 'constraints.supportedCompressions': 'placeholder-value', * // Required. The threat list to update. Only a single ThreatType should be specified per request. If you want to handle multiple ThreatTypes, you must make one request per ThreatType. * threatType: 'placeholder-value', * // The current version token of the client for the requested list (the client version that was received from the last successful diff). If the client does not have a version token (this is the first time calling ComputeThreatListDiff), this may be left empty and a full database snapshot will be returned. * versionToken: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "additions": {}, * // "checksum": {}, * // "newVersionToken": "my_newVersionToken", * // "recommendedNextDiff": "my_recommendedNextDiff", * // "removals": {}, * // "responseType": "my_responseType" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ computeDiff( params: Params$Resource$Threatlists$Computediff, options: StreamMethodOptions ): GaxiosPromise<Readable>; computeDiff( params?: Params$Resource$Threatlists$Computediff, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponse>; computeDiff( params: Params$Resource$Threatlists$Computediff, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; computeDiff( params: Params$Resource$Threatlists$Computediff, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponse>, callback: BodyResponseCallback<Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponse> ): void; computeDiff( params: Params$Resource$Threatlists$Computediff, callback: BodyResponseCallback<Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponse> ): void; computeDiff( callback: BodyResponseCallback<Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponse> ): void; computeDiff( paramsOrCallback?: | Params$Resource$Threatlists$Computediff | BodyResponseCallback<Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Threatlists$Computediff; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Threatlists$Computediff; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://webrisk.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/threatLists:computeDiff').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudWebriskV1ComputeThreatListDiffResponse>( parameters ); } } } export interface Params$Resource$Threatlists$Computediff extends StandardParameters { /** * Sets the maximum number of entries that the client is willing to have in the local database. This should be a power of 2 between 2**10 and 2**20. If zero, no database size limit is set. */ 'constraints.maxDatabaseEntries'?: number; /** * The maximum size in number of entries. The diff will not contain more entries than this value. This should be a power of 2 between 2**10 and 2**20. If zero, no diff size limit is set. */ 'constraints.maxDiffEntries'?: number; /** * The compression types supported by the client. */ 'constraints.supportedCompressions'?: string[]; /** * Required. The threat list to update. Only a single ThreatType should be specified per request. If you want to handle multiple ThreatTypes, you must make one request per ThreatType. */ threatType?: string; /** * The current version token of the client for the requested list (the client version that was received from the last successful diff). If the client does not have a version token (this is the first time calling ComputeThreatListDiff), this may be left empty and a full database snapshot will be returned. */ versionToken?: string; } export class Resource$Uris { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * This method is used to check whether a URI is on a given threatList. Multiple threatLists may be searched in a single query. The response will list all requested threatLists the URI was found to match. If the URI is not found on any of the requested ThreatList an empty response will be returned. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/webrisk.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const webrisk = google.webrisk('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await webrisk.uris.search({ * // Required. The ThreatLists to search in. Multiple ThreatLists may be specified. * threatTypes: 'placeholder-value', * // Required. The URI to be checked for matches. * uri: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "threat": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ search( params: Params$Resource$Uris$Search, options: StreamMethodOptions ): GaxiosPromise<Readable>; search( params?: Params$Resource$Uris$Search, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudWebriskV1SearchUrisResponse>; search( params: Params$Resource$Uris$Search, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; search( params: Params$Resource$Uris$Search, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchUrisResponse>, callback: BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchUrisResponse> ): void; search( params: Params$Resource$Uris$Search, callback: BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchUrisResponse> ): void; search( callback: BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchUrisResponse> ): void; search( paramsOrCallback?: | Params$Resource$Uris$Search | BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchUrisResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchUrisResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudWebriskV1SearchUrisResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudWebriskV1SearchUrisResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Uris$Search; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Uris$Search; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://webrisk.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/uris:search').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudWebriskV1SearchUrisResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudWebriskV1SearchUrisResponse>( parameters ); } } } export interface Params$Resource$Uris$Search extends StandardParameters { /** * Required. The ThreatLists to search in. Multiple ThreatLists may be specified. */ threatTypes?: string[]; /** * Required. The URI to be checked for matches. */ uri?: string; } }
the_stack
import React from 'react'; import path from "path"; import fs from "fs"; import escapeHTML from 'escape-html'; import {BrowserViewIPC} from '../../../IPC/BrowserViewIPC'; import {MainWindowIPC} from '../../../IPC/MainWindowIPC'; import {UserPrefRepo} from '../../Repository/UserPrefRepo'; import {IssueEntity} from '../../Library/Type/IssueEntity'; import {IssueRepo} from '../../Repository/IssueRepo'; import {IssueEvent} from '../../Event/IssueEvent'; import {GitHubIssueClient} from '../../Library/GitHub/GitHubIssueClient'; import {GitHubUtil} from '../../Library/Util/GitHubUtil'; import {GetIssueStateEntity} from '../../Library/Type/GetIssueStateEntity'; import {StreamEntity} from '../../Library/Type/StreamEntity'; import {StreamEvent} from '../../Event/StreamEvent'; import {ShellUtil} from '../../Library/Util/ShellUtil'; import {appTheme} from '../../Library/Style/appTheme'; const jsdiff = require('diff'); // hack: support japanese tokenize require('diff/lib/diff/word').wordDiff.tokenize = function(value){ return value.split(/(\s+|\b|、|。|「|」)/u); }; type Props = { } type State = { issue: IssueEntity | null; readBody: string; } export class BrowserCodeExecFragment extends React.Component<Props, State> { state: State = { issue: null, readBody: '', } private readonly css: string; private readonly jsExternalBrowser: string; private readonly jsShowDiffBody: string; private readonly jsUpdateBySelf: string; private readonly jsHighlightAndScroll: string; private readonly jsDetectInput: string; private readonly jsGetIssueState: string; private readonly jsProjectBoard: string; private readonly jsDarkReader: string; private projectStream: StreamEntity | null; constructor(props) { super(props); const dir = path.resolve(__dirname, './BrowserFragmentAsset/'); this.css = fs.readFileSync(`${dir}/style.css`).toString(); this.jsExternalBrowser = fs.readFileSync(`${dir}/external-browser.js`).toString(); this.jsShowDiffBody = fs.readFileSync(`${dir}/show-diff-body.js`).toString(); this.jsUpdateBySelf = fs.readFileSync(`${dir}/update-by-self.js`).toString(); this.jsHighlightAndScroll = fs.readFileSync(`${dir}/highlight-and-scroll.js`).toString(); this.jsDetectInput = fs.readFileSync(`${dir}/detect-input.js`).toString(); this.jsGetIssueState = fs.readFileSync(`${dir}/get-issue-state.js`).toString(); this.jsProjectBoard = fs.readFileSync(`${dir}/project-board.js`).toString(); this.jsDarkReader = fs.readFileSync(`${dir}/darkreader.js`).toString(); } componentDidMount() { this.setupDetectInput(); this.setupCSS(); this.setupExternalBrowser(); this.setupUpdateBySelf(); this.setupHighlightAndScrollLast(); this.setupShowDiffBody(); this.setupGetIssueState(); this.setupProjectBoard(); this.setupDarkReader(); IssueEvent.onSelectIssue(this, (issue, readBody) => this.setState({issue, readBody})); } componentWillUnmount() { IssueEvent.offAll(this); } private setupDetectInput() { BrowserViewIPC.onEventDOMReady(() => BrowserViewIPC.executeJavaScript(this.jsDetectInput)); BrowserViewIPC.onEventConsoleMessage((_level, message)=>{ if (message.indexOf('DETECT_INPUT:') === 0) { const res = message.split('DETECT_INPUT:')[1]; if (res === 'true') { MainWindowIPC.keyboardShortcut(false); } else { MainWindowIPC.keyboardShortcut(true); } } }); } private setupExternalBrowser() { BrowserViewIPC.onEventDOMReady(() => { const always = UserPrefRepo.getPref().general.alwaysOpenExternalUrlInExternalBrowser; const code = this.jsExternalBrowser.replace('_alwaysOpenExternalUrlInExternalBrowser_', `${always}`); BrowserViewIPC.executeJavaScript(code); }); BrowserViewIPC.onEventConsoleMessage((_level, message)=>{ if (message.indexOf('OPEN_EXTERNAL_BROWSER:') === 0) { const url = message.split('OPEN_EXTERNAL_BROWSER:')[1]; ShellUtil.openExternal(url); } }); } private setupHighlightAndScrollLast() { BrowserViewIPC.onEventDOMReady(() => { if (!this.isTargetIssuePage()) return; // if issue body was updated, does not scroll to last comment. let updatedBody = false; if (this.state.issue && this.state.readBody) { if (this.state.readBody !== this.state.issue.body) updatedBody = true; } let prevReadAt; if (this.state.issue) prevReadAt = new Date(this.state.issue.prev_read_at).getTime(); const code = this.jsHighlightAndScroll.replace('_prevReadAt_', prevReadAt).replace('_updatedBody_', `${updatedBody}`); BrowserViewIPC.executeJavaScript(code); }); } private setupShowDiffBody() { BrowserViewIPC.onEventDOMReady(() => { if (!this.isTargetIssuePage()) return; let diffBodyHTMLWord = ''; let diffBodyHTMLChar = ''; if (this.state.issue && this.state.readBody) { if (this.state.readBody === this.state.issue.body) return; // word diff { const diffBody = jsdiff.diffWords(this.state.readBody, this.state.issue.body); diffBody.forEach(function(part){ const type = part.added ? 'add' : part.removed ? 'delete' : 'normal'; const value = escapeHTML(part.value.replace(/`/g, '\\`')); diffBodyHTMLWord += `<span class="diff-body-${type}">${value}</span>`; }); } // char diff { const diffBody = jsdiff.diffChars(this.state.readBody, this.state.issue.body); diffBody.forEach(function(part){ const type = part.added ? 'add' : part.removed ? 'delete' : 'normal'; const value = escapeHTML(part.value.replace(/`/g, '\\`')); diffBodyHTMLChar += `<span class="diff-body-${type}">${value}</span>`; }); } } if (!diffBodyHTMLWord.length) return; const code = this.jsShowDiffBody .replace('_diffBodyHTML_Word_', diffBodyHTMLWord) .replace('_diffBodyHTML_Char_', diffBodyHTMLChar); BrowserViewIPC.executeJavaScript(code); }); BrowserViewIPC.onEventConsoleMessage((_level, message)=> { if (message.indexOf('OPEN_DIFF_BODY:') !== 0) return; }); } private setupUpdateBySelf() { BrowserViewIPC.onEventDOMReady(() => { if (!this.isTargetIssuePage()) return; const code = this.jsUpdateBySelf.replace('_loginName_', UserPrefRepo.getUser().login); BrowserViewIPC.executeJavaScript(code); }); BrowserViewIPC.onEventDidNavigateInPage(() => { if (!this.isTargetIssuePage()) return; const code = this.jsUpdateBySelf.replace('_loginName_', UserPrefRepo.getUser().login); BrowserViewIPC.executeJavaScript(code); }); let isRequesting = false; BrowserViewIPC.onEventConsoleMessage((_level, message)=>{ if (!this.isTargetIssuePage()) return; if (['UPDATE_BY_SELF:', 'UPDATE_COMMENT_BY_SELF:'].includes(message) === false) return; if (isRequesting) return; isRequesting = true; async function update(issue){ const github = UserPrefRepo.getPref().github; const client = new GitHubIssueClient(github.accessToken, github.host, github.pathPrefix, github.https); const repo = issue.repo; const number = issue.number; try { const res = await client.getIssue(repo, number); if (res.error) return console.error(res.error); const updatedIssue = res.issue; const date = new Date(updatedIssue.updated_at); await IssueRepo.updateRead(issue.id, date); const res2 = await IssueRepo.updateRead(issue.id, date); if (res2.error) return console.error(res2.error); } catch (e) { console.error(e); } isRequesting = false; } update(this.state.issue); }); } private setupCSS() { BrowserViewIPC.onEventDOMReady(() => { if (!this.isTargetHost()) return; BrowserViewIPC.insertCSS(this.css); }); } // todo: v0.10.0でmerged_atに対応したときに、過去分へのadhocな対応として実装したものなので、いずれ削除する private setupGetIssueState() { BrowserViewIPC.onEventDOMReady(() => BrowserViewIPC.executeJavaScript(this.jsGetIssueState)); BrowserViewIPC.onEventConsoleMessage((_level, message)=>{ if (message.indexOf('GET_ISSUE_STATE:') === 0) { const res = message.split('GET_ISSUE_STATE:')[1]; const obj = JSON.parse(res) as GetIssueStateEntity; this.handlePRMerged(obj); } }); } // 読み込んだPRはマージ状態だが、merged_atが保存されていない場合、closed_atで更新する private async handlePRMerged(issueState: GetIssueStateEntity) { if (issueState.issueType === 'pr' && issueState.issueState === 'merged' && issueState.issueNumber) { const {error, issue} = await IssueRepo.getIssueByIssueNumber(issueState.repo, issueState.issueNumber); if (error) return console.error(error); if (!issue.merged_at && issue.closed_at) { const {error, issue: updatedIssue} = await IssueRepo.updateMerged(issue.id, issue.closed_at); if (error) return console.error(error); IssueEvent.emitUpdateIssues([updatedIssue], [issue], 'merged'); } } } private async setupProjectBoard() { StreamEvent.onSelectStream(this, (stream) => { if (stream.type === 'ProjectStream') this.projectStream = stream; }); BrowserViewIPC.onEventDOMReady(() => this.handleProjectBoardInit()); BrowserViewIPC.onEventConsoleMessage((_level, message) => this.handleProjectBoardConsoleMessage(message)); } private async handleProjectBoardInit() { if (this.projectStream?.type !== 'ProjectStream') return; if (!GitHubUtil.isProjectUrl(UserPrefRepo.getPref().github.webHost, this.projectStream.queries[0])) return; const stream = this.projectStream; const {error, issues} = await IssueRepo.getIssuesInStream(stream.queryStreamId, stream.defaultFilter, stream.userFilter, 0, 1000); if (error) return console.error(error); const transferIssues = issues.map(issue => { return {id: issue.id, repo: issue.repo, number: issue.number, isRead: IssueRepo.isRead(issue)}; }); const js = this.jsProjectBoard .replace(`__ISSUES__`, JSON.stringify(transferIssues)) .replace(`__IS_DARK_MODE__`, `${UserPrefRepo.getThemeName() === 'dark'}`); await BrowserViewIPC.executeJavaScript(js); } private async handleProjectBoardConsoleMessage(message: string) { if (message.indexOf('PROJECT_BOARD_ACTION:') !== 0) return; const json = message.split('PROJECT_BOARD_ACTION:')[1]; const obj = JSON.parse(json) as {action: string; url: string}; if (obj.action === 'select') { const {repo, issueNumber} = GitHubUtil.getInfo(obj.url); const {error, issue} = await IssueRepo.getIssueByIssueNumber(repo, issueNumber); if (error) return console.error(error); await StreamEvent.emitSelectStream(this.projectStream, issue); } } private setupDarkReader() { const js = ` ${this.jsDarkReader} // dark readerが外部リソースを取得しようとしてクロスオリジンに引っかかってしまう // なので、setFetchMethodを使って、ダミーを返すようにする DarkReader.setFetchMethod(async () => { const blob = new Blob([' '], {type: 'text/plain'}); return {blob: () => blob}; }); DarkReader.enable({brightness: 100, contrast: 100}); document.body.classList.add('jasper-dark-mode'); setTimeout(() => { document.body.style.visibility = 'visible'; }, 16); `; const hideBody = () => { const theme = UserPrefRepo.getThemeName(); if (theme === 'dark' && UserPrefRepo.getPref().general.style.enableThemeModeOnGitHub) { BrowserViewIPC.insertCSS(`html { background: ${appTheme().bg.primary}; } body { visibility: hidden; }`); } }; BrowserViewIPC.onEventDidStartNavigation(hideBody); BrowserViewIPC.onEventDidNavigate(hideBody); BrowserViewIPC.onEventDOMReady(async () => { const theme = UserPrefRepo.getThemeName(); if (theme === 'dark' && UserPrefRepo.getPref().general.style.enableThemeModeOnGitHub) { BrowserViewIPC.executeJavaScript(js); } }); } private isTargetIssuePage() { // if (!this.state.issue) return false; // // const issueUrl = this.state.issue.html_url; // const validUrls = [issueUrl, `${issueUrl}/files`]; // return validUrls.includes(BrowserViewIPC.getURL()); return GitHubUtil.isTargetIssuePage(BrowserViewIPC.getURL(), this.state.issue); } private isTargetHost() { const url = new URL(BrowserViewIPC.getURL()); return UserPrefRepo.getPref().github.webHost === url.host; } render() { return null; } }
the_stack
namespace egret.sys { /** * @private */ export const enum TextKeys { /** * @private */ fontSize, /** * @private */ lineSpacing, /** * @private */ textColor, /** * @private */ textFieldWidth, /** * @private */ textFieldHeight, /** * @private */ textWidth, /** * @private */ textHeight, /** * @private */ textDrawWidth, /** * @private */ fontFamily, /** * @private */ textAlign, /** * @private */ verticalAlign, /** * @private */ textColorString, /** * @private */ fontString, /** * @private */ text, /** * @private */ measuredWidths, /** * @private */ bold, /** * @private */ italic, /** * @private */ fontStringChanged, /** * @private */ textLinesChanged, /** * @private */ wordWrap, /** * @private */ displayAsPassword, /** * @private */ maxChars, /** * @private */ selectionActivePosition, /** * @private */ selectionAnchorPosition, /** * @private */ type, /** * @private */ strokeColor, /** * @private */ strokeColorString, /** * @private */ stroke, /** * @private */ scrollV, /** * @private */ numLines, /** * @private */ multiline, /** * @private */ border, /** * @private */ borderColor, /** * @private */ background, /** * @private */ backgroundColor, /** * @private */ restrictAnd, /** * @private */ restrictNot, /** * @private */ inputType, /** * @private */ textLinesChangedForNativeRender } } namespace egret { let defaultRegex = "(?=[\\u00BF-\\u1FFF\\u2C00-\\uD7FF]|\\b|\\s)(?![0-9])(?![。,!、》…))}”】\\.\\,\\!\\?\\]\\:])"; let SplitRegex: RegExp; /** * @private */ let usingWordWrap = [ ] /** * @private */ let languageWordWrapMap = { "Vietnamese": "?![ẮẰẲẴẶĂẤẦẨẪẬÂÁÀÃẢẠĐẾỀỂỄỆÊÉÈẺẼẸÍÌỈĨỊỐỒỔỖỘÔỚỜỞỠỢƠÓÒÕỎỌỨỪỬỮỰƯÚÙỦŨỤÝỲỶỸỴA-Z]" } /** * add new language word wrap regex and use it * if languageKey already exists,the existing regex is replaced * if the pattern is not passed,it will be found and enabled int the existing word wrap map * @param languageKey * @param pattern * @version Egret 5.3.11 * @platform Web * @language en_US */ /** * 添加新的自动换行的语言正则表达式匹配并启用 * 如果已经有该语言了,则会替换现有正则表达式 * 不传入正则表达式则会在已有的语言自动换行匹配串中寻找并启用 * @param languageKey * @param pattern * @version Egret 5.3.11 * @platform Web * @language zh_CN */ export function addLanguageWordWrapRegex(languageKey: string, pattern?: string): void { if (pattern != undefined) { languageWordWrapMap[languageKey] = pattern; } if (usingWordWrap.indexOf(languageKey) < 0 && languageWordWrapMap[languageKey] != undefined) { usingWordWrap.push(languageKey); } updateWordWrapRegex(); } /** * return the existing word wrap keys * @version Egret 5.3.11 * @platform Web * @language en_US */ /** * 获取当前已有的自动换行映射键值组 * @version Egret 5.3.11 * @platform Web * @language zh_CN */ export function getAllSupportLanguageWordWrap(): string[] { const result: string[] = []; for (let key in languageWordWrapMap) { result.push(key); } return result; } /** * return the using word wrap keys * @version Egret 5.3.11 * @platform Web * @language en_US */ /** * 获取当前正在使用中的自动换行映射键值组 * @version Egret 5.3.11 * @platform Web * @language zh_CN */ export function getUsingWordWrap(): string[] { return usingWordWrap; } /** * cancels the using word wrap regex by the languageKey * @version Egret 5.3.11 * @platform Web * @language en_US */ /** * 根据languageKey取消正在启用的自动换行正则表达式 * @version Egret 5.3.11 * @platform Web * @language zh_CN */ export function cancelLanguageWordWrapRegex(languageKey: string): void { const index = usingWordWrap.indexOf(languageKey); if (index > -1) { usingWordWrap.splice(index, 1); } updateWordWrapRegex(); } /** * @private */ function updateWordWrapRegex() { let extendRegex = defaultRegex; for (let key of usingWordWrap) { if (languageWordWrapMap[key]) { extendRegex += "(" + languageWordWrapMap[key] + ")"; } } SplitRegex = new RegExp(extendRegex, "i"); } updateWordWrapRegex(); /** * @private * 根据样式测量文本宽度 */ function measureTextWidth(text, values: any, style?: ITextStyle): number { style = style || <egret.ITextStyle>{}; let italic: boolean = style.italic == null ? values[sys.TextKeys.italic] : style.italic; let bold: boolean = style.bold == null ? values[sys.TextKeys.bold] : style.bold; let size: number = style.size == null ? values[sys.TextKeys.fontSize] : style.size; let fontFamily: string = style.fontFamily || values[sys.TextKeys.fontFamily] || TextField.default_fontFamily; return sys.measureText(text, fontFamily, size, bold, italic); } /** * TextField is the text rendering class of egret. It conducts rendering by using the browser / device API. Due to different ways of font rendering in different browsers / devices, there may be differences in the rendering * If developers expect no differences among all platforms, please use BitmapText * @see http://edn.egret.com/cn/docs/page/141 Create Text * * @event egret.Event.CHANGE Dispatched when entering text user input。 * @event egret.FocusEvent.FOCUS_IN Dispatched after the focus to enter text. * @event egret.FocusEvent.FOCUS_OUT Enter the text loses focus after dispatch. * @version Egret 2.4 * @platform Web,Native * @includeExample egret/text/TextField.ts * @language en_US */ /** * TextField是egret的文本渲染类,采用浏览器/设备的API进行渲染,在不同的浏览器/设备中由于字体渲染方式不一,可能会有渲染差异 * 如果开发者希望所有平台完全无差异,请使用BitmapText * @see http://edn.egret.com/cn/docs/page/141 创建文本 * * @event egret.Event.CHANGE 输入文本有用户输入时调度。 * @event egret.FocusEvent.FOCUS_IN 聚焦输入文本后调度。 * @event egret.FocusEvent.FOCUS_OUT 输入文本失去焦点后调度。 * @version Egret 2.4 * @platform Web,Native * @includeExample egret/text/TextField.ts * @language zh_CN */ export class TextField extends DisplayObject { /** * default fontFamily * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 默认文本字体 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static default_fontFamily: string = "Arial"; /** * default size in pixels of text * @version Egret 3.2.1 * @platform Web,Native * @language en_US */ /** * 默认文本字号大小 * @version Egret 3.2.1 * @platform Web,Native * @language zh_CN */ public static default_size: number = 30; /** * default color of the text. * @version Egret 3.2.1 * @platform Web,Native * @language en_US */ /** * 默认文本颜色 * @version Egret 3.2.1 * @platform Web,Native * @language zh_CN */ public static default_textColor: number = 0xffffff; /** * @version Egret 2.4 * @platform Web,Native */ constructor() { super(); let textNode = new sys.TextNode(); textNode.fontFamily = TextField.default_fontFamily; this.textNode = textNode; this.$renderNode = textNode; this.$TextField = { 0: TextField.default_size, //fontSize 1: 0, //lineSpacing 2: TextField.default_textColor, //textColor 3: NaN, //textFieldWidth 4: NaN, //textFieldHeight 5: 0, //textWidth 6: 0, //textHeight 7: 0, //textDrawWidth 8: TextField.default_fontFamily, //fontFamily 9: "left", //textAlign 10: "top", //verticalAlign 11: "#ffffff", //textColorString 12: "", //fontString 13: "", //text 14: [], //measuredWidths 15: false, //bold, 16: false, //italic, 17: true, //fontStringChanged, 18: false, //textLinesChanged, 19: false, //wordWrap 20: false, //displayAsPassword 21: 0, //maxChars 22: 0, //selectionActivePosition, 23: 0, //selectionAnchorPosition, 24: TextFieldType.DYNAMIC, //type 25: 0x000000, //strokeColor 26: "#000000", //strokeColorString 27: 0, //stroke 28: -1, //scrollV 29: 0, //numLines 30: false, //multiline 31: false, //border 32: 0x000000, //borderColor 33: false, //background 34: 0xffffff, //backgroundColor 35: null, //restrictAnd 36: null, //restrictNot 37: TextFieldInputType.TEXT, //inputType 38: false //textLinesChangedForNativeRender }; if (egret.nativeRender) { this.$nativeDisplayObject.setFontFamily(TextField.default_fontFamily); this.$nativeDisplayObject.setFontSize(TextField.default_size); } } protected createNativeDisplayObject(): void { this.$nativeDisplayObject = new egret_native.NativeDisplayObject(egret_native.NativeObjectType.TEXT); } /** * @private */ $TextField: Object; /** * @private */ private isInput(): boolean { return this.$TextField[sys.TextKeys.type] == TextFieldType.INPUT; } $inputEnabled: boolean = false; $setTouchEnabled(value: boolean): void { super.$setTouchEnabled(value); if (this.isInput()) { this.$inputEnabled = true; } } /** * The name of the font to use, or a comma-separated list of font names. * @default "Arial" * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 要使用的字体的名称或用逗号分隔的字体名称列表。 * @default "Arial" * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get fontFamily(): string { return this.$TextField[sys.TextKeys.fontFamily]; } public set fontFamily(value: string) { this.$setFontFamily(value); } $setFontFamily(value: string): boolean { let values = this.$TextField; if (values[sys.TextKeys.fontFamily] == value) { return false; } values[sys.TextKeys.fontFamily] = value; this.invalidateFontString(); if (egret.nativeRender) { this.$nativeDisplayObject.setFontFamily(value); } return true; } /** * The size in pixels of text * @default 30 * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 文本的字号大小。 * @default 30 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get size(): number { return this.$TextField[sys.TextKeys.fontSize]; } public set size(value: number) { this.$setSize(value); } $setSize(value: number): boolean { let values = this.$TextField; if (values[sys.TextKeys.fontSize] == value) { return false; } values[sys.TextKeys.fontSize] = value; this.invalidateFontString(); if (egret.nativeRender) { this.$nativeDisplayObject.setFontSize(value); } return true; } /** * Specifies whether the text is boldface. * @default false * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 是否显示为粗体。 * @default false * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get bold(): boolean { return this.$TextField[sys.TextKeys.bold]; } public set bold(value: boolean) { this.$setBold(value); } $setBold(value: boolean): boolean { let values = this.$TextField; if (value == values[sys.TextKeys.bold]) { return false; } values[sys.TextKeys.bold] = value; this.invalidateFontString(); if (egret.nativeRender) { this.$nativeDisplayObject.setBold(value); } return true; } /** * Determines whether the text is italic font. * @default false * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 是否显示为斜体。 * @default false * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get italic(): boolean { return this.$TextField[sys.TextKeys.italic]; } public set italic(value: boolean) { this.$setItalic(value); } $setItalic(value: boolean): boolean { let values = this.$TextField; if (value == values[sys.TextKeys.italic]) { return false; } values[sys.TextKeys.italic] = value; this.invalidateFontString(); if (egret.nativeRender) { this.$nativeDisplayObject.setItalic(value); } return true; } /** * @private * */ private invalidateFontString(): void { this.$TextField[sys.TextKeys.fontStringChanged] = true; this.$invalidateTextField(); } /** * Horizontal alignment of text. * @default:egret.HorizontalAlign.LEFT * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 文本的水平对齐方式。 * @default:egret.HorizontalAlign.LEFT * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get textAlign(): string { return this.$TextField[sys.TextKeys.textAlign]; } public set textAlign(value: string) { this.$setTextAlign(value); } $setTextAlign(value: string): boolean { let values = this.$TextField; if (values[sys.TextKeys.textAlign] == value) { return false; } values[sys.TextKeys.textAlign] = value; this.$invalidateTextField(); if (egret.nativeRender) { this.$nativeDisplayObject.setTextAlign(value); } return true; } /** * Vertical alignment of text. * @default:egret.VerticalAlign.TOP * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 文字的垂直对齐方式。 * @default:egret.VerticalAlign.TOP * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get verticalAlign(): string { return this.$TextField[sys.TextKeys.verticalAlign]; } public set verticalAlign(value: string) { this.$setVerticalAlign(value); } $setVerticalAlign(value: string): boolean { let values = this.$TextField; if (values[sys.TextKeys.verticalAlign] == value) { return false; } values[sys.TextKeys.verticalAlign] = value; this.$invalidateTextField(); if (egret.nativeRender) { this.$nativeDisplayObject.setVerticalAlign(value); } return true; } /** * An integer representing the amount of vertical space between lines. * @default 0 * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 一个整数,表示行与行之间的垂直间距量 * @default 0 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get lineSpacing(): number { return this.$TextField[sys.TextKeys.lineSpacing]; } public set lineSpacing(value: number) { this.$setLineSpacing(value); } $setLineSpacing(value: number): boolean { let values = this.$TextField; if (values[sys.TextKeys.lineSpacing] == value) { return false; } values[sys.TextKeys.lineSpacing] = value; this.$invalidateTextField(); if (egret.nativeRender) { this.$nativeDisplayObject.setLineSpacing(value); } return true; } /** * Color of the text. * @default 0x000000 * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 文本颜色 * @default 0x000000 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get textColor(): number { return this.$TextField[sys.TextKeys.textColor]; } public set textColor(value: number) { this.$setTextColor(value); } $setTextColor(value: number): boolean { let values = this.$TextField; if (values[sys.TextKeys.textColor] == value) { return false; } values[sys.TextKeys.textColor] = value; if (this.inputUtils) { this.inputUtils._setColor(this.$TextField[sys.TextKeys.textColor]); } this.$invalidateTextField(); if (egret.nativeRender) { this.$nativeDisplayObject.setTextColor(value); } return true; } /** * A Boolean value that indicates whether the text field word wrap. If the value is true, then the text field by word wrap; * if the value is false, the text field by newline characters. * @default false * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 一个布尔值,表示文本字段是否按单词换行。如果值为 true,则该文本字段按单词换行; * 如果值为 false,则该文本字段按字符换行。 * @default false * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get wordWrap(): boolean { return this.$TextField[sys.TextKeys.wordWrap]; } public set wordWrap(value: boolean) { this.$setWordWrap(value); } $setWordWrap(value: boolean): void { let values = this.$TextField; if (value == values[sys.TextKeys.wordWrap]) { return; } if (values[sys.TextKeys.displayAsPassword]) { return; } values[sys.TextKeys.wordWrap] = value; this.$invalidateTextField(); if (egret.nativeRender) { this.$nativeDisplayObject.setWordWrap(value); } } protected inputUtils: InputController = null; /** * Type of the text field. * Any one of the following TextFieldType constants: TextFieldType.DYNAMIC (specifies the dynamic text field that users can not edit), or TextFieldType.INPUT (specifies the dynamic text field that users can edit). * @default egret.TextFieldType.DYNAMIC * @language en_US */ /** * 文本字段的类型。 * 以下 TextFieldType 常量中的任一个:TextFieldType.DYNAMIC(指定用户无法编辑的动态文本字段),或 TextFieldType.INPUT(指定用户可以编辑的输入文本字段)。 * @default egret.TextFieldType.DYNAMIC * @language zh_CN */ public set type(value: string) { this.$setType(value); } /** * @private * * @param value */ $setType(value: string): boolean { let values = this.$TextField; if (values[sys.TextKeys.type] != value) { values[sys.TextKeys.type] = value; if (egret.nativeRender) { this.$nativeDisplayObject.setType(value); } if (value == TextFieldType.INPUT) {//input,如果没有设置过宽高,则设置默认值为100,30 if (isNaN(values[sys.TextKeys.textFieldWidth])) { this.$setWidth(100); } if (isNaN(values[sys.TextKeys.textFieldHeight])) { this.$setHeight(30); } this.$setTouchEnabled(true); //创建stageText if (this.inputUtils == null) { this.inputUtils = new egret.InputController(); } this.inputUtils.init(this); this.$invalidateTextField(); if (this.$stage) { this.inputUtils._addStageText(); } } else { if (this.inputUtils) { this.inputUtils._removeStageText(); this.inputUtils = null; } this.$setTouchEnabled(false); } return true; } return false; } /** * @version Egret 2.4 * @platform Web,Native */ public get type(): string { return this.$TextField[sys.TextKeys.type]; } /** * Pop-up keyboard type. * Any of a TextFieldInputType constants. * @language en_US */ /** * 弹出键盘的类型。 * TextFieldInputType 常量中的任一个。 * @language zh_CN */ public set inputType(value: string) { if (this.$TextField[sys.TextKeys.inputType] == value) { return; } this.$TextField[sys.TextKeys.inputType] = value; if (egret.nativeRender) { this.$nativeDisplayObject.setInputType(value); } } /** * @version Egret 3.1.2 * @platform Web,Native */ public get inputType(): string { return this.$TextField[sys.TextKeys.inputType]; } /** * @version Egret 2.4 * @platform Web,Native */ public get text(): string { return this.$getText(); } /** * @private * * @returns */ public $getText(): string { if (this.$TextField[sys.TextKeys.type] == egret.TextFieldType.INPUT) { return this.inputUtils._getText(); } return this.$TextField[sys.TextKeys.text]; } /** * Serve as a string of the current text field in the text * @language en_US */ /** * 作为文本字段中当前文本的字符串 * @language zh_CN */ public set text(value: string) { this.$setText(value); } /** * @private * * @param value */ $setBaseText(value: string): boolean { if (value == null) { value = ""; } else { value = value.toString(); } this.isFlow = false; let values = this.$TextField; if (values[sys.TextKeys.text] != value) { this.$invalidateTextField(); values[sys.TextKeys.text] = value; let text: string = ""; if (values[sys.TextKeys.displayAsPassword]) { text = this.changeToPassText(value); } else { text = value; } if (egret.nativeRender) { this.$nativeDisplayObject.setText(text); } this.setMiddleStyle([<egret.ITextElement>{ text: text }]); return true; } return false; } /** * @private * * @param value */ $setText(value: string): boolean { if (value == null) { value = ""; } let result: boolean = this.$setBaseText(value); if (this.inputUtils) { this.inputUtils._setText(this.$TextField[sys.TextKeys.text]); } return result; } /** * Specify whether the text field is a password text field. * If the value of this property is true, the text field is treated as a password text field and hides the input characters using asterisks instead of the actual characters. If false, the text field is not treated as a password text field. * @default false * @language en_US */ /** * 指定文本字段是否是密码文本字段。 * 如果此属性的值为 true,则文本字段被视为密码文本字段,并使用星号而不是实际字符来隐藏输入的字符。如果为 false,则不会将文本字段视为密码文本字段。 * @default false * @language zh_CN */ public get displayAsPassword(): boolean { return this.$TextField[sys.TextKeys.displayAsPassword]; } public set displayAsPassword(value: boolean) { this.$setDisplayAsPassword(value); } /** * @private * * @param value */ $setDisplayAsPassword(value: boolean): boolean { let values = this.$TextField; if (values[sys.TextKeys.displayAsPassword] != value) { values[sys.TextKeys.displayAsPassword] = value; this.$invalidateTextField(); let text: string = ""; if (value) { text = this.changeToPassText(values[sys.TextKeys.text]); } else { text = values[sys.TextKeys.text]; } if (egret.nativeRender) { this.$nativeDisplayObject.setText(text); } this.setMiddleStyle([<egret.ITextElement>{ text: text }]); return true; } return false; } /** * @version Egret 2.4 * @platform Web,Native */ public get strokeColor(): number { return this.$TextField[sys.TextKeys.strokeColor]; } /** * Represent the stroke color of the text. * Contain three 8-bit numbers with RGB color components; for example, 0xFF0000 is red, 0x00FF00 is green. * @default 0x000000 * @language en_US */ /** * 表示文本的描边颜色。 * 包含三个 8 位 RGB 颜色成分的数字;例如,0xFF0000 为红色,0x00FF00 为绿色。 * @default 0x000000 * @language zh_CN */ public set strokeColor(value: number) { this.$setStrokeColor(value); } /** * @private * * @param value */ $setStrokeColor(value: number): boolean { let values = this.$TextField; if (values[sys.TextKeys.strokeColor] != value) { this.$invalidateTextField(); values[sys.TextKeys.strokeColor] = value; if (egret.nativeRender) { this.$nativeDisplayObject.setStrokeColor(value); } values[sys.TextKeys.strokeColorString] = toColorString(value); return true; } return false; } /** * @version Egret 2.4 * @platform Web,Native */ public get stroke(): number { return this.$TextField[sys.TextKeys.stroke]; } /** * Indicate the stroke width. * 0 means no stroke. * @default 0 * @language en_US */ /** * 表示描边宽度。 * 0为没有描边。 * @default 0 * @language zh_CN */ public set stroke(value: number) { this.$setStroke(value); } /** * @private * * @param value */ $setStroke(value: number): boolean { if (this.$TextField[sys.TextKeys.stroke] != value) { this.$invalidateTextField(); this.$TextField[sys.TextKeys.stroke] = value; if (egret.nativeRender) { this.$nativeDisplayObject.setStroke(value); } return true; } return false; } /** * The maximum number of characters that the text field can contain, as entered by a user. \n A script can insert more text than maxChars allows; the maxChars property indicates only how much text a user can enter. If the value of this property is 0, a user can enter an unlimited amount of text. * The default value is 0. * @default 0 * @language en_US */ /** * 文本字段中最多可包含的字符数(即用户输入的字符数)。 * 脚本可以插入比 maxChars 允许的字符数更多的文本;maxChars 属性仅表示用户可以输入多少文本。如果此属性的值为 0,则用户可以输入无限数量的文本。 * @default 0 * @language zh_CN */ public get maxChars(): number { return this.$TextField[sys.TextKeys.maxChars]; } public set maxChars(value: number) { this.$setMaxChars(value); } /** * @private * * @param value */ $setMaxChars(value: number): boolean { if (this.$TextField[sys.TextKeys.maxChars] != value) { this.$TextField[sys.TextKeys.maxChars] = value; if (egret.nativeRender) { this.$nativeDisplayObject.setMaxChars(value); } return true; } return false; } /** * Vertical position of text in a text field. scrollV property helps users locate specific passages in a long article, and create scrolling text fields. * Vertically scrolling units are lines, and horizontal scrolling unit is pixels. * If the first displayed line is the first line in the text field, scrollV is set to 1 (instead of 0). * @language en_US */ /** * 文本在文本字段中的垂直位置。scrollV 属性可帮助用户定位到长篇文章的特定段落,还可用于创建滚动文本字段。 * 垂直滚动的单位是行,而水平滚动的单位是像素。 * 如果显示的第一行是文本字段中的第一行,则 scrollV 设置为 1(而非 0)。 * @language zh_CN */ public set scrollV(value: number) { value = Math.max(value, 1); if (value == this.$TextField[sys.TextKeys.scrollV]) { return; } this.$TextField[sys.TextKeys.scrollV] = value; if (egret.nativeRender) { this.$nativeDisplayObject.setScrollV(value); } this.$invalidateTextField(); } /** * @version Egret 2.4 * @platform Web,Native */ public get scrollV(): number { return Math.min(Math.max(this.$TextField[sys.TextKeys.scrollV], 1), this.maxScrollV); } /** * The maximum value of scrollV * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * scrollV 的最大值 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get maxScrollV(): number { this.$getLinesArr(); return Math.max(this.$TextField[sys.TextKeys.numLines] - TextFieldUtils.$getScrollNum(this) + 1, 1); } /** * @private * @version Egret 2.4 * @platform Web,Native */ public get selectionBeginIndex(): number { return 0; } /** * @private * @version Egret 2.4 * @platform Web,Native */ public get selectionEndIndex(): number { return 0; } /** * @private * @version Egret 2.4 * @platform Web,Native */ public get caretIndex(): number { return 0; } /** * @private * * @param beginIndex * @param endIndex */ $setSelection(beginIndex: number, endIndex: number): boolean { return false; } /** * @private * * @returns */ $getLineHeight(): number { return this.$TextField[sys.TextKeys.lineSpacing] + this.$TextField[sys.TextKeys.fontSize]; } /** * Number of lines of text. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 文本行数。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get numLines(): number { this.$getLinesArr(); return this.$TextField[sys.TextKeys.numLines]; } /** * Indicate whether field is a multiline text field. Note that this property is valid only when the type is TextFieldType.INPUT. * If the value is true, the text field is multiline; if the value is false, the text field is a single-line text field. In a field of type TextFieldType.INPUT, the multiline value determines whether the Enter key creates a new line (a value of false, and the Enter key is ignored). * @default false * @language en_US */ /** * 表示字段是否为多行文本字段。注意,此属性仅在type为TextFieldType.INPUT时才有效。 * 如果值为 true,则文本字段为多行文本字段;如果值为 false,则文本字段为单行文本字段。在类型为 TextFieldType.INPUT 的字段中,multiline 值将确定 Enter 键是否创建新行(如果值为 false,则将忽略 Enter 键)。 * @default false * @language zh_CN */ public set multiline(value: boolean) { this.$setMultiline(value); } /** * @private * * @param value */ $setMultiline(value: boolean): boolean { if (this.$TextField[sys.TextKeys.multiline] == value) { return false; } this.$TextField[sys.TextKeys.multiline] = value; this.$invalidateTextField(); if (egret.nativeRender) { this.$nativeDisplayObject.setMultiline(value); } return true; } public get multiline(): boolean { return this.$TextField[sys.TextKeys.multiline]; } /** * Indicates a user can enter into the text field character set. If you restrict property is null, you can enter any character. If you restrict property is an empty string, you can not enter any character. If you restrict property is a string of characters, you can enter only characters in the string in the text field. The string is scanned from left to right. You can use a hyphen (-) to specify a range. Only restricts user interaction; a script may put any text into the text field. <br/> * If the string of characters caret (^) at the beginning, all characters are initially accepted, then the string are excluded from receiving ^ character. If the string does not begin with a caret (^) to, any characters are initially accepted and then a string of characters included in the set of accepted characters. <br/> * The following example allows only uppercase characters, spaces, and numbers in the text field: <br/> * My_txt.restrict = "A-Z 0-9"; <br/> * The following example includes all characters except lowercase letters: <br/> * My_txt.restrict = "^ a-z"; <br/> * If you need to enter characters \ ^, use two backslash "\\ -" "\\ ^": <br/> * Can be used anywhere in the string ^ to rule out including characters and switch between characters, but can only be used to exclude a ^. The following code includes only uppercase letters except uppercase Q: <br/> * My_txt.restrict = "A-Z ^ Q"; <br/> * @version Egret 2.4 * @platform Web,Native * @default null * @language en_US */ /** * 表示用户可输入到文本字段中的字符集。如果 restrict 属性的值为 null,则可以输入任何字符。如果 restrict 属性的值为空字符串,则不能输入任何字符。如果 restrict 属性的值为一串字符,则只能在文本字段中输入该字符串中的字符。从左向右扫描该字符串。可以使用连字符 (-) 指定一个范围。只限制用户交互;脚本可将任何文本放入文本字段中。<br/> * 如果字符串以尖号 (^) 开头,则先接受所有字符,然后从接受字符集中排除字符串中 ^ 之后的字符。如果字符串不以尖号 (^) 开头,则最初不接受任何字符,然后将字符串中的字符包括在接受字符集中。<br/> * 下例仅允许在文本字段中输入大写字符、空格和数字:<br/> * my_txt.restrict = "A-Z 0-9";<br/> * 下例包含除小写字母之外的所有字符:<br/> * my_txt.restrict = "^a-z";<br/> * 如果需要输入字符 \ ^,请使用2个反斜杠 "\\-" "\\^" :<br/> * 可在字符串中的任何位置使用 ^,以在包含字符与排除字符之间进行切换,但是最多只能有一个 ^ 用来排除。下面的代码只包含除大写字母 Q 之外的大写字母:<br/> * my_txt.restrict = "A-Z^Q";<br/> * @version Egret 2.4 * @platform Web,Native * @default null * @language zh_CN */ public set restrict(value: string) { let values = this.$TextField; if (value == null) { values[sys.TextKeys.restrictAnd] = null; values[sys.TextKeys.restrictNot] = null; } else { let index = -1; while (index < value.length) { index = value.indexOf("^", index); if (index == 0) { break; } else if (index > 0) { if (value.charAt(index - 1) != "\\") { break; } index++; } else { break; } } if (index == 0) { values[sys.TextKeys.restrictAnd] = null; values[sys.TextKeys.restrictNot] = value.substring(index + 1); } else if (index > 0) { values[sys.TextKeys.restrictAnd] = value.substring(0, index); values[sys.TextKeys.restrictNot] = value.substring(index + 1); } else { values[sys.TextKeys.restrictAnd] = value; values[sys.TextKeys.restrictNot] = null; } } } public get restrict(): string { let values = this.$TextField; let str: string = null; if (values[sys.TextKeys.restrictAnd] != null) { str = values[sys.TextKeys.restrictAnd]; } if (values[sys.TextKeys.restrictNot] != null) { if (str == null) { str = ""; } str += "^" + values[sys.TextKeys.restrictNot]; } return str; } /** * @private * * @param value */ $setWidth(value: number): boolean { if (egret.nativeRender) { this.$nativeDisplayObject.setTextFieldWidth(value); } let values = this.$TextField; if (isNaN(value)) { if (isNaN(values[sys.TextKeys.textFieldWidth])) { return false; } values[sys.TextKeys.textFieldWidth] = NaN; } else { if (values[sys.TextKeys.textFieldWidth] == value) { return false; } values[sys.TextKeys.textFieldWidth] = value; } value = +value; if (value < 0) { return false; } this.$invalidateTextField(); return true; } /** * @private * * @param value */ $setHeight(value: number): boolean { if (egret.nativeRender) { this.$nativeDisplayObject.setTextFieldHeight(value); } let values = this.$TextField; if (isNaN(value)) { if (isNaN(values[sys.TextKeys.textFieldHeight])) { return false; } values[sys.TextKeys.textFieldHeight] = NaN; } else { if (values[sys.TextKeys.textFieldHeight] == value) { return false; } values[sys.TextKeys.textFieldHeight] = value; } value = +value; if (value < 0) { return false; } this.$invalidateTextField(); return true; } /** * @private * 获取显示宽度 */ $getWidth(): number { let values = this.$TextField; return isNaN(values[sys.TextKeys.textFieldWidth]) ? this.$getContentBounds().width : values[sys.TextKeys.textFieldWidth]; } /** * @private * 获取显示宽度 */ $getHeight(): number { let values = this.$TextField; return isNaN(values[sys.TextKeys.textFieldHeight]) ? this.$getContentBounds().height : values[sys.TextKeys.textFieldHeight]; } /** * @private */ private textNode: sys.TextNode; /** * @private */ public $graphicsNode: sys.GraphicsNode = null; /** * Specifies whether the text field has a border. * If true, the text field has a border. If false, the text field has no border. * Use borderColor property to set the border color. * @default false * @language en_US */ /** * 指定文本字段是否具有边框。 * 如果为 true,则文本字段具有边框。如果为 false,则文本字段没有边框。 * 使用 borderColor 属性来设置边框颜色。 * @default false * @language zh_CN */ public set border(value: boolean) { this.$setBorder(value); } /** * @private */ $setBorder(value: boolean): void { value = !!value; if (this.$TextField[sys.TextKeys.border] == value) { return; } this.$TextField[sys.TextKeys.border] = value; this.$invalidateTextField(); if (egret.nativeRender) { this.$nativeDisplayObject.setBorder(value); } } /** * @version Egret 2.4 * @platform Web,Native */ public get border(): boolean { return this.$TextField[sys.TextKeys.border]; } /** * The color of the text field border. * Even currently is no border can be retrieved or set this property, but only if the text field has the border property is set to true, the color is visible. * @default 0x000000 * @language en_US */ /** * 文本字段边框的颜色。 * 即使当前没有边框,也可检索或设置此属性,但只有当文本字段已将 border 属性设置为 true 时,才可以看到颜色。 * @default 0x000000 * @language zh_CN */ public set borderColor(value: number) { this.$setBorderColor(value); } /** * @private */ $setBorderColor(value: number): void { value = +value || 0; if (this.$TextField[sys.TextKeys.borderColor] == value) { return; } this.$TextField[sys.TextKeys.borderColor] = value; this.$invalidateTextField(); if (egret.nativeRender) { this.$nativeDisplayObject.setBorderColor(value); } } /** * @version Egret 2.4 * @platform Web,Native */ public get borderColor(): number { return this.$TextField[sys.TextKeys.borderColor]; } /** * Specifies whether the text field has a background fill. * If true, the text field has a background fill. If false, the text field has no background fill. * Use the backgroundColor property to set the background color of the text field. * @default false * @language en_US */ /** * 指定文本字段是否具有背景填充。 * 如果为 true,则文本字段具有背景填充。如果为 false,则文本字段没有背景填充。 * 使用 backgroundColor 属性来设置文本字段的背景颜色。 * @default false * @language zh_CN */ public set background(value: boolean) { this.$setBackground(value); } /** * @private */ $setBackground(value: boolean): void { if (this.$TextField[sys.TextKeys.background] == value) { return; } this.$TextField[sys.TextKeys.background] = value; this.$invalidateTextField(); if (egret.nativeRender) { this.$nativeDisplayObject.setBackground(value); } } /** * @version Egret 2.4 * @platform Web,Native */ public get background(): boolean { return this.$TextField[sys.TextKeys.background]; } /** * Color of the text field background. * Even currently is no background, can be retrieved or set this property, but only if the text field has the background property set to true, the color is visible. * @default 0xFFFFFF * @language en_US */ /** * 文本字段背景的颜色。 * 即使当前没有背景,也可检索或设置此属性,但只有当文本字段已将 background 属性设置为 true 时,才可以看到颜色。 * @default 0xFFFFFF * @language zh_CN */ public set backgroundColor(value: number) { this.$setBackgroundColor(value); } /** * @private */ $setBackgroundColor(value: number): void { if (this.$TextField[sys.TextKeys.backgroundColor] == value) { return; } this.$TextField[sys.TextKeys.backgroundColor] = value; this.$invalidateTextField(); if (egret.nativeRender) { this.$nativeDisplayObject.setBackgroundColor(value); } } /** * @version Egret 2.4 * @platform Web,Native */ public get backgroundColor(): number { return this.$TextField[sys.TextKeys.backgroundColor]; } /** * @private * */ private fillBackground(lines?: number[]): void { let graphics = this.$graphicsNode; if (graphics) { graphics.clear(); } let values = this.$TextField; if (values[sys.TextKeys.background] || values[sys.TextKeys.border] || (lines && lines.length > 0)) { if (!graphics) { graphics = this.$graphicsNode = new sys.GraphicsNode(); if (!egret.nativeRender) { let groupNode = new sys.GroupNode(); groupNode.addNode(graphics); groupNode.addNode(this.textNode); this.$renderNode = groupNode; } else { this.$renderNode = this.textNode; } } let fillPath: sys.Path2D; let strokePath: sys.Path2D; //渲染背景 if (values[sys.TextKeys.background]) { fillPath = graphics.beginFill(values[sys.TextKeys.backgroundColor]); fillPath.drawRect(0, 0, this.$getWidth(), this.$getHeight()); } //渲染边框 if (values[sys.TextKeys.border]) { strokePath = graphics.lineStyle(1, values[sys.TextKeys.borderColor]); //1像素和3像素线条宽度的情况,会向右下角偏移0.5像素绘制。少画一像素宽度,正好能不超出文本测量边界。 strokePath.drawRect(0, 0, this.$getWidth() - 1, this.$getHeight() - 1); } //渲染下划线 if (lines && lines.length > 0) { let textColor = values[sys.TextKeys.textColor]; let lastColor = -1; let length = lines.length; for (let i = 0; i < length; i += 4) { let x: number = lines[i]; let y: number = lines[i + 1]; let w: number = lines[i + 2]; let color: number = typeof lines[i + 3] == "number" ? lines[i + 3] : textColor; if (lastColor < 0 || lastColor != color) { lastColor = color; strokePath = graphics.lineStyle(2, color, 1, CapsStyle.NONE); } strokePath.moveTo(x, y); strokePath.lineTo(x + w, y); } } } if (graphics) { let bounds = this.$getRenderBounds(); graphics.x = bounds.x; graphics.y = bounds.y; graphics.width = bounds.width; graphics.height = bounds.height; Rectangle.release(bounds); } } /** * Enter the text automatically entered into the input state, the input type is text only and may only be invoked in the user interaction. * @version Egret 3.0.8 * @platform Web,Native * @language en_US */ /** * 输入文本自动进入到输入状态,仅在类型是输入文本并且是在用户交互下才可以调用。 * @version Egret 3.0.8 * @platform Web,Native * @language zh_CN */ public setFocus(): void { if (this.type == egret.TextFieldType.INPUT && this.$stage) { this.inputUtils.$onFocus(true); } } /** * @private * */ public $onRemoveFromStage(): void { super.$onRemoveFromStage(); this.removeEvent(); if (this.$TextField[sys.TextKeys.type] == TextFieldType.INPUT) { this.inputUtils._removeStageText(); } if (this.textNode) { this.textNode.clean(); if (egret.nativeRender) { egret_native.NativeDisplayObject.disposeTextData(this); } } } /** * @private * * @param stage * @param nestLevel */ public $onAddToStage(stage: Stage, nestLevel: number): void { super.$onAddToStage(stage, nestLevel); this.addEvent(); if (this.$TextField[sys.TextKeys.type] == TextFieldType.INPUT) { this.inputUtils._addStageText(); } } $invalidateTextField(): void { let self = this; self.$renderDirty = true; self.$TextField[sys.TextKeys.textLinesChanged] = true; self.$TextField[sys.TextKeys.textLinesChangedForNativeRender] = true; if (egret.nativeRender) { // egret_native.dirtyTextField(this); } else { let p = self.$parent; if (p && !p.$cacheDirty) { p.$cacheDirty = true; p.$cacheDirtyUp(); } let maskedObject = self.$maskedObject; if (maskedObject && !maskedObject.$cacheDirty) { maskedObject.$cacheDirty = true; maskedObject.$cacheDirtyUp(); } } } $getRenderBounds(): Rectangle { let bounds = this.$getContentBounds(); let tmpBounds = Rectangle.create(); tmpBounds.copyFrom(bounds); if (this.$TextField[sys.TextKeys.border]) { tmpBounds.width += 2; tmpBounds.height += 2; } let _strokeDouble = this.$TextField[sys.TextKeys.stroke] * 2; if (_strokeDouble > 0) { tmpBounds.width += _strokeDouble * 2; tmpBounds.height += _strokeDouble * 2; } tmpBounds.x -= _strokeDouble + 2;//+2和+4 是为了webgl纹理太小导致裁切问题 tmpBounds.y -= _strokeDouble + 2; tmpBounds.width = Math.ceil(tmpBounds.width) + 4; tmpBounds.height = Math.ceil(tmpBounds.height) + 4; return tmpBounds; } /** * @private */ $measureContentBounds(bounds: Rectangle): void { this.$getLinesArr(); let w: number = 0; let h: number = 0; if (nativeRender) { w = egret_native.nrGetTextFieldWidth(this.$nativeDisplayObject.id); h = egret_native.nrGetTextFieldHeight(this.$nativeDisplayObject.id); } else { w = !isNaN(this.$TextField[sys.TextKeys.textFieldWidth]) ? this.$TextField[sys.TextKeys.textFieldWidth] : this.$TextField[sys.TextKeys.textWidth]; h = !isNaN(this.$TextField[sys.TextKeys.textFieldHeight]) ? this.$TextField[sys.TextKeys.textFieldHeight] : TextFieldUtils.$getTextHeight(this); } bounds.setTo(0, 0, w, h); } $updateRenderNode(): void { if (this.$TextField[sys.TextKeys.type] == TextFieldType.INPUT) { this.inputUtils._updateProperties(); if (this.$isTyping) { this.fillBackground(); return; } } else if (this.$TextField[sys.TextKeys.textFieldWidth] == 0) { let graphics = this.$graphicsNode; if (graphics) { graphics.clear(); } return; } let underLines = this.drawText(); this.fillBackground(underLines); //tudo 宽高很小的情况下webgl模式绘制异常 let bounds = this.$getRenderBounds(); let node = this.textNode; node.x = bounds.x; node.y = bounds.y; node.width = Math.ceil(bounds.width); node.height = Math.ceil(bounds.height); Rectangle.release(bounds); } /** * @private */ private isFlow: boolean = false; /** * Set rich text * @language en_US */ /** * 设置富文本 * @see http://edn.egret.com/cn/index.php/article/index/id/146 * @language zh_CN */ public set textFlow(textArr: Array<egret.ITextElement>) { this.isFlow = true; let text: string = ""; if (textArr == null) textArr = []; for (let i: number = 0; i < textArr.length; i++) { let element: egret.ITextElement = textArr[i]; text += element.text; } if (this.$TextField[sys.TextKeys.displayAsPassword]) { this.$setBaseText(text); } else { this.$TextField[sys.TextKeys.text] = text; this.setMiddleStyle(textArr); if (egret.nativeRender) { this.$nativeDisplayObject.setTextFlow(textArr); } } } /** * @version Egret 2.4 * @platform Web,Native */ public get textFlow(): Array<egret.ITextElement> { return this.textArr; } /** * @private * * @param text * @returns */ private changeToPassText(text: string): string { if (this.$TextField[sys.TextKeys.displayAsPassword]) { let passText: string = ""; for (let i: number = 0, num = text.length; i < num; i++) { switch (text.charAt(i)) { case '\n': passText += "\n"; break; case '\r': break; default: passText += '*'; } } return passText; } return text; } /** * @private */ private textArr: Array<egret.ITextElement> = []; /** * @private * * @param textArr */ private setMiddleStyle(textArr: Array<egret.ITextElement>): void { this.$TextField[sys.TextKeys.textLinesChanged] = true; this.$TextField[sys.TextKeys.textLinesChangedForNativeRender] = true; this.textArr = textArr; this.$invalidateTextField(); } /** * Get the text measured width * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 获取文本测量宽度 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get textWidth(): number { this.$getLinesArr(); if (nativeRender) { return egret_native.nrGetTextWidth(this.$nativeDisplayObject.id); } return this.$TextField[sys.TextKeys.textWidth]; } /** * Get Text measuring height * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 获取文本测量高度 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get textHeight(): number { this.$getLinesArr(); if (nativeRender) { return egret_native.nrGetTextHeight(this.$nativeDisplayObject.id); } return TextFieldUtils.$getTextHeight(this); } /** * @private * @param text * @version Egret 2.4 * @platform Web,Native */ public appendText(text: string): void { this.appendElement(<egret.ITextElement>{ text: text }); } /** * @private * @param element * @version Egret 2.4 * @platform Web,Native */ public appendElement(element: egret.ITextElement): void { const text: string = this.$TextField[sys.TextKeys.text] + element.text; if (egret.nativeRender) { this.textArr.push(element); this.$TextField[sys.TextKeys.text] = text; this.$TextField[sys.TextKeys.textLinesChanged] = true; this.$TextField[sys.TextKeys.textLinesChangedForNativeRender] = true; this.$nativeDisplayObject.setTextFlow(this.textArr); return; } if (this.$TextField[sys.TextKeys.displayAsPassword]) { this.$setBaseText(text); } else { this.$TextField[sys.TextKeys.text] = text; this.textArr.push(element); this.setMiddleStyle(this.textArr); } } /** * @private */ private linesArr: Array<egret.ILineElement> = []; $getLinesArr(): Array<egret.ILineElement> { let values = this.$TextField; if (nativeRender && values[sys.TextKeys.textLinesChangedForNativeRender]) { egret_native.updateNativeRender(); values[sys.TextKeys.textLinesChangedForNativeRender] = false; return; } else { return this.$getLinesArr2(); } } /** * @private * * @returns */ $getLinesArr2(): Array<egret.ILineElement> { let values = this.$TextField; if (!values[sys.TextKeys.textLinesChanged]) { return this.linesArr; } values[sys.TextKeys.textLinesChanged] = false; let text2Arr: Array<egret.ITextElement> = this.textArr; this.linesArr.length = 0; values[sys.TextKeys.textHeight] = 0; values[sys.TextKeys.textWidth] = 0; let textFieldWidth: number = values[sys.TextKeys.textFieldWidth]; //宽度被设置为0 if (!isNaN(textFieldWidth) && textFieldWidth == 0) { values[sys.TextKeys.numLines] = 0; return [{ width: 0, height: 0, charNum: 0, elements: [], hasNextLine: false }]; } let linesArr: Array<egret.ILineElement> = this.linesArr; let lineW: number = 0; let lineCharNum: number = 0; let lineH: number = 0; let lineCount: number = 0; let lineElement: egret.ILineElement; for (let i: number = 0, text2ArrLength: number = text2Arr.length; i < text2ArrLength; i++) { let element: egret.ITextElement = text2Arr[i]; //可能设置为没有文本,忽略绘制 if (!element.text) { if (lineElement) { lineElement.width = lineW; lineElement.height = lineH; lineElement.charNum = lineCharNum; values[sys.TextKeys.textWidth] = Math.max(values[sys.TextKeys.textWidth], lineW); values[sys.TextKeys.textHeight] += lineH; } continue; } element.style = element.style || <egret.ITextStyle>{}; let text: string = element.text.toString(); let textArr: string[] = text.split(/(?:\r\n|\r|\n)/); for (let j: number = 0, textArrLength: number = textArr.length; j < textArrLength; j++) { if (linesArr[lineCount] == null) { lineElement = { width: 0, height: 0, elements: [], charNum: 0, hasNextLine: false }; linesArr[lineCount] = lineElement; lineW = 0; lineH = 0; lineCharNum = 0; } if (values[sys.TextKeys.type] == egret.TextFieldType.INPUT) { lineH = values[sys.TextKeys.fontSize]; } else { lineH = Math.max(lineH, typeof (element.style.size) == "number" ? element.style.size : values[sys.TextKeys.fontSize]); } let isNextLine: boolean = true; if (textArr[j] == "") { if (j == textArrLength - 1) { isNextLine = false; } } else { let w: number = measureTextWidth(textArr[j], values, element.style); if (isNaN(textFieldWidth)) {//没有设置过宽 lineW += w; lineCharNum += textArr[j].length; lineElement.elements.push(<egret.IWTextElement>{ width: w, text: textArr[j], style: element.style }); if (j == textArrLength - 1) { isNextLine = false; } } else { if (lineW + w <= textFieldWidth) {//在设置范围内 lineElement.elements.push(<egret.IWTextElement>{ width: w, text: textArr[j], style: element.style }); lineW += w; lineCharNum += textArr[j].length; if (j == textArrLength - 1) { isNextLine = false; } } else { let k: number = 0; let ww: number = 0; let word: string = textArr[j]; let words: string[]; if (values[sys.TextKeys.wordWrap]) { words = word.split(SplitRegex); } else { words = word.match(/./g); } let wl: number = words.length; let charNum = 0; for (; k < wl; k++) { // detect 4 bytes unicode, refer https://mths.be/punycode var codeLen = words[k].length; var has4BytesUnicode = false; if (codeLen == 1 && k < wl - 1) // when there is 2 bytes high surrogate { var charCodeHigh = words[k].charCodeAt(0); var charCodeLow = words[k + 1].charCodeAt(0); if (charCodeHigh >= 0xD800 && charCodeHigh <= 0xDBFF && (charCodeLow & 0xFC00) == 0xDC00) { // low var realWord = words[k] + words[k + 1]; codeLen = 2; has4BytesUnicode = true; w = measureTextWidth(realWord, values, element.style); } else { w = measureTextWidth(words[k], values, element.style); } } else { w = measureTextWidth(words[k], values, element.style); } // w = measureTextWidth(words[k], values, element.style); if (lineW != 0 && lineW + w > textFieldWidth && lineW + k != 0) { break; } if (ww + w > textFieldWidth) {//纯英文,一个词就超出宽度的情况 var words2: Array<string> = words[k].match(/./g); for (var k2 = 0, wl2 = words2.length; k2 < wl2; k2++) { // detect 4 bytes unicode, refer https://mths.be/punycode var codeLen = words2[k2].length; var has4BytesUnicode2 = false; if (codeLen == 1 && k2 < wl2 - 1) // when there is 2 bytes high surrogate { var charCodeHigh = words2[k2].charCodeAt(0); var charCodeLow = words2[k2 + 1].charCodeAt(0); if (charCodeHigh >= 0xD800 && charCodeHigh <= 0xDBFF && (charCodeLow & 0xFC00) == 0xDC00) { // low var realWord = words2[k2] + words2[k2 + 1]; codeLen = 2; has4BytesUnicode2 = true; w = measureTextWidth(realWord, values, element.style); } else { w = measureTextWidth(words2[k2], values, element.style); } } else { w = measureTextWidth(words2[k2], values, element.style); } // w = measureTextWidth(words2[k2], values, element.style); if (k2 > 0 && lineW + w > textFieldWidth) { break; } // charNum += words2[k2].length; charNum += codeLen; ww += w; lineW += w; lineCharNum += charNum; if (has4BytesUnicode2) { k2++; } } } else { // charNum += words[k].length; charNum += codeLen; ww += w; lineW += w; lineCharNum += charNum; } if (has4BytesUnicode) { k++; } } if (k > 0) { lineElement.elements.push(<egret.IWTextElement>{ width: ww, text: word.substring(0, charNum), style: element.style }); let leftWord: string = word.substring(charNum); let m: number; let lwleng = leftWord.length; for (m = 0; m < lwleng; m++) { if (leftWord.charAt(m) != " ") { break; } } textArr[j] = leftWord.substring(m); } if (textArr[j] != "") { j--; isNextLine = false; } } } } if (isNextLine) { lineCharNum++; lineElement.hasNextLine = true; } if (j < textArr.length - 1) {//非最后一个 lineElement.width = lineW; lineElement.height = lineH; lineElement.charNum = lineCharNum; values[sys.TextKeys.textWidth] = Math.max(values[sys.TextKeys.textWidth], lineW); values[sys.TextKeys.textHeight] += lineH; //if (this._type == TextFieldType.INPUT && !this._multiline) { // this._numLines = linesArr.length; // return linesArr; //} lineCount++; } } if (i == text2Arr.length - 1 && lineElement) { lineElement.width = lineW; lineElement.height = lineH; lineElement.charNum = lineCharNum; values[sys.TextKeys.textWidth] = Math.max(values[sys.TextKeys.textWidth], lineW); values[sys.TextKeys.textHeight] += lineH; } } values[sys.TextKeys.numLines] = linesArr.length; return linesArr; } /** * @private */ $isTyping: boolean = false; /** * @private */ public $setIsTyping(value: boolean): void { this.$isTyping = value; this.$invalidateTextField(); if (nativeRender) { this.$nativeDisplayObject.setIsTyping(value); } } /** * @private * 返回要绘制的下划线列表 */ private drawText(): number[] { let node = this.textNode; let values = this.$TextField; //更新文本样式 node.bold = values[sys.TextKeys.bold]; node.fontFamily = values[sys.TextKeys.fontFamily] || TextField.default_fontFamily; node.italic = values[sys.TextKeys.italic]; node.size = values[sys.TextKeys.fontSize]; node.stroke = values[sys.TextKeys.stroke]; node.strokeColor = values[sys.TextKeys.strokeColor]; node.textColor = values[sys.TextKeys.textColor]; //先算出需要的数值 let lines: Array<egret.ILineElement> = this.$getLinesArr(); if (values[sys.TextKeys.textWidth] == 0) { return []; } let maxWidth: number = !isNaN(values[sys.TextKeys.textFieldWidth]) ? values[sys.TextKeys.textFieldWidth] : values[sys.TextKeys.textWidth]; let textHeight: number = TextFieldUtils.$getTextHeight(this); let drawY: number = 0; let startLine: number = TextFieldUtils.$getStartLine(this); let textFieldHeight: number = values[sys.TextKeys.textFieldHeight]; if (!isNaN(textFieldHeight) && textFieldHeight > textHeight) { let vAlign: number = TextFieldUtils.$getValign(this); drawY += vAlign * (textFieldHeight - textHeight); } drawY = Math.round(drawY); let hAlign: number = TextFieldUtils.$getHalign(this); let drawX: number = 0; let underLineData: number[] = []; for (let i: number = startLine, numLinesLength: number = values[sys.TextKeys.numLines]; i < numLinesLength; i++) { let line: egret.ILineElement = lines[i]; let h: number = line.height; drawY += h / 2; if (i != startLine) { if (values[sys.TextKeys.type] == egret.TextFieldType.INPUT && !values[sys.TextKeys.multiline]) { break; } if (!isNaN(textFieldHeight) && drawY > textFieldHeight) { break; } } drawX = Math.round((maxWidth - line.width) * hAlign); for (let j: number = 0, elementsLength: number = line.elements.length; j < elementsLength; j++) { let element: egret.IWTextElement = line.elements[j]; let size: number = typeof element.style.size == "number" ? element.style.size : values[sys.TextKeys.fontSize]; node.drawText(drawX, drawY + (h - size) / 2, element.text, element.style); if (element.style.underline) { underLineData.push( drawX, drawY + (h) / 2, element.width, element.style.textColor ); } drawX += element.width; } drawY += h / 2 + values[sys.TextKeys.lineSpacing]; } return underLineData; } //增加点击事件 private addEvent(): void { this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTapHandler, this); } //释放点击事件 private removeEvent(): void { this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTapHandler, this); } //处理富文本中有href的 private onTapHandler(e: egret.TouchEvent): void { if (this.$TextField[sys.TextKeys.type] == egret.TextFieldType.INPUT) { return; } let ele: ITextElement = TextFieldUtils.$getTextElement(this, e.localX, e.localY); if (ele == null) { return; } let style: egret.ITextStyle = ele.style; if (style && style.href) { if (style.href.match(/^event:/)) { let type: string = style.href.match(/^event:/)[0]; egret.TextEvent.dispatchTextEvent(this, egret.TextEvent.LINK, style.href.substring(type.length)); } else { open(style.href, style.target || "_blank"); } } } } export interface TextField { addEventListener<Z>(type: "link" , listener: (this: Z, e: TextEvent) => void, thisObject: Z, useCapture?: boolean, priority?: number); addEventListener<Z>(type: "focusIn" | "focusOut" , listener: (this: Z, e: FocusEvent) => void, thisObject: Z, useCapture?: boolean, priority?: number); addEventListener(type: string, listener: Function, thisObject: any, useCapture?: boolean, priority?: number); } }
the_stack
import { Directive, ElementRef, Input, OnChanges, OnDestroy, OnInit, SimpleChange } from '@angular/core'; import { CoreCancellablePromise } from '@classes/cancellable-promise'; import { CorePromisedValue } from '@classes/promised-value'; import { CoreLoadingComponent } from '@components/loading/loading'; import { CoreTabsOutletComponent } from '@components/tabs-outlet/tabs-outlet'; import { CoreTabsComponent } from '@components/tabs/tabs'; import { CoreSettingsHelper } from '@features/settings/services/settings-helper'; import { ScrollDetail } from '@ionic/core'; import { CoreUtils } from '@services/utils/utils'; import { CoreComponentsRegistry } from '@singletons/components-registry'; import { CoreDom } from '@singletons/dom'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { CoreMath } from '@singletons/math'; import { Subscription } from 'rxjs'; import { CoreFormatTextDirective } from './format-text'; declare module '@singletons/events' { /** * Augment CoreEventsData interface with events specific to this service. * * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { [COLLAPSIBLE_HEADER_UPDATED]: { collapsed: boolean }; } } export const COLLAPSIBLE_HEADER_UPDATED = 'collapsible_header_updated'; /** * Directive to make <ion-header> collapsible. * * This directive expects h1 titles to be duplicated in a header and an item inside the page, and it will transition * from one state to another listening to the scroll in the page content. The item to be used as the expanded form * should also have the [collapsed] attribute. * * Example usage: * * <ion-header collapsible> * <ion-toolbar> * <ion-title> * <h1>Title</h1> * </ion-title> * </ion-toolbar> * </ion-header> * * <ion-content> * <ion-item collapsible> * <ion-label> * <h1>Title</h1> * </ion-label> * </ion-item> * ... * </ion-content> */ @Directive({ selector: 'ion-header[collapsible]', }) export class CoreCollapsibleHeaderDirective implements OnInit, OnChanges, OnDestroy { @Input() collapsible = true; protected page?: HTMLElement; protected collapsedHeader: HTMLIonHeaderElement; protected collapsedFontStyles?: Partial<CSSStyleDeclaration>; protected expandedHeader?: HTMLIonItemElement; protected expandedHeaderHeight?: number; protected expandedFontStyles?: Partial<CSSStyleDeclaration>; protected content?: HTMLIonContentElement; protected contentScrollListener?: EventListener; protected endContentScrollListener?: EventListener; protected pageDidEnterListener?: EventListener; protected resizeListener?: CoreEventObserver; protected floatingTitle?: HTMLHeadingElement; protected scrollingHeight?: number; protected subscriptions: Subscription[] = []; protected enabled = true; protected isWithinContent = false; protected enteredPromise = new CorePromisedValue<void>(); protected mutationObserver?: MutationObserver; protected loadingFloatingTitle = false; protected visiblePromise?: CoreCancellablePromise<void>; constructor(el: ElementRef) { this.collapsedHeader = el.nativeElement; } /** * @inheritdoc */ ngOnInit(): void { this.collapsible = !CoreUtils.isFalseOrZero(this.collapsible); this.init(); } /** * Init function. */ async init(): Promise<void> { if (!this.collapsible || this.expandedHeader) { return; } this.initializePage(); await Promise.all([ this.initializeCollapsedHeader(), this.initializeExpandedHeader(), await this.enteredPromise, ]); await this.initializeFloatingTitle(); this.initializeContent(); } /** * @inheritdoc */ async ngOnChanges(changes: {[name: string]: SimpleChange}): Promise<void> { if (changes.collapsible && !changes.collapsible.firstChange) { this.collapsible = !CoreUtils.isFalseOrZero(changes.collapsible.currentValue); this.enabled = this.collapsible; await this.init(); setTimeout(() => { this.setEnabled(this.enabled); }, 200); } } /** * @inheritdoc */ ngOnDestroy(): void { this.subscriptions.forEach(subscription => subscription.unsubscribe()); if (this.content && this.contentScrollListener) { this.content.removeEventListener('ionScroll', this.contentScrollListener); } if (this.content && this.endContentScrollListener) { this.content.removeEventListener('ionScrollEnd', this.endContentScrollListener); } if (this.page && this.pageDidEnterListener) { this.page.removeEventListener('ionViewDidEnter', this.pageDidEnterListener); } this.resizeListener?.off(); this.mutationObserver?.disconnect(); this.visiblePromise?.cancel(); } /** * Update collapsed status of the header. * * @param collapsed Whether header is collapsed or not. */ protected setCollapsed(collapsed: boolean): void { if (!this.page) { return; } const isCollapsed = this.page.classList.contains('collapsible-header-page-is-collapsed'); if (isCollapsed === collapsed) { return; } this.page.classList.toggle('collapsible-header-page-is-collapsed', collapsed); CoreEvents.trigger(COLLAPSIBLE_HEADER_UPDATED, { collapsed }); } /** * Listen to changing events. */ protected listenEvents(): void { this.resizeListener = CoreDom.onWindowResize(() => { this.initializeFloatingTitle(); }, 50); this.subscriptions.push(CoreSettingsHelper.onDarkModeChange().subscribe(() => { this.initializeFloatingTitle(); })); this.mutationObserver = new MutationObserver(() => { if (!this.expandedHeader) { return; } const originalTitle = this.expandedHeader.querySelector('h1.collapsible-header-original-title') || this.expandedHeader.querySelector('h1') as HTMLHeadingElement; const floatingTitleWrapper = originalTitle.parentElement as HTMLElement; const floatingTitle = floatingTitleWrapper.querySelector('.collapsible-header-floating-title') as HTMLHeadingElement; if (!floatingTitle || !originalTitle) { return; } // Original title changed, change the contents. const newFloatingTitle = originalTitle.cloneNode(true) as HTMLHeadingElement; newFloatingTitle.classList.add('collapsible-header-floating-title'); newFloatingTitle.classList.remove('collapsible-header-original-title'); floatingTitleWrapper.replaceChild(newFloatingTitle, floatingTitle); this.initializeFloatingTitle(); }); } /** * Search the page element, initialize it, and wait until it's ready for the transition to trigger on scroll. */ protected initializePage(): void { if (!this.collapsedHeader.parentElement) { throw new Error('[collapsible-header] Couldn\'t get page'); } // Find element and prepare classes. this.page = this.collapsedHeader.parentElement; this.page.classList.add('collapsible-header-page'); this.page.addEventListener( 'ionViewDidEnter', this.pageDidEnterListener = () => { clearTimeout(timeout); this.enteredPromise.resolve(); if (this.page && this.pageDidEnterListener) { this.page.removeEventListener('ionViewDidEnter', this.pageDidEnterListener); } }, ); // Timeout in case event is never fired. const timeout = window.setTimeout(() => { this.enteredPromise.reject(new Error('[collapsible-header] Waiting for ionViewDidEnter timeout reached')); }, 5000); } /** * Search the collapsed header element, initialize it, and wait until it's ready for the transition to trigger on scroll. */ protected async initializeCollapsedHeader(): Promise<void> { this.collapsedHeader.classList.add('collapsible-header-collapsed'); await this.waitFormatTextsRendered(this.collapsedHeader); } /** * Search the expanded header element, initialize it, and wait until it's ready for the transition to trigger on scroll. */ protected async initializeExpandedHeader(): Promise<void> { await this.waitLoadingsDone(); this.expandedHeader = this.page?.querySelector('ion-item[collapsible]') ?? undefined; if (!this.expandedHeader) { this.enabled = false; this.setEnabled(this.enabled); throw new Error('[collapsible-header] Couldn\'t initialize expanded header'); } this.expandedHeader.classList.add('collapsible-header-expanded'); await this.waitFormatTextsRendered(this.expandedHeader); } /** * Search the page content, initialize it, and wait until it's ready for the transition to trigger on scroll. */ protected async initializeContent(): Promise<void> { if (!this.page) { return; } this.listenEvents(); // Initialize from tabs. const tabs = CoreComponentsRegistry.resolve(this.page.querySelector('core-tabs-outlet'), CoreTabsOutletComponent); if (tabs) { const outlet = tabs.getOutlet(); const onOutletUpdated = () => { const activePage = outlet.nativeEl.querySelector('.ion-page:not(.ion-page-hidden)'); this.updateContent(activePage?.querySelector('ion-content:not(.disable-scroll-y)') as HTMLIonContentElement); }; this.subscriptions.push(outlet.activateEvents.subscribe(onOutletUpdated)); onOutletUpdated(); return; } // Initialize from page content. const content = this.page.querySelector('ion-content:not(.disable-scroll-y)'); if (!content) { throw new Error('[collapsible-header] Couldn\'t get content'); } this.trackContentScroll(content as HTMLIonContentElement); } /** * Initialize a floating title to mimic transitioning the title from one state to the other. */ protected async initializeFloatingTitle(): Promise<void> { if (!this.page || !this.expandedHeader) { return; } if (this.loadingFloatingTitle) { // Already calculating, return. return; } this.loadingFloatingTitle = true; this.visiblePromise = CoreDom.waitToBeVisible(this.expandedHeader); await this.visiblePromise; this.page.classList.remove('collapsible-header-page-is-active'); await CoreUtils.nextTick(); // Add floating title and measure initial position. const collapsedHeaderTitle = this.collapsedHeader.querySelector('h1') as HTMLHeadingElement; const originalTitle = this.expandedHeader.querySelector('h1.collapsible-header-original-title') || this.expandedHeader.querySelector('h1') as HTMLHeadingElement; const floatingTitleWrapper = originalTitle.parentElement as HTMLElement; let floatingTitle = floatingTitleWrapper.querySelector('.collapsible-header-floating-title') as HTMLHeadingElement; if (!floatingTitle) { // First time, create it. floatingTitle = originalTitle.cloneNode(true) as HTMLHeadingElement; floatingTitle.classList.add('collapsible-header-floating-title'); floatingTitleWrapper.classList.add('collapsible-header-floating-title-wrapper'); floatingTitleWrapper.insertBefore(floatingTitle, originalTitle); originalTitle.classList.add('collapsible-header-original-title'); this.mutationObserver?.observe(originalTitle, { childList: true, subtree: true }); } const floatingTitleBoundingBox = floatingTitle.getBoundingClientRect(); // Prepare styles variables. const collapsedHeaderTitleBoundingBox = collapsedHeaderTitle.getBoundingClientRect(); const collapsedTitleStyles = getComputedStyle(collapsedHeaderTitle); const expandedHeaderHeight = this.expandedHeader.clientHeight; const expandedTitleStyles = getComputedStyle(originalTitle); const originalTitleBoundingBox = originalTitle.getBoundingClientRect(); const textProperties = ['overflow', 'white-space', 'text-overflow', 'color']; const [collapsedFontStyles, expandedFontStyles] = Array .from(collapsedTitleStyles) .filter( property => property.startsWith('font-') || property.startsWith('letter-') || textProperties.includes(property), ) .reduce((styles, property) => { styles[0][property] = collapsedTitleStyles.getPropertyValue(property); styles[1][property] = expandedTitleStyles.getPropertyValue(property); return styles; }, [{}, {}]); const cssVariables = { '--collapsible-header-collapsed-height': `${this.collapsedHeader.clientHeight}px`, '--collapsible-header-expanded-y-delta': `-${this.collapsedHeader.clientHeight}px`, '--collapsible-header-expanded-height': `${expandedHeaderHeight}px`, '--collapsible-header-floating-title-top': `${originalTitleBoundingBox.top - floatingTitleBoundingBox.top}px`, '--collapsible-header-floating-title-left': `${originalTitleBoundingBox.left - floatingTitleBoundingBox.left}px`, '--collapsible-header-floating-title-width': `${originalTitle.clientWidth}px`, '--collapsible-header-floating-title-x-delta': `${collapsedHeaderTitleBoundingBox.left - originalTitleBoundingBox.left}px`, '--collapsible-header-floating-title-width-delta': `${collapsedHeaderTitle.clientWidth - originalTitle.clientWidth}px`, }; Object .entries(cssVariables) .forEach(([property, value]) => this.page?.style.setProperty(property, value)); Object .entries(expandedFontStyles) .forEach(([property, value]) => floatingTitle.style.setProperty(property, value as string)); // Activate styles. this.page.classList.add('collapsible-header-page-is-active'); this.floatingTitle = floatingTitle; this.scrollingHeight = originalTitleBoundingBox.top - collapsedHeaderTitleBoundingBox.top; this.collapsedFontStyles = collapsedFontStyles; this.expandedFontStyles = expandedFontStyles; this.expandedHeaderHeight = expandedHeaderHeight; this.loadingFloatingTitle = false; } /** * Wait until all <core-loading> children inside the page. */ protected async waitLoadingsDone(): Promise<void> { if (!this.page) { return; } // Wait loadings to finish. await CoreComponentsRegistry.waitComponentsReady(this.page, 'core-loading', CoreLoadingComponent); // Wait tabs to be ready. await CoreComponentsRegistry.waitComponentsReady(this.page, 'core-tabs', CoreTabsComponent); await CoreComponentsRegistry.waitComponentsReady(this.page, 'core-tabs-outlet', CoreTabsOutletComponent); // Wait loadings to finish, inside tabs (if any). await CoreComponentsRegistry.waitComponentsReady( this.page, 'core-tab core-loading, ion-router-outlet core-loading', CoreLoadingComponent, ); } /** * Wait until all <core-format-text> children inside the element are done rendering. * * @param element Element. * @return Promise resolved when texts are rendered. */ protected async waitFormatTextsRendered(element: Element): Promise<void> { await CoreComponentsRegistry.waitComponentsReady(element, 'core-format-text', CoreFormatTextDirective); } /** * Update content element whos scroll is being tracked. * * @param content Content element. */ protected updateContent(content?: HTMLIonContentElement | null): void { if (content === (this.content ?? null)) { return; } if (this.content) { if (this.contentScrollListener) { this.content.removeEventListener('ionScroll', this.contentScrollListener); delete this.contentScrollListener; } if (this.endContentScrollListener) { this.content.removeEventListener('ionScrollEnd', this.endContentScrollListener); delete this.endContentScrollListener; } delete this.content; } content && this.trackContentScroll(content); } /** * Set collapsed/expanded based on properties. * * @param enable True to enable, false otherwise */ async setEnabled(enable: boolean): Promise<void> { if (!this.page) { return; } if (enable && this.content) { const contentScroll = await this.content.getScrollElement(); // Do nothing, since scroll has already started on the page. if (contentScroll.scrollTop > 0) { return; } } this.setCollapsed(!enable); this.page.style.setProperty('--collapsible-header-progress', enable ? '0' : '1'); } /** * Listen to a content element for scroll events that will control the header state transition. * * @param content Content element. */ protected async trackContentScroll(content: HTMLIonContentElement): Promise<void> { if (content === this.content) { return; } this.content = content; const page = this.page; const scrollingHeight = this.scrollingHeight; const expandedHeader = this.expandedHeader; const expandedHeaderHeight = this.expandedHeaderHeight; const expandedFontStyles = this.expandedFontStyles; const collapsedFontStyles = this.collapsedFontStyles; const floatingTitle = this.floatingTitle; const contentScroll = await this.content.getScrollElement(); if ( !page || !scrollingHeight || !expandedHeader || !expandedHeaderHeight || !expandedFontStyles || !collapsedFontStyles || !floatingTitle ) { page?.classList.remove('collapsible-header-page-is-active'); throw new Error('[collapsible-header] Couldn\'t set up scrolling'); } this.isWithinContent = content.contains(expandedHeader); page.classList.toggle('collapsible-header-page-is-within-content', this.isWithinContent); this.setEnabled(this.enabled); Object .entries(expandedFontStyles) .forEach(([property, value]) => floatingTitle.style.setProperty(property, value as string)); this.content.scrollEvents = true; this.content.addEventListener('ionScroll', this.contentScrollListener = ({ target }: CustomEvent<ScrollDetail>): void => { if (target !== this.content || !this.enabled) { return; } const scrollableHeight = contentScroll.scrollHeight - contentScroll.clientHeight; let frozen = false; if (this.isWithinContent) { frozen = scrollableHeight <= scrollingHeight; } else { const collapsedHeight = expandedHeaderHeight - (expandedHeader.clientHeight ?? 0); frozen = scrollableHeight + collapsedHeight <= 2 * expandedHeaderHeight; } const progress = frozen ? 0 : CoreMath.clamp(contentScroll.scrollTop / scrollingHeight, 0, 1); this.setCollapsed(progress === 1); page.style.setProperty('--collapsible-header-progress', `${progress}`); page.classList.toggle('collapsible-header-page-is-frozen', frozen); Object .entries(progress > .5 ? collapsedFontStyles : expandedFontStyles) .forEach(([property, value]) => floatingTitle.style.setProperty(property, value as string)); }); this.content.addEventListener( 'ionScrollEnd', this.endContentScrollListener = ({ target }: CustomEvent<ScrollDetail>): void => { if (target !== this.content || !this.enabled) { return; } if (page.classList.contains('collapsible-header-page-is-frozen')) { return; } const progress = parseFloat(page.style.getPropertyValue('--collapsible-header-progress')); const scrollTop = contentScroll.scrollTop; const collapse = progress > 0.5; this.setCollapsed(collapse); page.style.setProperty('--collapsible-header-progress', collapse ? '1' : '0'); if (collapse && this.scrollingHeight && this.scrollingHeight > 0 && scrollTop < this.scrollingHeight) { this.content?.scrollToPoint(null, this.scrollingHeight); } if (!collapse && this.scrollingHeight && this.scrollingHeight > 0 && scrollTop > 0) { this.content?.scrollToPoint(null, 0); } }, ); } }
the_stack
import { default as setListItemStyle } from '../../lib/list/setListItemStyle'; interface TestChildElement { elementTag: string; styles: string; textContent?: string; } describe('setListItemStyle', () => { const stylesToInherit = ['font-size', 'font-family', 'color']; it('singleElement with fontSize and Color', () => { runTest( [ { elementTag: 'span', styles: 'font-size:72pt;color:blue', textContent: 'test', }, ], 'font-size:72pt;color:blue' ); }); it('Multiple Elements with same fontSize and Color', () => { runTest( [ { elementTag: 'span', styles: 'font-size:72pt;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;color:blue', textContent: 'test', }, ], 'font-size:72pt;color:blue' ); }); it('Multiple Elements with same fontSize, fontName and Color', () => { runTest( [ { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;color:blue', textContent: 'test', }, ], 'font-size:72pt;font-family:Tahoma;color:blue' ); }); it('Multiple Elements with different Styles 1', () => { runTest( [ { elementTag: 'span', styles: 'font-size:72pt;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;', textContent: 'test', }, ], 'font-size:72pt' ); }); it('Multiple Elements with different Styles 2', () => { runTest( [ { elementTag: 'span', styles: 'font-size:72pt;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;', textContent: 'test', }, ], 'font-size:72pt' ); }); it('Multiple Elements with different Styles 3', () => { runTest( [ { elementTag: 'span', styles: 'font-size:14pt;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;', textContent: 'test', }, ], null ); }); it('Multiple Elements with different Styles 4', () => { runTest( [ { elementTag: 'span', styles: 'font-size:14pt;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;font-family:Arial;', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;', textContent: 'test', }, ], null ); }); it('Multiple Elements with same styles', () => { runTest( [ { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;color:blue', textContent: 'test', }, ], 'font-size:72pt;font-family:Tahoma;color:blue' ); }); it('Multiple Elements with no styles', () => { runTest( [ { elementTag: 'span', styles: '', textContent: 'test', }, { elementTag: 'span', styles: '', textContent: 'test', }, { elementTag: 'span', styles: '', textContent: 'test', }, ], null ); }); it('List Item element, with Block Element and child elements', () => { // Arrange let listItemElement = document.createElement('li'); let divElement = document.createElement('div'); let testChildElements = [ { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;color:blue', textContent: 'test', }, ]; testChildElements.forEach(element => { divElement.appendChild(createElement(element)); }); listItemElement.appendChild(divElement); // Act setListItemStyle(listItemElement, stylesToInherit); // Assert expect(listItemElement.getAttribute('style')).toBe( 'font-size:72pt;font-family:Tahoma;color:blue' ); }); it('List Item element, with Block Element and child elements, #text Node and BR Element', () => { // Arrange let listItemElement = document.createElement('li'); let divElement = document.createElement('div'); let testChildElements = [ { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;color:blue', textContent: 'test', }, { elementTag: 'span', styles: 'font-size:72pt;font-family:Tahoma;color:blue', textContent: 'test', }, ]; testChildElements.forEach(element => { divElement.appendChild(createElement(element)); }); let spanElement = createElement({ elementTag: 'span', styles: 'font-size: 72pt;font-family: Tahoma;color:blue', textContent: 'test', }); spanElement.appendChild(document.createTextNode('test')); listItemElement.appendChild(divElement); listItemElement.appendChild(spanElement); // Act setListItemStyle(listItemElement, stylesToInherit); // Assert expect(listItemElement.getAttribute('style')).toBe( 'font-size:72pt;font-family:Tahoma;color:blue' ); }); it('List Item element, with <ol><li><div><span>aaa</span></div></li><ol>', () => { // Arrange; let listItemElement = document.createElement('li'); let divElement = document.createElement('div'); let spanElement = createElement({ elementTag: 'span', styles: 'font-size: 72pt;font-family: Tahoma;color:blue', textContent: 'test', }); divElement.appendChild(spanElement); listItemElement.appendChild(divElement); listItemElement.appendChild(spanElement); // Act; setListItemStyle(listItemElement, stylesToInherit); // Assert; expect(listItemElement.getAttribute('style')).toBe( 'font-size:72pt;font-family:Tahoma;color:blue' ); }); function runTest(childElement: TestChildElement[], result: string) { // Arrange let listItemElement = document.createElement('li'); childElement.forEach(element => { listItemElement.appendChild(createElement(element)); }); // Act setListItemStyle(listItemElement, stylesToInherit); // Assert expect(listItemElement.getAttribute('style')).toBe(result); } function createElement(input: TestChildElement): HTMLElement { const { elementTag, styles, textContent } = input; const element = document.createElement(elementTag); element.setAttribute('style', styles); element.textContent = textContent; return element; } });
the_stack
import type {Mutable, Proto, ObserverType} from "@swim/util"; import type {FastenerOwner, Fastener} from "@swim/component"; import type {Model} from "../model/Model"; import type {AnyTrait, Trait} from "./Trait"; import {TraitRelationInit, TraitRelationClass, TraitRelation} from "./TraitRelation"; /** @internal */ export type TraitRefType<F extends TraitRef<any, any>> = F extends TraitRef<any, infer T> ? T : never; /** @public */ export interface TraitRefInit<T extends Trait = Trait> extends TraitRelationInit<T> { extends?: {prototype: TraitRef<any, any>} | string | boolean | null; key?: string | boolean; } /** @public */ export type TraitRefDescriptor<O = unknown, T extends Trait = Trait, I = {}> = ThisType<TraitRef<O, T> & I> & TraitRefInit<T> & Partial<I>; /** @public */ export interface TraitRefClass<F extends TraitRef<any, any> = TraitRef<any, any>> extends TraitRelationClass<F> { } /** @public */ export interface TraitRefFactory<F extends TraitRef<any, any> = TraitRef<any, any>> extends TraitRefClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): TraitRefFactory<F> & I; define<O, T extends Trait = Trait>(className: string, descriptor: TraitRefDescriptor<O, T>): TraitRefFactory<TraitRef<any, T>>; define<O, T extends Trait = Trait>(className: string, descriptor: {observes: boolean} & TraitRefDescriptor<O, T, ObserverType<T>>): TraitRefFactory<TraitRef<any, T>>; define<O, T extends Trait = Trait, I = {}>(className: string, descriptor: {implements: unknown} & TraitRefDescriptor<O, T, I>): TraitRefFactory<TraitRef<any, T> & I>; define<O, T extends Trait = Trait, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & TraitRefDescriptor<O, T, I & ObserverType<T>>): TraitRefFactory<TraitRef<any, T> & I>; <O, T extends Trait = Trait>(descriptor: TraitRefDescriptor<O, T>): PropertyDecorator; <O, T extends Trait = Trait>(descriptor: {observes: boolean} & TraitRefDescriptor<O, T, ObserverType<T>>): PropertyDecorator; <O, T extends Trait = Trait, I = {}>(descriptor: {implements: unknown} & TraitRefDescriptor<O, T, I>): PropertyDecorator; <O, T extends Trait = Trait, I = {}>(descriptor: {implements: unknown; observes: boolean} & TraitRefDescriptor<O, T, I & ObserverType<T>>): PropertyDecorator; } /** @public */ export interface TraitRef<O = unknown, T extends Trait = Trait> extends TraitRelation<O, T> { (): T | null; (trait: AnyTrait<T> | null, target?: Trait | null, key?: string): O; /** @override */ get fastenerType(): Proto<TraitRef<any, any>>; /** @protected @override */ onInherit(superFastener: Fastener): void; readonly trait: T | null; getTrait(): T; setTrait(trait: AnyTrait<T> | null, target?: Trait | null, key?: string): T | null; attachTrait(trait?: AnyTrait<T>, target?: Trait | null): T; detachTrait(): T | null; insertTrait(model?: Model | null, trait?: AnyTrait<T>, target?: Trait | null, key?: string): T; removeTrait(): T | null; deleteTrait(): T | null; /** @internal @override */ bindModel(model: Model, target: Model | null): void; /** @internal @override */ unbindModel(model: Model): void; /** @override */ detectModel(model: Model): T | null; /** @internal @override */ bindTrait(trait: Trait, target: Trait | null): void; /** @internal @override */ unbindTrait(trait: Trait): void; /** @override */ detectTrait(trait: Trait): T | null; /** @internal */ get key(): string | undefined; // optional prototype field } /** @public */ export const TraitRef = (function (_super: typeof TraitRelation) { const TraitRef: TraitRefFactory = _super.extend("TraitRef"); Object.defineProperty(TraitRef.prototype, "fastenerType", { get: function (this: TraitRef): Proto<TraitRef<any, any>> { return TraitRef; }, configurable: true, }); TraitRef.prototype.onInherit = function (this: TraitRef, superFastener: TraitRef): void { this.setTrait(superFastener.trait); }; TraitRef.prototype.getTrait = function <T extends Trait>(this: TraitRef<unknown, T>): T { const trait = this.trait; if (trait === null) { let message = trait + " "; if (this.name.length !== 0) { message += this.name + " "; } message += "trait"; throw new TypeError(message); } return trait; }; TraitRef.prototype.setTrait = function <T extends Trait>(this: TraitRef<unknown, T>, newTrait: AnyTrait<T> | null, target?: Trait | null, key?: string): T | null { if (newTrait !== null) { newTrait = this.fromAny(newTrait); } let oldTrait = this.trait; if (oldTrait !== newTrait) { if (target === void 0) { target = null; } let model: Model | null; if (this.binds && (model = this.parentModel, model !== null)) { if (oldTrait !== null && oldTrait.model === model) { if (target === null) { target = oldTrait.nextTrait; } oldTrait.remove(); } if (newTrait !== null) { if (key === void 0) { key = this.key; } this.insertChild(model, newTrait, target, key); } oldTrait = this.trait; } if (oldTrait !== newTrait) { if (oldTrait !== null) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).trait = null; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); } if (newTrait !== null) { this.willAttachTrait(newTrait, target); (this as Mutable<typeof this>).trait = newTrait; this.onAttachTrait(newTrait, target); this.initTrait(newTrait); this.didAttachTrait(newTrait, target); } } } return oldTrait; }; TraitRef.prototype.attachTrait = function <T extends Trait>(this: TraitRef<unknown, T>, newTrait?: AnyTrait<T>, target?: Trait | null): T { const oldTrait = this.trait; if (newTrait !== void 0 && newTrait !== null) { newTrait = this.fromAny(newTrait); } else if (oldTrait === null) { newTrait = this.createTrait(); } else { newTrait = oldTrait; } if (newTrait !== oldTrait) { if (target === void 0) { target = null; } if (oldTrait !== null) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).trait = null; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); } this.willAttachTrait(newTrait, target); (this as Mutable<typeof this>).trait = newTrait; this.onAttachTrait(newTrait, target); this.initTrait(newTrait); this.didAttachTrait(newTrait, target); } return newTrait; }; TraitRef.prototype.detachTrait = function <T extends Trait>(this: TraitRef<unknown, T>): T | null { const oldTrait = this.trait; if (oldTrait !== null) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).trait = null; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); } return oldTrait; }; TraitRef.prototype.insertTrait = function <T extends Trait>(this: TraitRef<unknown, T>, model?: Model | null, newTrait?: AnyTrait<T>, target?: Trait | null, key?: string): T { if (newTrait !== void 0 && newTrait !== null) { newTrait = this.fromAny(newTrait); } else { const oldTrait = this.trait; if (oldTrait === null) { newTrait = this.createTrait(); } else { newTrait = oldTrait; } } if (model === void 0 || model === null) { model = this.parentModel; } if (target === void 0) { target = null; } if (key === void 0) { key = this.key; } if (model !== null && (newTrait.parent !== model || newTrait.key !== key)) { this.insertChild(model, newTrait, target, key); } const oldTrait = this.trait; if (newTrait !== oldTrait) { if (oldTrait !== null) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).trait = null; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); oldTrait.remove(); } this.willAttachTrait(newTrait, target); (this as Mutable<typeof this>).trait = newTrait; this.onAttachTrait(newTrait, target); this.initTrait(newTrait); this.didAttachTrait(newTrait, target); } return newTrait; }; TraitRef.prototype.removeTrait = function <T extends Trait>(this: TraitRef<unknown, T>): T | null { const trait = this.trait; if (trait !== null) { trait.remove(); } return trait; }; TraitRef.prototype.deleteTrait = function <T extends Trait>(this: TraitRef<unknown, T>): T | null { const trait = this.detachTrait(); if (trait !== null) { trait.remove(); } return trait; }; TraitRef.prototype.bindModel = function <T extends Trait>(this: TraitRef<unknown, T>, model: Model, target: Model | null): void { if (this.binds && this.trait === null) { const newTrait = this.detectModel(model); if (newTrait !== null) { this.willAttachTrait(newTrait, null); (this as Mutable<typeof this>).trait = newTrait; this.onAttachTrait(newTrait, null); this.initTrait(newTrait); this.didAttachTrait(newTrait, null); } } }; TraitRef.prototype.unbindModel = function <T extends Trait>(this: TraitRef<unknown, T>, model: Model): void { if (this.binds) { const oldTrait = this.detectModel(model); if (oldTrait !== null && this.trait === oldTrait) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).trait = null; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); } } }; TraitRef.prototype.detectModel = function <T extends Trait>(this: TraitRef<unknown, T>, model: Model): T | null { return null; }; TraitRef.prototype.bindTrait = function <T extends Trait>(this: TraitRef<unknown, T>, trait: Trait, target: Trait | null): void { if (this.binds && this.trait === null) { const newTrait = this.detectTrait(trait); if (newTrait !== null) { this.willAttachTrait(newTrait, target); (this as Mutable<typeof this>).trait = newTrait; this.onAttachTrait(newTrait, target); this.initTrait(newTrait); this.didAttachTrait(newTrait, target); } } }; TraitRef.prototype.unbindTrait = function <T extends Trait>(this: TraitRef<unknown, T>, trait: Trait): void { if (this.binds) { const oldTrait = this.detectTrait(trait); if (oldTrait !== null && this.trait === oldTrait) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).trait = null; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); } } }; TraitRef.prototype.detectTrait = function <T extends Trait>(this: TraitRef<unknown, T>, trait: Trait): T | null { const key = this.key; if (key !== void 0 && key === trait.key) { return trait as T; } return null; }; TraitRef.construct = function <F extends TraitRef<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { if (fastener === null) { fastener = function (trait?: AnyTrait<TraitRefType<F>> | null, target?: Trait | null, key?: string): TraitRefType<F> | null | FastenerOwner<F> { if (trait === void 0) { return fastener!.trait; } else { fastener!.setTrait(trait, target, key); return fastener!.owner; } } as F; delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name Object.setPrototypeOf(fastener, fastenerClass.prototype); } fastener = _super.construct(fastenerClass, fastener, owner) as F; (fastener as Mutable<typeof fastener>).trait = null; return fastener; }; TraitRef.define = function <O, T extends Trait>(className: string, descriptor: TraitRefDescriptor<O, T>): TraitRefFactory<TraitRef<any, T>> { let superClass = descriptor.extends as TraitRefFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; if (descriptor.key === true) { Object.defineProperty(descriptor, "key", { value: className, configurable: true, }); } else if (descriptor.key === false) { Object.defineProperty(descriptor, "key", { value: void 0, configurable: true, }); } if (superClass === void 0 || superClass === null) { superClass = this; } const fastenerClass = superClass.extend(className, descriptor); fastenerClass.construct = function (fastenerClass: {prototype: TraitRef<any, any>}, fastener: TraitRef<O, T> | null, owner: O): TraitRef<O, T> { fastener = superClass!.construct(fastenerClass, fastener, owner); if (affinity !== void 0) { fastener.initAffinity(affinity); } if (inherits !== void 0) { fastener.initInherits(inherits); } return fastener; }; return fastenerClass; }; return TraitRef; })(TraitRelation);
the_stack
import { vec3, quat } from 'gl-matrix'; import ModelInstance from '../../modelinstance'; import { createSkeletalNodes, SkeletalNode } from '../../skeletalnode'; import DataTexture from '../../gl/datatexture'; import Scene from '../../scene'; import Texture from '../../texture'; import MdxNode from './node'; import AttachmentInstance from './attachmentinstance'; import ParticleEmitter from './particleemitter'; import ParticleEmitter2 from './particleemitter2'; import RibbonEmitter from './ribbonemitter'; import EventObjectEmitter from './eventobjectemitter'; import EventObjectSpnEmitter from './eventobjectspnemitter'; import EventObjectSplEmitter from './eventobjectsplemitter'; import EventObjectUbrEmitter from './eventobjectubremitter'; import EventObjectSndEmitter from './eventobjectsndemitter'; import MdxModel from './model'; import GenericObject from './genericobject'; import { EMITTER_PARTICLE2_TEXTURE_OFFSET, EMITTER_EVENT_TEXTURE_OFFSET } from './geometryemitterfuncs'; import Bounds from '../../bounds'; const visibilityHeap = new Float32Array(1); const translationHeap = vec3.create(); const rotationHeap = quat.create(); const scaleHeap = vec3.create(); const colorHeap = new Float32Array(3); const alphaHeap = new Float32Array(1); const textureIdHeap = new Uint32Array(1); type SkeletalNodeObject = AttachmentInstance | ParticleEmitter | ParticleEmitter2 | RibbonEmitter | EventObjectEmitter; /** * An MDX model instance. */ export default class MdxModelInstance extends ModelInstance { attachments: AttachmentInstance[] = []; particleEmitters: ParticleEmitter[] = []; particleEmitters2: ParticleEmitter2[] = []; ribbonEmitters: RibbonEmitter[] = []; eventObjectEmitters: (EventObjectSpnEmitter | EventObjectSplEmitter | EventObjectUbrEmitter | EventObjectSndEmitter)[] = []; nodes: SkeletalNode[] = []; sortedNodes: SkeletalNode[] = []; frame = 0; // Global sequences counter = 0; sequence = -1; sequenceLoopMode = 0; sequenceEnded = false; teamColor = 0; vertexColor = new Float32Array([1, 1, 1, 1]); // Particles do not spawn when the sequence is -1, or when the sequence finished and it's not repeating allowParticleSpawn = false; // If forced is true, everything will update regardless of variancy. // Any later non-forced update can then use variancy to skip updating things. // It is set to true every time the sequence is set with setSequence(). forced = true; geosetColors: Float32Array[] = []; layerAlphas: number[] = []; layerTextures: number[] = []; uvAnims: Float32Array[] = []; worldMatrices: Float32Array | null = null; boneTexture: DataTexture | null = null; constructor(model: MdxModel) { super(model); for (let i = 0, l = model.geosets.length; i < l; i++) { this.geosetColors[i] = new Float32Array(4); } for (let i = 0, l = model.layers.length; i < l; i++) { this.layerAlphas[i] = 0; this.layerTextures[i] = 0; this.uvAnims[i] = new Float32Array(5); } // Create the needed amount of shared nodes. const sharedNodeData = createSkeletalNodes(model.genericObjects.length, MdxNode); const nodes = sharedNodeData.nodes; let nodeIndex = 0; this.nodes.push(...nodes); // A shared typed array for all world matrices of the internal nodes. this.worldMatrices = sharedNodeData.worldMatrices; // And now initialize all of the nodes and objects for (const bone of model.bones) { this.initNode(nodes, nodes[nodeIndex++], bone); } for (const light of model.lights) { this.initNode(nodes, nodes[nodeIndex++], light); } for (const helper of model.helpers) { this.initNode(nodes, nodes[nodeIndex++], helper); } for (const attachment of model.attachments) { let attachmentInstance; // Attachments may have game models attached to them, such as Undead and Nightelf building animations. if (attachment.internalModel) { attachmentInstance = new AttachmentInstance(this, attachment); this.attachments.push(attachmentInstance); } this.initNode(nodes, nodes[nodeIndex++], attachment, attachmentInstance); } for (const emitterObject of model.particleEmitters) { const emitter = new ParticleEmitter(this, emitterObject); this.particleEmitters.push(emitter); this.initNode(nodes, nodes[nodeIndex++], emitterObject, emitter); } for (const emitterObject of model.particleEmitters2) { const emitter = new ParticleEmitter2(this, emitterObject); this.particleEmitters2.push(emitter); this.initNode(nodes, nodes[nodeIndex++], emitterObject, emitter); } for (const emitterObject of model.ribbonEmitters) { const emitter = new RibbonEmitter(this, emitterObject); this.ribbonEmitters.push(emitter); this.initNode(nodes, nodes[nodeIndex++], emitterObject, emitter); } for (const emitterObject of model.eventObjects) { const type = emitterObject.type; let emitter; if (type === 'SPN') { emitter = new EventObjectSpnEmitter(this, emitterObject); } else if (type === 'SPL') { emitter = new EventObjectSplEmitter(this, emitterObject); } else if (type === 'UBR') { emitter = new EventObjectUbrEmitter(this, emitterObject); } else { emitter = new EventObjectSndEmitter(this, emitterObject); } this.eventObjectEmitters.push(emitter); this.initNode(nodes, nodes[nodeIndex++], emitterObject, emitter); } for (const collisionShape of model.collisionShapes) { this.initNode(nodes, nodes[nodeIndex++], collisionShape); } // Save a sorted array of all of the nodes, such that every child node comes after its parent. // This allows for flat iteration when updating. const hierarchy = model.hierarchy; for (let i = 0, l = nodes.length; i < l; i++) { this.sortedNodes[i] = nodes[hierarchy[i]]; } if (model.bones.length) { this.boneTexture = new DataTexture(model.viewer.gl, 4, model.bones.length * 4, 1); } } /** * Override the texture at the given index. * * If a texture isn't given, removes the override if there was one. */ setTexture(index: number, texture?: Texture): void { this.overrideTexture(index, texture); } /** * Override the texture of the particle emitter the given index. * * If a texture isn't given, removes the override if there was one. */ setParticle2Texture(index: number, texture?: Texture): void { this.overrideTexture(EMITTER_PARTICLE2_TEXTURE_OFFSET + index, texture); } /** * Override the texture of the event emitter the given index. * * If a texture isn't given, removes the override if there was one. */ setEventTexture(index: number, texture?: Texture): void { this.overrideTexture(EMITTER_EVENT_TEXTURE_OFFSET + index, texture); } /** * Clear all of the emitted objects that belong to this instance. */ override clearEmittedObjects(): void { for (const emitter of this.particleEmitters) { emitter.clear(); } for (const emitter of this.particleEmitters2) { emitter.clear(); } for (const emitter of this.ribbonEmitters) { emitter.clear(); } for (const emitter of this.eventObjectEmitters) { emitter.clear(); } } /** * Initialize a skeletal node. */ initNode(nodes: SkeletalNode[], node: SkeletalNode, genericObject: GenericObject, object?: SkeletalNodeObject): void { vec3.copy(node.pivot, genericObject.pivot); if (genericObject.parentId === -1) { node.parent = this; } else { node.parent = nodes[genericObject.parentId]; } if (genericObject.billboarded) { node.billboarded = true; } else if (genericObject.billboardedX) { node.billboardedX = true; } else if (genericObject.billboardedY) { node.billboardedY = true; } else if (genericObject.billboardedZ) { node.billboardedZ = true; } if (object) { node.object = object; } } /** * Overriden to hide also attachment models. */ override hide(): void { super.hide(); this.resetAttachments(); } /** * Updates all of this instance internal nodes and objects. * Nodes that are determined to not be visible will not be updated, nor will any of their children down the hierarchy. */ updateNodes(dt: number, forced: boolean): void { const sequence = this.sequence; const frame = this.frame; const counter = this.counter; const sortedNodes = this.sortedNodes; const model = <MdxModel>this.model; const sortedGenericObjects = model.sortedGenericObjects; const scene = <Scene>this.scene; // Update the nodes for (let i = 0, l = sortedNodes.length; i < l; i++) { const genericObject = sortedGenericObjects[i]; const node = sortedNodes[i]; const parent = <MdxNode | SkeletalNode>node.parent; let wasDirty = forced || parent.wasDirty || genericObject.anyBillboarding; const variants = genericObject.variants; // Local node transformation. // Use variants to skip animation data when possible. if (forced || variants['generic'][sequence]) { wasDirty = true; // Translation if (forced || variants['translation'][sequence]) { genericObject.getTranslation(node.localLocation, sequence, frame, counter); } // Rotation if (forced || variants['rotation'][sequence]) { genericObject.getRotation(node.localRotation, sequence, frame, counter); } // Scale if (forced || variants['scale'][sequence]) { genericObject.getScale(node.localScale, sequence, frame, counter); } } node.wasDirty = wasDirty; // If this is a forced update, or this node's local data was updated, or the parent node was updated, do a full world update. if (wasDirty) { node.recalculateTransformation(scene); } // If there is an instance object associated with this node (emitter/attachment), and it is visible, update it. if (node.object) { genericObject.getVisibility(visibilityHeap, sequence, frame, counter); // If the attachment/emitter is visible, update it. if (visibilityHeap[0] > 0) { (<SkeletalNodeObject>node.object).update(dt); } } // Recalculate and update child nodes. // Note that this only affects normal nodes such as instances, and not skeletal nodes. for (const child of node.children) { if (wasDirty) { child.recalculateTransformation(); } child.update(dt); } } } /** * If a model has no sequences or is running no sequence, it will only update once since it will never be forced to update. * This is generally the desired behavior, except when it is moved by the client. * Therefore, if an instance is transformed, always do a forced update. */ override recalculateTransformation(): void { super.recalculateTransformation(); this.forced = true; } /** * Update the batch data. */ updateBatches(forced: boolean): void { const sequence = this.sequence; const frame = this.frame; const counter = this.counter; const model = <MdxModel>this.model; const geosets = model.geosets; const layers = model.layers; const geosetColors = this.geosetColors; const layerAlphas = this.layerAlphas; const layerTextures = this.layerTextures; const uvAnims = this.uvAnims; // Geosets for (let i = 0, l = geosets.length; i < l; i++) { const geoset = geosets[i]; const geosetAnimation = geoset.geosetAnimation; const geosetColor = geosetColors[i]; if (geosetAnimation) { // Color if (forced || geosetAnimation.variants['color'][sequence]) { geosetAnimation.getColor(colorHeap, sequence, frame, counter); geosetColor[0] = colorHeap[0]; geosetColor[1] = colorHeap[1]; geosetColor[2] = colorHeap[2]; } // Alpha if (forced || geosetAnimation.variants['alpha'][sequence]) { geosetAnimation.getAlpha(alphaHeap, sequence, frame, counter); geosetColor[3] = alphaHeap[0]; } } else if (forced) { geosetColor[0] = 1; geosetColor[1] = 1; geosetColor[2] = 1; geosetColor[3] = 1; } } // Layers for (let i = 0, l = layers.length; i < l; i++) { const layer = layers[i]; const textureAnimation = layer.textureAnimation; const uvAnim = uvAnims[i]; // Alpha if (forced || layer.variants['alpha'][sequence]) { layer.getAlpha(alphaHeap, sequence, frame, counter); layerAlphas[i] = alphaHeap[0]; } // Sprite animation if (forced || layer.variants['textureId'][sequence]) { layer.getTextureId(textureIdHeap, sequence, frame, counter); layerTextures[i] = textureIdHeap[0]; } if (textureAnimation) { // UV translation animation if (forced || textureAnimation.variants['translation'][sequence]) { textureAnimation.getTranslation(<Float32Array>translationHeap, sequence, frame, counter); uvAnim[0] = translationHeap[0]; uvAnim[1] = translationHeap[1]; } // UV rotation animation if (forced || textureAnimation.variants['rotation'][sequence]) { textureAnimation.getRotation(<Float32Array>rotationHeap, sequence, frame, counter); uvAnim[2] = rotationHeap[2]; uvAnim[3] = rotationHeap[3]; } // UV scale animation if (forced || textureAnimation.variants['scale'][sequence]) { textureAnimation.getScale(<Float32Array>scaleHeap, sequence, frame, counter); uvAnim[4] = scaleHeap[0]; } } else if (forced) { uvAnim[0] = 0; uvAnim[1] = 0; uvAnim[2] = 0; uvAnim[3] = 1; uvAnim[4] = 1; } } } updateBoneTexture(): void { if (this.boneTexture) { this.boneTexture.bindAndUpdate(<Float32Array>this.worldMatrices); } } override renderOpaque(): void { const model = <MdxModel>this.model; for (const group of model.opaqueGroups) { group.render(this); } } override renderTranslucent(): void { const model = <MdxModel>this.model; for (const group of model.translucentGroups) { group.render(this); } } override updateAnimations(dt: number): void { const model = <MdxModel>this.model; const sequenceId = this.sequence; if (sequenceId !== -1) { const sequence = model.sequences[sequenceId]; const interval = sequence.interval; const frameTime = dt * 1000; this.frame += frameTime; this.counter += frameTime; this.allowParticleSpawn = true; if (this.frame >= interval[1]) { if (this.sequenceLoopMode === 2 || (this.sequenceLoopMode === 0 && sequence.nonLooping === 0)) { this.frame = interval[0]; this.resetEventEmitters(); } else { this.frame = interval[1]; this.counter -= frameTime; this.allowParticleSpawn = false; } this.sequenceEnded = true; } else { this.sequenceEnded = false; } } const forced = this.forced; if (sequenceId !== -1 || forced) { // Update the nodes this.updateNodes(dt, forced); // Update the bone texture. this.updateBoneTexture(); // Update the batches this.updateBatches(forced); } this.forced = false; } /** * Set the team color of this instance. */ setTeamColor(id: number): this { this.teamColor = id; return this; } /** * Set the vertex color of this instance. */ setVertexColor(color: Float32Array | number[]): this { this.vertexColor.set(color); return this; } /** * Set the sequence of this instance. */ setSequence(id: number): this { const model = <MdxModel>this.model; const sequences = model.sequences; this.sequence = id; if (id < 0 || id > sequences.length - 1) { this.sequence = -1; this.frame = 0; this.allowParticleSpawn = false; } else { this.frame = sequences[id].interval[0]; } this.resetEventEmitters(); this.resetAttachments(); this.forced = true; return this; } override getBounds(): Bounds { const model = <MdxModel>this.model; if (this.sequence === -1) { return model.bounds; } const bounds = model.sequences[this.sequence].bounds; if (bounds.r === 0) { return model.bounds; } return bounds; } /** * Set the sequence loop mode. * 0 to never loop, 1 to loop based on the model, and 2 to always loop. */ setSequenceLoopMode(mode: number): this { this.sequenceLoopMode = mode; return this; } /** * Get an attachment node. */ getAttachment(id: number): SkeletalNode | undefined { const model = <MdxModel>this.model; const attachment = model.attachments[id]; if (attachment) { return this.nodes[attachment.index]; } return; } resetEventEmitters(): void { for (const emitter of this.eventObjectEmitters) { emitter.lastValue = 0; } } resetAttachments(): void { for (const attachment of this.attachments) { attachment.internalInstance.hide(); } } }
the_stack
import { Component, AfterViewInit, OnInit, OnDestroy, OnChanges, ViewChild, SimpleChanges, Input, NgZone, } from '@angular/core'; import { ConfigService } from 'services/config.service'; import { Subscription, timer } from 'rxjs'; import { Media, Configuration } from '@vimtur/common'; import { isMobile } from 'is-mobile'; import Hls from 'hls.js'; const PLAYER_CONTROLS_TIMEOUT = 3000; const DOUBLE_CLICK_TIMEOUT = 500; interface QualityLevel { index: number; height: number; } interface VideoPlayerState { playing?: boolean; duration?: number; currentTime?: number; width?: number; height?: number; top?: number; loading?: boolean; switching?: boolean; active?: Subscription; inControls?: boolean; lastClick?: number; fullscreen?: boolean; navigationTime?: number; muted?: boolean; volume?: number; updatingVolume?: boolean; previewTime?: number; qualities?: QualityLevel[]; currentQuality?: number; selectedQuality?: QualityLevel; } @Component({ selector: 'app-video-player', templateUrl: './video-player.component.html', styleUrls: ['./video-player.component.scss'], }) export class VideoPlayerComponent implements AfterViewInit, OnInit, OnDestroy, OnChanges { @ViewChild('videoElement', { static: false }) public videoElement: any; @ViewChild('videoPlayer', { static: false }) public videoPlayer: any; @Input() public media?: Media; public videoPlayerState: VideoPlayerState = { muted: true, }; public qualitySelectorOpen = false; public readonly isMobile = isMobile(); private configService: ConfigService; private subscriptions: Subscription[] = []; private hls?: any; private config?: Configuration.Main; private zone: NgZone; private initialised = false; public constructor(configService: ConfigService, zone: NgZone) { this.configService = configService; this.zone = zone; } public ngOnInit() { this.subscriptions.push( this.configService.getConfiguration().subscribe(config => { this.config = config; }), ); } public ngOnDestroy() { for (const subscription of this.subscriptions) { subscription.unsubscribe(); } this.subscriptions = []; if (this.videoPlayerState.active) { this.videoPlayerState.active.unsubscribe(); this.videoPlayerState.active = undefined; } if (this.videoElement) { this.videoElement.nativeElement.pause(); } if (this.hls) { this.hls.detachMedia(); this.hls = undefined; } } public ngOnChanges(changes: SimpleChanges) { if (!changes.media) { return; } // If not previous value or next value let reset = !changes.media.previousValue || !changes.media.currentValue; // If current and previous and hashes don't match if (changes.media.previousValue && changes.media.currentValue) { reset = changes.media.previousValue.hash !== changes.media.currentValue.hash; } if (reset) { if (this.hls) { this.initialised = false; if (this.videoElement) { this.videoElement.nativeElement.pause(); } this.hls.detachMedia(); this.hls.destroy(); this.hls = undefined; this.videoPlayerState = { width: this.videoPlayerState.width, height: this.videoPlayerState.height, top: this.videoPlayerState.top, inControls: this.videoPlayerState.inControls, active: this.videoPlayerState.active, selectedQuality: this.videoPlayerState.selectedQuality, muted: this.videoPlayerState.muted, volume: this.videoPlayerState.volume, }; } if (this.media && this.media.type === 'video') { this.playVideo(this.media); } } } public onSeeking() { const lowQualityOnSeek = this.config && (this.isMobile ? this.config.user.lowQualityOnLoadEnabledForMobile : this.config.user.lowQualityOnLoadEnabled); // Only has an effect if the segment isn't already loaded. if (lowQualityOnSeek) { console.debug('Seeking - Forcing to level 0'); this.hls.nextLoadLevel = 0; } } public onPlay() { if (this.hls) { const autoPlay = !this.isMobile && this.config && this.config.user.autoplayEnabled; if (!autoPlay) { this.hls.startLoad(); } } } public onResized() { if (this.videoElement) { const update = this.videoElement.nativeElement.clientWidth !== this.videoPlayerState.width || this.videoElement.nativeElement.clientHeight !== this.videoPlayerState.height || this.videoElement.nativeElement.offsetTop !== this.videoPlayerState.top; if (update) { setTimeout(() => { this.zone.run(() => { this.videoPlayerState.width = this.videoElement.nativeElement.clientWidth; this.videoPlayerState.height = this.videoElement.nativeElement.clientHeight; this.videoPlayerState.top = this.videoElement.nativeElement.offsetTop; }); }, 0); } } } public ngAfterViewInit() { if (!this.media || this.media.type !== 'video') { return; } this.onResized(); if (this.videoElement) { this.videoElement.nativeElement.muted = true; } this.playVideo(this.media); } public syncVolume() { if (!this.videoElement) { return; } this.videoPlayerState.muted = this.videoElement.nativeElement.muted; this.videoPlayerState.volume = this.videoElement.nativeElement.volume; } public updateNavigationTime(event: any, start = false) { if (event.type.startsWith('touch')) { event.preventDefault(); event.clientX = event.changedTouches[0] && event.changedTouches[0].clientX; event.button = 0; } if (!this.videoElement || !this.videoPlayerState.duration) { return; } const rect = (event.currentTarget || event.target).getBoundingClientRect(); const offsetX = event.clientX - rect.left; const percent = offsetX / (rect.right - rect.left); const time = percent * this.videoPlayerState.duration; this.videoPlayerState.previewTime = time; if (!start && this.videoPlayerState.navigationTime === undefined) { return; } if (start && event.button !== 0) { return; } this.videoPlayerState.navigationTime = time; } public applyNavigationTime() { this.videoPlayerState.previewTime = undefined; if (!this.videoElement || this.videoPlayerState.navigationTime === undefined) { return; } const duration = this.videoElement.nativeElement.duration; if (this.videoPlayerState.navigationTime < 0) { this.videoPlayerState.navigationTime = 0; } else if (this.videoPlayerState.navigationTime > duration) { this.videoPlayerState.navigationTime = duration; } if ( this.videoPlayerState.navigationTime !== undefined && !isNaN(this.videoPlayerState.navigationTime) ) { console.debug(`Seeking to ${this.videoPlayerState.navigationTime}`); this.videoElement.nativeElement.currentTime = this.videoPlayerState.navigationTime; } this.videoPlayerState.navigationTime = undefined; } public updateVolume(event: any) { if (event.type.startsWith('touch')) { event.preventDefault(); event.clientX = event.changedTouches[0] && event.changedTouches[0].clientX; event.button = 0; } if (!this.videoElement || event.button !== 0) { return; } if (event.type === 'mousedown' || event.type === 'touchstart') { this.videoPlayerState.updatingVolume = true; } if (this.videoPlayerState.updatingVolume) { const rect = event.currentTarget.getBoundingClientRect(); const offsetX = event.clientX - rect.left; let volume = offsetX / (rect.right - rect.left); if (volume < 0) { volume = 0; } else if (volume > 1) { volume = 1; } this.videoElement.nativeElement.volume = volume; } if (event.type === 'mouseup' || event.type === 'mouseleave' || event.type === 'touchend') { this.videoPlayerState.updatingVolume = false; } } public areControlsOpen(): boolean { return Boolean( !this.videoPlayerState.playing || this.videoPlayerState.loading || this.videoPlayerState.inControls || this.videoPlayerState.active || this.videoPlayerState.updatingVolume || this.videoPlayerState.navigationTime !== undefined || this.qualitySelectorOpen, ); } public toggleFullscreen() { if (!this.videoPlayer) { return; } if (document.fullscreenElement) { document.exitFullscreen(); } else { this.videoPlayer.nativeElement.requestFullscreen(); } } public isFullscreen(): boolean { return !!document.fullscreenElement; } public updatePlayerActivity(move = false) { if (move && this.isMobile) { return; } if (this.videoPlayerState.active) { this.videoPlayerState.active.unsubscribe(); this.videoPlayerState.active = undefined; } this.videoPlayerState.active = timer(PLAYER_CONTROLS_TIMEOUT).subscribe(() => { if (this.videoPlayerState.active) { this.videoPlayerState.active.unsubscribe(); this.videoPlayerState.active = undefined; } }); } public formatTime(value?: number): string { value = value || 0; const hours = Math.floor(value / 3600); const minutes = Math.floor((value % 3600) / 60); const seconds = Math.floor(value % 60); const time: string[] = []; const pad = (num: number) => { return num < 10 ? `0${num}` : `${num}`; }; if (hours > 0) { time.push(String(hours)); } time.push(pad(minutes)); time.push(pad(seconds)); return time.join(':'); } public toggleVideoPlay() { if (!this.videoElement) { return; } if (this.videoPlayerState.playing) { this.videoElement.nativeElement.pause(); } else { this.videoElement.nativeElement.play(); } } public onVideoOverlayClick() { this.toggleVideoPlay(); const lastClick = this.videoPlayerState.lastClick; if (lastClick && Date.now() - lastClick < DOUBLE_CLICK_TIMEOUT) { this.toggleFullscreen(); } this.videoPlayerState.lastClick = Date.now(); } public selectQuality(quality: QualityLevel) { this.qualitySelectorOpen = false; if (!this.hls) { return; } if (quality.index === -1) { console.debug('switching hls stream to auto'); this.videoPlayerState.currentQuality = -1; this.videoPlayerState.selectedQuality = undefined; this.hls.currentLevel = quality.index; this.videoPlayerState.switching = true; return; } this.videoPlayerState.selectedQuality = quality; if (this.hls.levels.length === 0) { return; } const foundIndex = this.hls.levels.findIndex( (l: { height: number }) => l.height >= quality.height, ); this.videoPlayerState.currentQuality = foundIndex === undefined ? this.hls.levels.length - 1 : foundIndex; console.debug( 'switching hls stream quality', this.videoPlayerState.currentQuality, this.hls.levels, ); this.hls.currentLevel = this.videoPlayerState.currentQuality; this.videoPlayerState.switching = true; } private playVideo(media: Media) { if (!this.videoElement) { console.warn('playVideo called before videoElement initialised'); return; } if (this.initialised) { return; } else { this.initialised = true; } const autoPlay = !this.isMobile && this.config && this.config.user.autoplayEnabled; const lowQualityOnSeek = this.config && (this.isMobile ? this.config.user.lowQualityOnLoadEnabledForMobile : this.config.user.lowQualityOnLoadEnabled); console.debug('playing video', media.hash, lowQualityOnSeek, autoPlay); this.hls = new Hls({ autoStartLoad: false, capLevelToPlayerSize: true, maxBufferHole: 5, maxBufferLength: 15, startLevel: lowQualityOnSeek ? 0 : -1, }); this.videoElement.nativeElement.volume = this.videoPlayerState.volume || 1; this.videoElement.nativeElement.muted = this.videoPlayerState.muted; this.hls.on( Hls.Events.MANIFEST_PARSED, (_: unknown, data: { levels: Array<{ height: number }> }) => { console.log('Manifest quality levels', data.levels); this.zone.run(() => { this.videoPlayerState.qualities = data.levels.map( (level: { height: number }, index: number) => ({ height: level.height, index, }), ); if (this.videoPlayerState.selectedQuality !== undefined) { this.selectQuality(this.videoPlayerState.selectedQuality); } }); if (autoPlay) { this.videoElement.nativeElement.play(); } }, ); /*for (const key of Object.keys(Hls.Events)) { this.hls.on(Hls.Events[key], (event, data) => { if (key !== 'FRAG_LOAD_PROGRESS' && key !== 'BUFFER_APPENDED' && key !== 'BUFFER_APPENDING' && key !== 'STREAM_STATE_TRANSITION') { console.log(key, event, data); } }); }*/ // Need this for when switching from a fixed quality to auto. this.hls.on(Hls.Events.FRAG_LOADED, () => { this.zone.run(() => { if (this.hls.currentLevel >= 0) { this.videoPlayerState.currentQuality = this.hls.currentLevel; } this.videoPlayerState.switching = false; }); }); this.hls.on(Hls.Events.LEVEL_SWITCHED, (_: unknown, data: { level: number }) => { console.debug('Switched to quality level', data.level, this.hls.levels[data.level]); this.zone.run(() => { this.videoPlayerState.currentQuality = data.level; this.videoPlayerState.switching = false; }); }); this.hls.on(Hls.Events.ERROR, (event: unknown, data: unknown) => { console.warn('HLS error', event, data); }); this.hls.attachMedia(this.videoElement.nativeElement); this.hls.loadSource(`/api/images/${media.hash}/stream/index.m3u8`); if (autoPlay) { this.hls.startLoad(); } } }
the_stack
/// <reference types="node"/> declare namespace BN { type Endianness = 'le' | 'be'; type IPrimeName = 'k256' | 'p224' | 'p192' | 'p25519'; interface MPrime { name: string; p: BN; n: number; k: BN; } interface ReductionContext { m: number; prime: MPrime; [key: string]: any; } } declare class BN { static BN: typeof BN; static wordSize: 26; constructor( number: number | string | number[] | Uint8Array | Buffer | BN, base?: number | 'hex', endian?: BN.Endianness ); constructor( number: number | string | number[] | Uint8Array | Buffer | BN, endian?: BN.Endianness ) /** * @description create a reduction context */ static red(reductionContext: BN | BN.IPrimeName): BN.ReductionContext; /** * @description create a reduction context with the Montgomery trick. */ static mont(num: BN): BN.ReductionContext; /** * @description returns true if the supplied object is a BN.js instance */ static isBN(b: any): b is BN; /** * @description returns the maximum of 2 BN instances. */ static max(left: BN, right: BN): BN; /** * @description returns the minimum of 2 BN instances. */ static min(left: BN, right: BN): BN; /** * @description clone number */ clone(): BN; /** * @description convert to base-string and pad with zeroes */ toString(base?: number | 'hex', length?: number): string; /** * @description convert to Javascript Number (limited to 53 bits) */ toNumber(): number; /** * @description convert to JSON compatible hex string (alias of toString(16)) */ toJSON(): string; /** * @description convert to byte Array, and optionally zero pad to length, throwing if already exceeding */ toArray(endian?: BN.Endianness, length?: number): number[]; /** * @description convert to an instance of `type`, which must behave like an Array */ toArrayLike( ArrayType: typeof Buffer, endian?: BN.Endianness, length?: number ): Buffer; toArrayLike( ArrayType: any[], endian?: BN.Endianness, length?: number ): any[]; /** * @description convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: a.toArrayLike(Buffer, endian, length) */ toBuffer(endian?: BN.Endianness, length?: number): Buffer; /** * @description get number of bits occupied */ bitLength(): number; /** * @description return number of less-significant consequent zero bits (example: 1010000 has 4 zero bits) */ zeroBits(): number; /** * @description return number of bytes occupied */ byteLength(): number; /** * @description true if the number is negative */ isNeg(): boolean; /** * @description check if value is even */ isEven(): boolean; /** * @description check if value is odd */ isOdd(): boolean; /** * @description check if value is zero */ isZero(): boolean; /** * @description compare numbers and return `-1 (a < b)`, `0 (a == b)`, or `1 (a > b)` depending on the comparison result */ cmp(b: BN): -1 | 0 | 1; /** * @description compare numbers and return `-1 (a < b)`, `0 (a == b)`, or `1 (a > b)` depending on the comparison result */ ucmp(b: BN): -1 | 0 | 1; /** * @description compare numbers and return `-1 (a < b)`, `0 (a == b)`, or `1 (a > b)` depending on the comparison result */ cmpn(b: number): -1 | 0 | 1; /** * @description a less than b */ lt(b: BN): boolean; /** * @description a less than b */ ltn(b: number): boolean; /** * @description a less than or equals b */ lte(b: BN): boolean; /** * @description a less than or equals b */ lten(b: number): boolean; /** * @description a greater than b */ gt(b: BN): boolean; /** * @description a greater than b */ gtn(b: number): boolean; /** * @description a greater than or equals b */ gte(b: BN): boolean; /** * @description a greater than or equals b */ gten(b: number): boolean; /** * @description a equals b */ eq(b: BN): boolean; /** * @description a equals b */ eqn(b: number): boolean; /** * @description convert to two's complement representation, where width is bit width */ toTwos(width: number): BN; /** * @description convert from two's complement representation, where width is the bit width */ fromTwos(width: number): BN; /** * @description negate sign */ neg(): BN; /** * @description negate sign */ ineg(): BN; /** * @description absolute value */ abs(): BN; /** * @description absolute value */ iabs(): BN; /** * @description addition */ add(b: BN): BN; /** * @description addition */ iadd(b: BN): BN; /** * @description addition */ addn(b: number): BN; /** * @description addition */ iaddn(b: number): BN; /** * @description subtraction */ sub(b: BN): BN; /** * @description subtraction */ isub(b: BN): BN; /** * @description subtraction */ subn(b: number): BN; /** * @description subtraction */ isubn(b: number): BN; /** * @description multiply */ mul(b: BN): BN; /** * @description multiply */ imul(b: BN): BN; /** * @description multiply */ muln(b: number): BN; /** * @description multiply */ imuln(b: number): BN; /** * @description square */ sqr(): BN; /** * @description square */ isqr(): BN; /** * @description raise `a` to the power of `b` */ pow(b: BN): BN; /** * @description divide */ div(b: BN): BN; /** * @description divide */ divn(b: number): BN; /** * @description divide */ idivn(b: number): BN; /** * @description reduct */ mod(b: BN): BN; /** * @description reduct */ umod(b: BN): BN; /** * @deprecated * @description reduct */ modn(b: number): number; /** * @description reduct */ modrn(b: number): number; /** * @description rounded division */ divRound(b: BN): BN; /** * @description or */ or(b: BN): BN; /** * @description or */ ior(b: BN): BN; /** * @description or */ uor(b: BN): BN; /** * @description or */ iuor(b: BN): BN; /** * @description and */ and(b: BN): BN; /** * @description and */ iand(b: BN): BN; /** * @description and */ uand(b: BN): BN; /** * @description and */ iuand(b: BN): BN; /** * @description and (NOTE: `andln` is going to be replaced with `andn` in future) */ andln(b: number): BN; /** * @description xor */ xor(b: BN): BN; /** * @description xor */ ixor(b: BN): BN; /** * @description xor */ uxor(b: BN): BN; /** * @description xor */ iuxor(b: BN): BN; /** * @description set specified bit to 1 */ setn(b: number): BN; /** * @description shift left */ shln(b: number): BN; /** * @description shift left */ ishln(b: number): BN; /** * @description shift left */ ushln(b: number): BN; /** * @description shift left */ iushln(b: number): BN; /** * @description shift right */ shrn(b: number): BN; /** * @description shift right (unimplemented https://github.com/indutny/bn.js/blob/master/lib/bn.js#L2086) */ ishrn(b: number): BN; /** * @description shift right */ ushrn(b: number): BN; /** * @description shift right */ iushrn(b: number): BN; /** * @description test if specified bit is set */ testn(b: number): boolean; /** * @description clear bits with indexes higher or equal to `b` */ maskn(b: number): BN; /** * @description clear bits with indexes higher or equal to `b` */ imaskn(b: number): BN; /** * @description add `1 << b` to the number */ bincn(b: number): BN; /** * @description not (for the width specified by `w`) */ notn(w: number): BN; /** * @description not (for the width specified by `w`) */ inotn(w: number): BN; /** * @description GCD */ gcd(b: BN): BN; /** * @description Extended GCD results `({ a: ..., b: ..., gcd: ... })` */ egcd(b: BN): { a: BN; b: BN; gcd: BN }; /** * @description inverse `a` modulo `b` */ invm(b: BN): BN; /** * @description Convert number to red */ toRed(reductionContext: BN.ReductionContext): RedBN; } /** * Big-Number class with additionnal methods that are using modular * operation. */ declare class RedBN extends BN { /** * @description Convert back a number using a reduction context */ fromRed(): BN; /** * @description modular addition */ redAdd(b: BN): RedBN; /** * @description in-place modular addition */ redIAdd(b: BN): RedBN; /** * @description modular subtraction */ redSub(b: BN): RedBN; /** * @description in-place modular subtraction */ redISub(b: BN): RedBN; /** * @description modular shift left */ redShl(num: number): RedBN; /** * @description modular multiplication */ redMul(b: BN): RedBN; /** * @description in-place modular multiplication */ redIMul(b: BN): RedBN; /** * @description modular square */ redSqr(): RedBN; /** * @description in-place modular square */ redISqr(): RedBN; /** * @description modular square root */ redSqrt(): RedBN; /** * @description modular inverse of the number */ redInvm(): RedBN; /** * @description modular negation */ redNeg(): RedBN; /** * @description modular exponentiation */ redPow(b: BN): RedBN; } export = BN;
the_stack
'use strict'; import * as fs from 'fs'; /* tslint:disable */ let util = { getDataType: function (data: any): string { if (typeof data === 'string') { return 'string'; } if (data instanceof Array) { return 'array'; } if (typeof global !== 'undefined' && global.Buffer && global.Buffer.isBuffer(data)) { return 'buffer'; } if (data instanceof ArrayBuffer) { return 'arraybuffer'; } if (data.buffer instanceof ArrayBuffer) { return 'view'; } if (data instanceof Blob) { return 'blob'; } throw new Error('Unsupported data type.'); } }; // The Rusha object is a wrapper around the low-level RushaCore. // It provides means of converting different inputs to the // format accepted by RushaCore as well as other utility methods. function Rusha(chunkSize: any) { 'use strict'; // Private object structure. let self$2: any = { fill: 0 }; // Calculate the length of buffer that the sha1 routine uses // including the padding. let padlen: any = function (len: any) { for (len += 9; len % 64 > 0; len += 1); return len; }; let padZeroes: any = function (bin: any, len: any) { for (let i = len >> 2; i < bin.length; i++) bin[i] = 0; }; let padData: any = function (bin: any, chunkLen: any, msgLen: any) { bin[chunkLen >> 2] |= 128 << 24 - (chunkLen % 4 << 3); bin[((chunkLen >> 2) + 2 & ~15) + 14] = msgLen >> 29; bin[((chunkLen >> 2) + 2 & ~15) + 15] = msgLen << 3; }; // Convert a binary string and write it to the heap. // A binary string is expected to only contain char codes < 256. let convStr: any = function (H8: any, H32: any, start: any, len: any, off: any) { let str = this, i: any, om = off % 4, lm = len % 4, j = len - lm; if (j > 0) { switch (om) { case 0: H8[off + 3 | 0] = str.charCodeAt(start); case 1: H8[off + 2 | 0] = str.charCodeAt(start + 1); case 2: H8[off + 1 | 0] = str.charCodeAt(start + 2); case 3: H8[off | 0] = str.charCodeAt(start + 3); } } for (i = om; i < j; i = i + 4 | 0) { H32[off + i >> 2] = str.charCodeAt(start + i) << 24 | str.charCodeAt(start + i + 1) << 16 | str.charCodeAt(start + i + 2) << 8 | str.charCodeAt(start + i + 3); } switch (lm) { case 3: H8[off + j + 1 | 0] = str.charCodeAt(start + j + 2); case 2: H8[off + j + 2 | 0] = str.charCodeAt(start + j + 1); case 1: H8[off + j + 3 | 0] = str.charCodeAt(start + j); } }; // Convert a buffer or array and write it to the heap. // The buffer or array is expected to only contain elements < 256. let convBuf: any = function (H8: any, H32: any, start: any, len: any, off: any) { let buf = this, i: any, om = off % 4, lm = len % 4, j = len - lm; if (j > 0) { switch (om) { case 0: H8[off + 3 | 0] = buf[start]; case 1: H8[off + 2 | 0] = buf[start + 1]; case 2: H8[off + 1 | 0] = buf[start + 2]; case 3: H8[off | 0] = buf[start + 3]; } } for (i = 4 - om; i < j; i = i += 4 | 0) { H32[off + i >> 2] = buf[start + i] << 24 | buf[start + i + 1] << 16 | buf[start + i + 2] << 8 | buf[start + i + 3]; } switch (lm) { case 3: H8[off + j + 1 | 0] = buf[start + j + 2]; case 2: H8[off + j + 2 | 0] = buf[start + j + 1]; case 1: H8[off + j + 3 | 0] = buf[start + j]; } }; let convFn = function (data: any): any { switch (util.getDataType(data)) { case 'string': return convStr.bind(data); case 'array': return convBuf.bind(data); case 'buffer': return convBuf.bind(data); case 'arraybuffer': return convBuf.bind(new Uint8Array(data)); case 'view': return convBuf.bind(new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); } }; let slice = function (data: any, offset: any): any { switch (util.getDataType(data)) { case 'string': return data.slice(offset); case 'array': return data.slice(offset); case 'buffer': return data.slice(offset); case 'arraybuffer': return data.slice(offset); case 'view': return data.buffer.slice(offset); } }; // Convert an ArrayBuffer into its hexadecimal string representation. let hex = function (arrayBuffer: any): any { let i: any, x: any, hex_tab = '0123456789abcdef', res: any[] = [], binarray = new Uint8Array(arrayBuffer); for (i = 0; i < binarray.length; i++) { x = binarray[i]; res[i] = hex_tab.charAt(x >> 4 & 15) + hex_tab.charAt(x >> 0 & 15); } return res.join(''); }; let ceilHeapSize = function (v: any): any { // The asm.js spec says: // The heap object's byteLength must be either // 2^n for n in [12, 24) or 2^24 * n for n ≥ 1. // Also, byteLengths smaller than 2^16 are deprecated. let p: any; // If v is smaller than 2^16, the smallest possible solution // is 2^16. if (v <= 65536) return 65536; // If v < 2^24, we round up to 2^n, // otherwise we round up to 2^24 * n. if (v < 16777216) { for (p = 1; p < v; p = p << 1); } else { for (p = 16777216; p < v; p += 16777216); } return p; }; // Initialize the internal data structures to a new capacity. let init = function (size: any): any { if (size % 64 > 0) { throw new Error('Chunk size must be a multiple of 128 bit'); } self$2.maxChunkLen = size; self$2.padMaxChunkLen = padlen(size); // The size of the heap is the sum of: // 1. The padded input message size // 2. The extended space the algorithm needs (320 byte) // 3. The 160 bit state the algoritm uses self$2.heap = new ArrayBuffer(ceilHeapSize(self$2.padMaxChunkLen + 320 + 20)); self$2.h32 = new Int32Array(self$2.heap); self$2.h8 = new Int8Array(self$2.heap); self$2.core = new (<any>Rusha)._core({ Int32Array: Int32Array, DataView: DataView }, {}, self$2.heap); self$2.buffer = null; }; // Iinitializethe datastructures according // to a chunk siyze. init(chunkSize || 64 * 1024); let initState = function (heap: any, padMsgLen: any): any { let io = new Int32Array(heap, padMsgLen + 320, 5); io[0] = 1732584193; io[1] = -271733879; io[2] = -1732584194; io[3] = 271733878; io[4] = -1009589776; }; let padChunk = function (chunkLen: any, msgLen: any): any { let padChunkLen = padlen(chunkLen); let view = new Int32Array(self$2.heap, 0, padChunkLen >> 2); padZeroes(view, chunkLen); padData(view, chunkLen, msgLen); return padChunkLen; }; // Write data to the heap. let write = function (data: any, chunkOffset: any, chunkLen: any): any { convFn(data)(self$2.h8, self$2.h32, chunkOffset, chunkLen, 0); }; // Initialize and call the RushaCore, // assuming an input buffer of length len * 4. let coreCall = function (data: any, chunkOffset: any, chunkLen: any, msgLen: any, finalize: any): any { let padChunkLen = chunkLen; if (finalize) { padChunkLen = padChunk(chunkLen, msgLen); } write(data, chunkOffset, chunkLen); self$2.core.hash(padChunkLen, self$2.padMaxChunkLen); }; let getRawDigest = function (heap: any, padMaxChunkLen: any): any { let io = new Int32Array(heap, padMaxChunkLen + 320, 5); let out = new Int32Array(5); let arr = new DataView(out.buffer); arr.setInt32(0, io[0], false); arr.setInt32(4, io[1], false); arr.setInt32(8, io[2], false); arr.setInt32(12, io[3], false); arr.setInt32(16, io[4], false); return out; }; // Calculate the hash digest as an array of 5 32bit integers. let rawDigest = this.rawDigest = function (str: any): any { let msgLen = str.byteLength || str.length || str.size || 0; initState(self$2.heap, self$2.padMaxChunkLen); let chunkOffset = 0, chunkLen = self$2.maxChunkLen, last: any; for (chunkOffset = 0; msgLen > chunkOffset + chunkLen; chunkOffset += chunkLen) { coreCall(str, chunkOffset, chunkLen, msgLen, false); } coreCall(str, chunkOffset, msgLen - chunkOffset, msgLen, true); return getRawDigest(self$2.heap, self$2.padMaxChunkLen); }; // The digest and digestFrom* interface returns the hash digest // as a hex string. this.digest = this.digestFromString = this.digestFromBuffer = this.digestFromArrayBuffer = function (str: any): any { return hex(rawDigest(str).buffer); }; } ; // The low-level RushCore module provides the heart of Rusha, // a high-speed sha1 implementation working on an Int32Array heap. // At first glance, the implementation seems complicated, however // with the SHA1 spec at hand, it is obvious this almost a textbook // implementation that has a few functions hand-inlined and a few loops // hand-unrolled. (<any>Rusha)._core = function RushaCore(stdlib: any, foreign: any, heap: any): any { 'use asm'; let H = new stdlib.Int32Array(heap); function hash(k: any, x: any) { // k in bytes k = k | 0; x = x | 0; let i = 0, j = 0, y0 = 0, z0 = 0, y1 = 0, z1 = 0, y2 = 0, z2 = 0, y3 = 0, z3 = 0, y4 = 0, z4 = 0, t0 = 0, t1 = 0; y0 = H[x + 320 >> 2] | 0; y1 = H[x + 324 >> 2] | 0; y2 = H[x + 328 >> 2] | 0; y3 = H[x + 332 >> 2] | 0; y4 = H[x + 336 >> 2] | 0; for (i = 0; (i | 0) < (k | 0); i = i + 64 | 0) { z0 = y0; z1 = y1; z2 = y2; z3 = y3; z4 = y4; for (j = 0; (j | 0) < 64; j = j + 4 | 0) { t1 = H[i + j >> 2] | 0; t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | ~y1 & y3) | 0) + ((t1 + y4 | 0) + 1518500249 | 0) | 0; y4 = y3; y3 = y2; y2 = y1 << 30 | y1 >>> 2; y1 = y0; y0 = t0; H[k + j >> 2] = t1; } for (j = k + 64 | 0; (j | 0) < (k + 80 | 0); j = j + 4 | 0) { t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31; t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | ~y1 & y3) | 0) + ((t1 + y4 | 0) + 1518500249 | 0) | 0; y4 = y3; y3 = y2; y2 = y1 << 30 | y1 >>> 2; y1 = y0; y0 = t0; H[j >> 2] = t1; } for (j = k + 80 | 0; (j | 0) < (k + 160 | 0); j = j + 4 | 0) { t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31; t0 = ((y0 << 5 | y0 >>> 27) + (y1 ^ y2 ^ y3) | 0) + ((t1 + y4 | 0) + 1859775393 | 0) | 0; y4 = y3; y3 = y2; y2 = y1 << 30 | y1 >>> 2; y1 = y0; y0 = t0; H[j >> 2] = t1; } for (j = k + 160 | 0; (j | 0) < (k + 240 | 0); j = j + 4 | 0) { t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31; t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | y1 & y3 | y2 & y3) | 0) + ((t1 + y4 | 0) - 1894007588 | 0) | 0; y4 = y3; y3 = y2; y2 = y1 << 30 | y1 >>> 2; y1 = y0; y0 = t0; H[j >> 2] = t1; } for (j = k + 240 | 0; (j | 0) < (k + 320 | 0); j = j + 4 | 0) { t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31; t0 = ((y0 << 5 | y0 >>> 27) + (y1 ^ y2 ^ y3) | 0) + ((t1 + y4 | 0) - 899497514 | 0) | 0; y4 = y3; y3 = y2; y2 = y1 << 30 | y1 >>> 2; y1 = y0; y0 = t0; H[j >> 2] = t1; } y0 = y0 + z0 | 0; y1 = y1 + z1 | 0; y2 = y2 + z2 | 0; y3 = y3 + z3 | 0; y4 = y4 + z4 | 0; } H[x + 320 >> 2] = y0; H[x + 324 >> 2] = y1; H[x + 328 >> 2] = y2; H[x + 332 >> 2] = y3; H[x + 336 >> 2] = y4; } return { hash: hash }; }; interface NamedStream { name: string; stream: NodeJS.ReadableStream } function concat(inputs: NamedStream[], output: NodeJS.WritableStream, code: number): void { 'use strict'; if (!inputs || !inputs.length) { process.exit(code); return; } let currentNS = inputs[0]; inputs = inputs.slice(1); if (!currentNS) { // use setTimeout to avoid a deep stack as well as // cooperatively yield setTimeout(concat, 0, inputs, output, code); return; } let current = currentNS.stream; let result: Buffer = null; current.on('readable', function(): void { let buf: Buffer = <any>(current.read()); if (buf === null) return; if (!result) { result = buf; return; } result = Buffer.concat([result, buf]); }); current.on('end', function(): void { if (!result) { setTimeout(concat, 0, inputs, output, code); return; } let rusha: any = new (<any>Rusha)(); let digest: string = rusha.digestFromBuffer(result); process.stdout.write(digest + ' ' + currentNS.name + '\n', () => { setTimeout(concat, 0, inputs, output, code); }); }); } function main(): void { 'use strict'; let argv = process.argv; let pathToNode = argv[0]; let pathToScript = argv[1]; let args = argv.slice(2); // exit code to use - if we fail to open an input file it gets // set to 1 below. let code = 0; if (!args.length) args = ['-']; let files: NamedStream[] = []; let opened = 0; // use map instead of a for loop so that we easily get the // tuple of (path, i) on each iteration. args.map(function(path: string, i: number): void { if (path === '-') { files[i] = {name: path, stream: process.stdin}; // if we've opened all of the files, pipe them // to stdout. if (++opened === args.length) setTimeout(concat, 0, files, process.stdout, code); return; } fs.open(path, 'r', function(err: any, fd: any): void { if (err) { // if we couldn't open the specified // file we should print a message but // not exit early - we need to process // as many inputs as we can. files[i] = null; code = 1; process.stderr.write(pathToScript + ': ' + err.message + '\n'); } else { files[i] = {name: path, stream: fs.createReadStream(path, {fd: fd})}; } // if we've opened all of the files, // pipe them to stdout. if (++opened === args.length) setTimeout(concat, 0, files, process.stdout, code); }); }); } main();
the_stack
/** @jsxFrag Fragment */ import { Fragment, h } from "preact"; import { PageProps } from "$fresh/server.ts"; import { Head } from "$fresh/runtime.ts"; import { tw } from "@twind"; import { Handlers } from "$fresh/server.ts"; import { Header } from "@/components/Header.tsx"; import { Footer } from "@/components/Footer.tsx"; import { InlineCode } from "@/components/InlineCode.tsx"; import { BenchmarkRun, formatKB, formatLogScale, formatMB, formatMsec, formatReqSec, reshape, } from "@/util/benchmark_utils.ts"; import { BenchmarkChart } from "@/components/BenchmarkChart.tsx"; type ShowData = { dataFile: string; range: number[]; search: string }; interface Data { show: ShowData; rawData: BenchmarkRun[]; } // TODO(lucacasonato): add anchor points to headers export default function Benchmarks({ url, data }: PageProps<Data>) { const showAll = url.searchParams.has("all"); const typescriptBenches = ["check", "no_check", "bundle", "bundle_no_check"]; const benchData = reshape(data.rawData.slice(...data.show.range)); const dataRangeTitle = showAll ? [(ks: number[]) => ks[0], (ks: number[]) => ks.pop()] .map((f) => f([...data.rawData.keys()].slice(...data.show.range))) .filter((k) => k != null) .join("...") : ""; function IOMaybeNormalized({ normalized }: { normalized: boolean }) { return ( <div> <div class={tw`mt-8`}> <a href="#http-server-throughput" id="http-server-throughput"> <h5 class={tw`text-lg font-medium tracking-tight hover:underline`}> HTTP Server Throughput </h5> </a> <BenchmarkChart columns={normalized ? benchData.normalizedReqPerSec : benchData.reqPerSec} yLabel="1k req/sec" yTickFormat={formatReqSec} /> <p class={tw`mt-1`}> Tests HTTP server performance. 10 keep-alive connections do as many hello-world requests as possible. Bigger is better. </p> <ul class={tw`ml-8 list-disc my-2`}> <li> <SourceLink path="cli/bench/deno_tcp.ts" name="deno_tcp" />{" "} is a fake http server that doesn't parse HTTP. It is comparable to {" "} <SourceLink path="cli/bench/node_tcp.js" name="node_tcp" /> </li> <li> <SourceLink repo="deno_std" path="http/bench.ts" name="deno_http" />{" "} is a web server written in TypeScript. It is comparable to{" "} <SourceLink path="cli/bench/node_http.js" name="node_http" /> </li> <li class={tw`break-words`}> core_http_bin_ops and core_http_json_ops are two versions of a minimal fake HTTP server. It blindly reads and writes fixed HTTP packets. It is comparable to deno_tcp and node_tcp. This is a standalone executable that uses{" "} <a class={tw`link`} href="https://crates.io/crates/deno_core" > the deno rust crate </a> . The code is in{" "} <SourceLink path="core/examples/http_bench_json_ops.rs" name="http_bench_json_ops.rs" />{" "} and{" "} <SourceLink path="core/examples/http_bench_json_ops.js" name="http_bench_json_ops.js" />{" "} for http_bench_json_ops. </li> <li> <SourceLink path="test_util/src/test_server.rs" name="hyper" />{" "} is a Rust HTTP server and represents an upper bound. </li> </ul> </div> <div class={tw`mt-8`}> <a href="#http-latency" id="http-latency"> <h5 class={tw`text-lg font-medium tracking-tight hover:underline`}> HTTP Latency </h5> </a>{" "} <BenchmarkChart columns={normalized ? benchData.normalizedMaxLatency : benchData.maxLatency} yLabel="milliseconds" yTickFormat={formatMsec} /> <p class={tw`mt-1`}> Max latency during the same test used above for requests/second. Smaller is better. </p> </div> </div> ); } return ( <> <Head> <title> Benchmarks {dataRangeTitle ? `(${dataRangeTitle}) ` : " "}| Deno </title> </Head> <script src="https://cdn.jsdelivr.net/npm/apexcharts" /> <script id="data" type="application/json" dangerouslySetInnerHTML={{ __html: JSON.stringify(benchData) }} /> <script dangerouslySetInnerHTML={{ __html: ` const TimeScaleFactor = 10000; const data = JSON.parse(document.getElementById("data").text); const shortSha1List = data.sha1List.map((s) => s.slice(0, 6)); `, }} /> <div class={tw`bg-gray-50 min-h-full`}> <Header subtitle="Continuous Benchmarks" widerContent={true} /> <div class={tw`mb-12`}> <div class={tw`max-w-screen-md mx-auto px-4 sm:px-6 md:px-8 mt-8 pb-8`} > <img src="/images/deno_logo_4.gif" class={tw`mb-12 w-32 h-32`} /> <h4 class={tw`text-2xl font-bold tracking-tight`}>About</h4> <p class={tw`mt-4`}> As part of Deno's continuous integration and testing pipeline we measure the performance of certain key metrics of the runtime. You can view these benchmarks here. </p> <p class={tw`mt-4`}> You are currently viewing data for{" "} {showAll ? "all" : "the most recent"} commits to the{" "} <a href="https://github.com/denoland/deno">main</a>{" "} branch. You can also view{" "} <a class={tw`link`} href={!showAll ? "/benchmarks?all" : "/benchmarks"} > {!showAll ? "all" : "the most recent"} </a>{" "} commits. </p> <div class={tw`mt-12 pt-4`}> <h4 class={tw`text-2xl font-bold tracking-tight`}> Runtime Metrics </h4> <p class={tw`mt-2`}> In this section we measure various metrics of the following scripts: </p> <ul class={tw`ml-8 list-disc my-2`}> <li> <SourceLink path="cli/tests/testdata/003_relative_import.ts" name="cold_relative_import" /> </li> <li> <SourceLink path="cli/tests/testdata/text_decoder_perf.js" name="text_decoder" /> </li> <li> <SourceLink path="cli/tests/testdata/error_001.ts" name="error_001" /> </li> <li> <SourceLink path="cli/tests/testdata/002_hello.ts" name="cold_hello" /> </li> <li> <SourceLink path="cli/tests/testdata/workers/bench_round_robin.ts" name="workers_round_robin" /> </li> <li> <SourceLink path="cli/tests/testdata/003_relative_import.ts" name="relative_import" /> </li> <li> <SourceLink path="cli/tests/testdata/workers/bench_startup.ts" name="workers_startup" /> </li> <li> <SourceLink path="cli/tests/testdata/002_hello.ts" name="hello" /> </li> </ul> <div class={tw`mt-8`}> <a href="#execution-time" id="execution-time"> <h5 class={tw `text-lg font-medium tracking-tight hover:underline`} > Execution time </h5> </a> <BenchmarkChart columns={benchData.execTime.filter(({ name }) => !typescriptBenches.includes(name) )} yLabel="seconds" yTickFormat={formatLogScale} /> <p class={tw`mt-1`}> Log scale. This shows how much time total it takes to run a script. For deno to execute typescript, it must first compile it to JS. A warm startup is when deno has a cached JS output already, so it should be fast because it bypasses the TS compiler. A cold startup is when deno must compile from scratch. </p> </div> <div class={tw`mt-8`}> <a href="#thread-count" id="thread-count"> <h5 class={tw `text-lg font-medium tracking-tight hover:underline`} > Thread count </h5> </a> <BenchmarkChart columns={benchData.threadCount.filter(({ name }) => !typescriptBenches.includes(name) )} yLabel="threads" /> <p class={tw`mt-1`}> How many threads various programs use. Smaller is better. </p> </div> <div class={tw`mt-8`}> <a href="#syscall-count" id="syscall-count"> <h5 class={tw `text-lg font-medium tracking-tight hover:underline`} > Syscall count </h5> </a>{" "} <BenchmarkChart columns={benchData.syscallCount.filter(({ name }) => !typescriptBenches.includes(name) )} yLabel="syscalls" /> <p class={tw`mt-1`}> How many total syscalls are performed when executing a given script. Smaller is better. </p> </div> <div class={tw`mt-8`}> <a href="#max-memory-usage" id="max-memory-usage"> <h5 class={tw `text-lg font-medium tracking-tight hover:underline`} > Max memory usage </h5> </a>{" "} <BenchmarkChart columns={benchData.maxMemory.filter(({ name }) => !typescriptBenches.includes(name) )} yLabel="megabytes" yTickFormat={formatMB} /> <p class={tw`mt-1`}> Max memory usage during execution. Smaller is better. </p> </div> </div> <div class={tw`mt-20`}> <h4 class={tw`text-2xl font-bold tracking-tight`}> TypeScript Performance </h4> <div class={tw`mt-8`}> <a href="#type-checking" id="type-checking"> <h5 class={tw `text-lg font-medium tracking-tight hover:underline`} > Type Checking </h5> </a> <BenchmarkChart columns={benchData.execTime.filter(({ name }) => typescriptBenches.includes(name) )} yLabel="seconds" yTickFormat={formatLogScale} /> <p class={tw`mt-1`}> In both cases,{" "} <InlineCode>std/examples/chat/server_test.ts</InlineCode>{" "} is cached by Deno. The workload contains 20 unique TypeScript modules. With <em>check</em>{" "} a full TypeScript type check is performed, while{" "} <em>no_check</em> uses the <InlineCode>--no-check</InlineCode> {" "} flag to skip a full type check. <em>bundle</em>{" "} does a full type check and generates a single file output, while <em>bundle_no_check</em> uses the{" "} <InlineCode>--no-check</InlineCode>{" "} flag to skip a full type check. </p> </div> </div> <div class={tw`mt-20`}> <h4 class={tw`text-2xl font-bold tracking-tight`}>I/O</h4> <input type="checkbox" class={tw`hidden`} id="normalizedToggle" autoComplete="off" /> <label class={tw`mt-4 flex cursor-pointer`} htmlFor="normalizedToggle" > <span role="checkbox" tabIndex={0} class={tw `bg-gray-900 relative inline-block flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full transition-colors ease-in-out duration-200 focus:outline-none focus:shadow-outline`} > <span aria-hidden="true" class={tw `inline-block h-5 w-5 rounded-full bg-white shadow transform transition ease-in-out duration-200`} /> </span> <span class={tw`ml-2 text-gray-900`}> Show normalized benchmarks </span> </label> { /* The below 2 charts are controlled by :checked pseudo selector and general sibling combinator in app.css */ } <IOMaybeNormalized normalized={false} /> <IOMaybeNormalized normalized={true} /> </div> <div class={tw`mt-20`}> <h4 class={tw`text-2xl font-bold tracking-tight`}>Size</h4> <div class={tw`mt-8`}> <a href="#executable-size" id="executable-size"> <h5 class={tw `text-lg font-medium tracking-tight hover:underline`} > File sizes </h5> </a> <BenchmarkChart columns={benchData.binarySize} yLabel={"megabytes"} yTickFormat={formatMB} /> <p class={tw`mt-1`}> We track the size of various files here. "deno" is the release binary. </p> </div> <div class={tw`mt-8`}> <a href="#bundle-size" id="bundle-size"> <h5 class={tw `text-lg font-medium tracking-tight hover:underline`} > Bundle size </h5> </a>{" "} <BenchmarkChart columns={benchData.bundleSize} yLabel="kilobytes" yTickFormat={formatKB} /> <p class={tw`mt-1`}>Size of different bundled scripts.</p> <ul class={tw`ml-8 list-disc my-2`}> <li> <a class={tw`link`} href="/std/http/file_server.ts"> file_server </a> </li> <li> <a class={tw`link`} href="/std/examples/gist.ts">gist</a> </li> </ul> </div> <div class={tw`mt-8`}> <a href="#cargo-deps" id="cargo-deps"> <h5 class={tw `text-lg font-medium tracking-tight hover:underline`} > Cargo Dependencies </h5> </a>{" "} <BenchmarkChart columns={benchData.cargoDeps} yLabel="dependencies" /> </div> </div> <div class={tw`mt-20`}> <h4 class={tw`text-2xl font-bold tracking-tight`}> Language Server </h4> <div class={tw`mt-8`}> <BenchmarkChart columns={benchData.lspExecTime} yLabel="milliseconds" /> <p class={tw`mt-1`}> We track the performance of the Deno language server under different scenarios to help gauge the overall performance of the language server. </p> </div> </div> </div> </div> <Footer simple /> </div> </> ); } function SourceLink({ name, path, repo = "deno", }: { name: string; path: string; repo?: string; }) { return ( <a href={`https://github.com/denoland/${repo}/blob/main/${path}`} class={tw`link`} > {name} </a> ); } export const handler: Handlers<Data> = { async GET(req, { render }) { const url = new URL(req.url); const showAll = url.searchParams.has("all"); let show: ShowData = { dataFile: "recent.json", range: [], search: "", }; if (showAll) { show = { dataFile: "data.json", range: [], search: "all", }; } else { const range = decodeURIComponent(url.search) .split(/([?,]|\.{2,})/g) .filter(Boolean) .map(Number) .filter(Number.isInteger); if ([1, 2].includes(range.length)) { show = { dataFile: "data.json", range, search: range.join("..."), }; } } if (url.search && url.search !== "?" + show.search) { url.search = "?" + show.search; return Response.redirect(url); } const res = await fetch( `https://denoland.github.io/benchmark_data/${show.dataFile}`, ); return render!({ show, rawData: await res.json() }); }, };
the_stack
import * as React from 'react'; import { saveAs } from 'file-saver'; import { ContextMenuTrigger } from "react-contextmenu"; import 'purecss/build/pure-min.css'; import 'react-quill/dist/quill.snow.css'; import './scss/index.scss'; import './fonts/icofont.min.css'; import ResumeComponentFactory from './components/ResumeComponent'; import { assignIds, deepCopy, arraysEqual, createContainer } from './components/Helpers'; import ResumeTemplates from './components/templates/ResumeTemplates'; import { ResizableSidebarLayout, StaticSidebarLayout, DefaultLayout } from './components/controls/Layouts'; import Landing from './components/help/Landing'; import TopNavBar, { TopNavBarProps } from './components/controls/TopNavBar'; import ResumeHotKeys from './components/controls/ResumeHotkeys'; import Help from './components/help/Help'; import TopEditingBar, { EditingBarProps } from './components/controls/TopEditingBar'; import ResumeNodeTree from './components/utility/NodeTree'; import CssNode, { ReadonlyCssNode } from './components/utility/CssTree'; import PureMenu, { PureMenuLink, PureMenuItem } from './components/controls/menus/PureMenu'; import { Button } from './components/controls/Buttons'; import { SelectedNodeActions } from './components/controls/SelectedNodeActions'; import CssEditor, { makeCssEditorProps } from './components/utility/CssEditor'; import NodeTreeVisualizer from './components/utility/NodeTreeVisualizer'; import Tabs from './components/controls/Tabs'; import ResumeContextMenu from './components/controls/ResumeContextMenu'; import generateHtml from './components/utility/GenerateHtml'; import ComponentTypes from './components/schema/ComponentTypes'; import { IdType, NodeProperty, ResumeSaveData, ResumeNode, EditorMode, Globals } from './components/utility/Types'; import ObservableResumeNodeTree from './components/utility/ObservableResumeNodeTree'; import ResumeContext from './components/ResumeContext'; import ReactDOM from 'react-dom'; import { HighlightBox } from './components/utility/HighlightBox'; import SplitPane from 'react-split-pane'; /** These props are only used for testing */ export interface ResumeProps { mode?: EditorMode; nodes?: Array<ResumeNode>; css?: CssNode; rootCss?: CssNode; } export interface ResumeState { css: CssNode; rootCss: CssNode; childNodes: Array<ResumeNode>; mode: EditorMode; unsavedChanges: boolean; hlBox?: React.ReactNode; activeTemplate?: string; clipboard?: ResumeNode; // TODO: Remove??? hoverNode?: IdType; /** Are we editing the currently selected node */ isEditingSelected: boolean; selectedNode?: IdType; } class Resume extends React.Component<ResumeProps, ResumeState> { /** Stores IDs of nodes that were targeted by a single click */ private clicked = new Array<IdType>(); private nodes = new ObservableResumeNodeTree(); private css: CssNode; private rootCss: CssNode; private style = document.createElement("style"); private verticalPaneRef = React.createRef<SplitPane>(); private resumeRef = React.createRef<HTMLDivElement>(); private selectedRef = React.createRef<HTMLElement>(); constructor(props: ResumeProps) { super(props); // Custom CSS const head = document.getElementsByTagName("head")[0]; head.appendChild(this.style); this.css = props.css || new CssNode("Resume CSS", {}, "#resume"); this.rootCss = props.rootCss || new CssNode(":root", {}, ":root"); this.nodes.childNodes = props.nodes || []; this.state = { css: this.css, rootCss: this.rootCss, childNodes: props.nodes || [], isEditingSelected: false, mode: props.mode || "landing", unsavedChanges: false }; this.nodes.subscribe(this.onNodeUpdate.bind(this)); this.handleClick = this.handleClick.bind(this); this.print = this.print.bind(this); this.toggleMode = this.toggleMode.bind(this); /** Resume Nodes */ this.addCssClasses = this.addCssClasses.bind(this); this.addHtmlId = this.addHtmlId.bind(this); this.addChild = this.addChild.bind(this); this.updateData = this.updateData.bind(this); this.deleteSelected = this.deleteSelected.bind(this); this.updateSelected = this.updateSelected.bind(this); /** Templates and Styling **/ this.loadTemplate = this.loadTemplate.bind(this); this.renderSidebar = this.renderSidebar.bind(this); this.renderCssEditor = this.renderCssEditor.bind(this); /** Load & Save */ this.exportHtml = this.exportHtml.bind(this); this.loadData = this.loadData.bind(this); this.saveLocal = this.saveLocal.bind(this); this.saveFile = this.saveFile.bind(this); } /** Returns true if we are actively editing a resume */ get isEditing(): boolean { return this.state.mode === 'normal' || this.state.mode === 'help'; } get isPrinting(): boolean { return this.state.mode === 'printing'; } /** Retrieve the selected node **/ get selectedNode() { return this.state.selectedNode ? this.nodes.getNodeById(this.state.selectedNode) : undefined; } /** Return resume stylesheet */ get stylesheet() { return `${this.state.rootCss.stylesheet()}\n\n${this.state.css.stylesheet()}`; } /** * Update stylesheets * @param prevProps */ componentDidUpdate(_prevProps, prevState: ResumeState) { if (this.state.css !== prevState.css || this.state.rootCss !== prevState.css) { this.style.innerHTML = this.stylesheet; } // Reset "editing selected" when selected node changes if (this.state.selectedNode !== prevState.selectedNode) { if (this.state.isEditingSelected) { this.setState({ isEditingSelected: false }); } if (this.state.selectedNode && this.selectedRef.current) { this.setState({ hlBox: <HighlightBox className="resume-hl-box resume-hl-box-selected-node" elem={this.selectedRef.current} verticalSplitRef={this.verticalPaneRef} /> }) } else { this.setState({ hlBox: <></> }) } } } /** * Handles clicks on the resume * @param rightClick Whether or not the click was a right click */ private handleClick(rightClick = false) { // We want to select the node with the longest ID, i.e. // the deepest node that was clicked let selectedNode: IdType = []; this.clicked.forEach((id) => { if (id.length > selectedNode.length) { selectedNode = id; } }); // Reset list of clicked nodes this.clicked = new Array<IdType>(); if (!rightClick && arraysEqual(selectedNode, this.state.selectedNode)) { // Double click on a node ==> edit the node this.setState({ isEditingSelected: true }); } else { this.setState({ selectedNode: selectedNode }); } } /** * Switch into mode if not already. Otherwise, return to normal. * @param mode Mode to check */ toggleMode(mode: EditorMode = 'normal') { const newMode = (this.state.mode === mode) ? 'normal' : mode; this.setState({ mode: newMode }); } //#region Changing Templates loadTemplate(key = 'Integrity') { const template: ResumeSaveData = ResumeTemplates.templates[key]; this.setState({ activeTemplate: key}); this.loadData(template, 'changingTemplate'); }; private renderTemplateChanger() { const templateNames = Object.keys(ResumeTemplates.templates); return ( <div id="template-selector"> <PureMenu> {templateNames.map((key: string) => <PureMenuItem key={key} onClick={() => this.loadTemplate(key)}> <PureMenuLink>{key}</PureMenuLink> </PureMenuItem> )} </PureMenu> <Button onClick={() => this.toggleMode()}>Use this Template</Button> </div> ); } //#endregion //#region Creating/Editing Nodes addHtmlId(htmlId: string) { const currentNode = this.selectedNode as ResumeNode; if (currentNode) { let root = new CssNode(`#${htmlId}`, {}, `#${htmlId}`); let copyTree = this.css.findNode( ComponentTypes.cssName(currentNode.type)) as CssNode; if (copyTree) { root = copyTree.copySkeleton(`#${htmlId}`, `#${htmlId}`); } currentNode.htmlId = htmlId; this.css.addNode(root); this.setState({ css: this.css.deepCopy(), childNodes: this.nodes.childNodes }); } } addCssClasses(classes: string) { const currentNode = this.selectedNode as ResumeNode; if (currentNode) { currentNode.classNames = classes; this.setState({ childNodes: this.nodes.childNodes }); } } /** * Respond to ObservableResumeNodeTree's updates * @param nodes */ private onNodeUpdate(nodes: ResumeNodeTree) { this.setState({ childNodes: nodes.childNodes, unsavedChanges: true }); } /** * Add node as a child to the node identified by id * @param id Hierarchical id pointing to some node * @param node Node to be added */ addChild(id: IdType, node: ResumeNode) { this.nodes.addNestedChild(id, node); } deleteSelected() { const id = this.state.selectedNode as IdType; if (id) { this.nodes.deleteChild(id); this.setState({ selectedNode: undefined }); } } updateData(id: IdType, key: string, data: any) { this.nodes.updateChild(id, key, data); } updateSelected(key: string, data: NodeProperty) { const id = this.state.selectedNode as IdType; if (id) { this.nodes.updateChild(id, key, data); } } get clipboardProps() { const copyClipboard = () => { if (this.selectedNode) { this.setState({ clipboard: deepCopy(this.selectedNode) }); } }; return { copyClipboard: copyClipboard, cutClipboard: () => { if (this.selectedNode) { copyClipboard(); this.deleteSelected(); } }, pasteClipboard: this.state.clipboard as ResumeNode ? () => { // Default target: root let target: IdType = []; if (this.state.selectedNode) { target = this.state.selectedNode; // UUIDs will be added in the method below this.addChild(target, deepCopy(this.state.clipboard as ResumeNode)); } } : undefined } } get undoRedoProps() { return { undo: this.nodes.isUndoable ? this.nodes.undo : undefined, redo: this.nodes.isRedoable ? this.nodes.redo : undefined }; } get moveSelectedProps() { const id = this.state.selectedNode as IdType; const moveSelectedDownEnabled = id && !this.nodes.isLastSibling(id); const moveSelectedUpEnabled = id && id[id.length - 1] > 0; return { moveUp: moveSelectedUpEnabled ? () => this.setState({ selectedNode: this.nodes.moveUp(id) }) : undefined, moveDown: moveSelectedDownEnabled ? () => this.setState({ selectedNode: this.nodes.moveDown(id) }) : undefined }; } //#endregion //#region Serialization exportHtml() { // TODO: Make this user defineable const filename = 'resume.html'; let resumeHtml = this.resumeRef.current ? this.resumeRef.current.outerHTML : ''; var blob = new Blob( [generateHtml(this.stylesheet, resumeHtml)], { type: "text/html;charset=utf-8" } ); saveAs(blob, filename); } loadData(data: object, mode: EditorMode = 'normal') { let savedData = data as ResumeSaveData; this.nodes.childNodes = assignIds(savedData.childNodes); this.css = CssNode.load(savedData.builtinCss); this.rootCss = CssNode.load(savedData.rootCss); this.setState({ css: this.css.deepCopy(), mode: mode, rootCss: this.rootCss.deepCopy() }) } loadLocal() { const savedData = localStorage.getItem(Globals.localStorageKey); if (savedData) { try { this.loadData(JSON.parse(savedData)); } catch { // TODO: Show an error message console.log("Nope, that didn't work."); } } } dump(): ResumeSaveData { return { childNodes: this.state.childNodes, builtinCss: this.css.dump(), rootCss: this.rootCss.dump() }; } saveLocal() { this.setState({ unsavedChanges: false }); localStorage.setItem('experiencer', JSON.stringify(this.dump())); } // Save data to an external file saveFile(filename: string) { saveAs(new Blob([JSON.stringify(this.dump())], { type: "text/plain;charset=utf-8" }), filename); } //#endregion //#region Helper Component Props private get selectedNodeActions() : SelectedNodeActions { return { ...this.clipboardProps, ...this.moveSelectedProps, delete: this.deleteSelected, } } private get topMenuProps(): TopNavBarProps { let props = { exportHtml: this.exportHtml, isEditing: this.isEditing, loadData: this.loadData, mode: this.state.mode, new: this.loadTemplate, print: this.print, saveLocal: this.saveLocal, saveFile: this.saveFile, toggleHelp: () => this.toggleMode('help'), toggleLanding: () => this.setState({ mode: 'landing' }) } return props; } private get editingBarProps() : EditingBarProps { return { ...this.undoRedoProps, ...this.selectedNodeActions, selectedNodeId: this.state.selectedNode, selectedNode: this.selectedNode, addHtmlId: this.addHtmlId, addCssClasses: this.addCssClasses, addChild: this.addChild, unselect: () => this.setState({ selectedNode: undefined }), updateSelected: this.updateSelected, saveLocal: this.state.unsavedChanges ? this.saveLocal : undefined } } private get resumeHotKeysProps() { return { ...this.selectedNodeActions, ...this.undoRedoProps, togglePrintMode: () => this.toggleMode('printing'), reset: () => { this.setState({ mode: 'normal', selectedNode: undefined }); } } } print() { requestAnimationFrame(() => { const prevState = { ...this.state }; this.setState({ selectedNode: undefined, mode: 'printing' }); window.print(); this.setState(prevState); }); } //#endregion private renderSidebar() { let CssEditor = this.renderCssEditor; return <Tabs> <NodeTreeVisualizer key="Tree" childNodes={this.state.childNodes} selectNode={(id) => this.setState({ selectedNode: id })} selectedNode={this.state.selectedNode} /> <CssEditor key="CSS" /> <div key="Raw CSS"> <pre> <code> {this.stylesheet} </code> </pre> </div> </Tabs> } /** Gather all variable declarations in :root */ makeCssEditorVarSuggestions(): Array<string> { let suggestions = new Array<string>(); for (let k of this.rootCss.properties.keys()) { if (k.slice(0, 2) === '--') { suggestions.push(`var(${k})`); } } return suggestions; } private renderCssEditor() { const cssUpdateCallback = () => this.setState({ css: this.css.deepCopy() }); const rootCssUpdateCallback = () => this.setState({ rootCss: this.rootCss.deepCopy() }); if (this.selectedNode) { let generalCssEditor = <></> let specificCssEditor = <></> const rootNode = this.state.css.findNode( ComponentTypes.cssName(this.selectedNode.type)) as CssNode; if (rootNode) { generalCssEditor = <CssEditor cssNode={new ReadonlyCssNode(rootNode)} isOpen={true} verticalSplitRef={this.verticalPaneRef} {...makeCssEditorProps(this.css, cssUpdateCallback)} /> } if (this.selectedNode.htmlId && this.state.css.findNode([`#${this.selectedNode.htmlId}`])) { const specificRoot = this.state.css.findNode([`#${this.selectedNode.htmlId}`]) as CssNode; specificCssEditor = <CssEditor cssNode={new ReadonlyCssNode(specificRoot)} isOpen={true} verticalSplitRef={this.verticalPaneRef} {...makeCssEditorProps(this.css, cssUpdateCallback)} /> } return <> {specificCssEditor} {generalCssEditor} </> } return <> <CssEditor cssNode={new ReadonlyCssNode(this.state.rootCss)} isOpen={true} verticalSplitRef={this.verticalPaneRef} {...makeCssEditorProps(this.rootCss, rootCssUpdateCallback)} /> <CssEditor cssNode={new ReadonlyCssNode(this.state.css)} isOpen={true} verticalSplitRef={this.verticalPaneRef} varSuggestions={this.makeCssEditorVarSuggestions()} {...makeCssEditorProps(this.css, cssUpdateCallback)} /> </> } render() { const hlBoxContainer = createContainer("hl-box-container"); const resume = ( <> <ContextMenuTrigger attributes={{ id: "resume-container" }} id="resume-menu"> <div id="resume" ref={this.resumeRef} onClick={() => this.handleClick()} onContextMenu={() => this.handleClick(true)}> <ResumeHotKeys {...this.resumeHotKeysProps} /> {this.state.childNodes.map((elem, idx, arr) => { const uniqueId = elem.uuid; const props = { ...elem, updateResumeData: this.updateData, index: idx, numSiblings: arr.length }; return ( <ResumeContext.Provider key={uniqueId} value={{ isEditingSelected: this.state.isEditingSelected, selectedUuid: this.selectedNode ? this.selectedNode.uuid : undefined, updateClicked: (id: IdType) => { this.clicked.push(id) }, updateSelectedRef: (ref: React.RefObject<any>) => { this.selectedRef = ref } }}> <ResumeComponentFactory {...props} /> </ResumeContext.Provider> ); })} </div> <ResumeContextMenu nodes={this.nodes} currentId={this.state.selectedNode} editSelected={() => this.setState({ isEditingSelected: true })} updateSelected={this.updateSelected} selectNode={(id) => this.setState({ selectedNode: id })} /> </ContextMenuTrigger> {ReactDOM.createPortal(this.state.hlBox, hlBoxContainer)} </> ); const editingTop = this.isPrinting ? <></> : ( <header id="app-header" className="no-print"> <TopNavBar {...this.topMenuProps} /> {this.isEditing ? <TopEditingBar {...this.editingBarProps} /> : <></>} </header> ); // Render the final layout based on editor mode switch (this.state.mode) { case 'help': return <ResizableSidebarLayout topNav={editingTop} main={resume} sidebar={<Help close={() => this.toggleMode()} />} /> case 'changingTemplate': return <StaticSidebarLayout topNav={editingTop} main={resume} sidebar={this.renderTemplateChanger()} /> case 'landing': return <DefaultLayout topNav={editingTop} main={<Landing loadLocal={() => { this.loadLocal() }} new={this.loadTemplate} loadData={this.loadData} /> } /> case 'printing': return resume; default: return <ResizableSidebarLayout ref={this.verticalPaneRef} topNav={editingTop} main={resume} isPrinting={this.isPrinting} sidebar={this.renderSidebar()} /> } } } export default Resume;
the_stack
import { createMachine, Interpreter, assign, TransitionsConfig } from "xstate"; import { EVENTS, GameEvent } from "../events"; import { processEvent } from "./processEvent"; import { Context as AuthContext } from "features/auth/lib/authMachine"; import { metamask } from "../../../lib/blockchain/metamask"; import { GameState } from "../types/game"; import { loadSession, MintedAt } from "../actions/loadSession"; import { INITIAL_FARM, EMPTY } from "./constants"; import { autosave } from "../actions/autosave"; import { LimitedItemName } from "../types/craftables"; import { sync } from "../actions/sync"; import { getOnChainState } from "../actions/onchain"; import { ErrorCode, ERRORS } from "lib/errors"; import { updateGame } from "./transforms"; import { getFingerPrint } from "./botDetection"; import { SkillName } from "../types/skills"; import { levelUp } from "../actions/levelUp"; import { reset } from "features/farming/hud/actions/reset"; export type PastAction = GameEvent & { createdAt: Date; }; export interface Context { state: GameState; onChain: GameState; actions: PastAction[]; offset: number; owner?: string; sessionId?: string; errorCode?: keyof typeof ERRORS; fingerprint?: string; itemsMintedAt?: MintedAt; } type MintEvent = { type: "MINT"; item: LimitedItemName; captcha: string; }; type LevelUpEvent = { type: "LEVEL_UP"; skill: SkillName; }; type WithdrawEvent = { type: "WITHDRAW"; sfl: number; ids: number[]; amounts: string[]; captcha: string; }; type SyncEvent = { captcha: string; type: "SYNC"; }; export type BlockchainEvent = | { type: "SAVE"; } | SyncEvent | { type: "REFRESH"; } | { type: "EXPIRED"; } | { type: "CONTINUE"; } | { type: "RESET"; } | WithdrawEvent | GameEvent | MintEvent | LevelUpEvent; // For each game event, convert it to an XState event + handler const GAME_EVENT_HANDLERS: TransitionsConfig<Context, BlockchainEvent> = Object.keys(EVENTS).reduce( (events, eventName) => ({ ...events, [eventName]: { actions: assign((context: Context, event: GameEvent) => ({ state: processEvent({ state: context.state as GameState, action: event, onChain: context.onChain as GameState, }) as GameState, actions: [ ...context.actions, { ...event, createdAt: new Date(), }, ], })), }, }), {} ); export type BlockchainState = { value: | "loading" | "playing" | "readonly" | "autosaving" | "syncing" | "synced" | "levelling" | "error" | "resetting"; context: Context; }; export type StateKeys = keyof Omit<BlockchainState, "context">; export type StateValues = BlockchainState[StateKeys]; export type MachineInterpreter = Interpreter< Context, any, BlockchainEvent, BlockchainState >; type Options = AuthContext & { isNoob: boolean }; // Hashed eth 0 value export const INITIAL_SESSION = "0x0000000000000000000000000000000000000000000000000000000000000000"; const isVisiting = () => window.location.href.includes("visit"); export function startGame(authContext: Options) { const handleInitialState = () => { if (isVisiting()) { return "readonly"; } return "playing"; }; return createMachine<Context, BlockchainEvent, BlockchainState>( { id: "gameMachine", initial: "loading", context: { actions: [], state: EMPTY, onChain: EMPTY, sessionId: INITIAL_SESSION, offset: 0, }, states: { loading: { invoke: { src: async () => { const farmId = authContext.farmId as number; const { game: onChain, owner } = await getOnChainState({ farmAddress: authContext.address as string, id: farmId, }); // Visit farm if (isVisiting()) { onChain.id = farmId; return { state: onChain, onChain, owner }; } // Get sessionId const sessionId = farmId && (await metamask.getSessionManager().getSessionId(farmId)); // Load the farm session if (sessionId) { const fingerprint = await getFingerPrint(); const response = await loadSession({ farmId, sessionId, token: authContext.rawToken as string, }); if (!response) { throw new Error("NO_FARM"); } const { game, offset, whitelistedAt, itemsMintedAt } = response; // add farm address game.farmAddress = authContext.address; return { state: { ...game, id: Number(authContext.farmId), }, sessionId, offset, whitelistedAt, fingerprint, itemsMintedAt, onChain, owner, }; } return { state: INITIAL_FARM }; }, onDone: [ { target: handleInitialState(), actions: assign({ state: (_, event) => event.data.state, onChain: (_, event) => event.data.onChain, owner: (_, event) => event.data.owner, offset: (_, event) => event.data.offset, sessionId: (_, event) => event.data.sessionId, fingerprint: (_, event) => event.data.fingerprint, itemsMintedAt: (_, event) => event.data.itemsMintedAt, }), }, ], onError: { target: "error", actions: "assignErrorMessage", }, }, }, playing: { invoke: { /** * An in game loop that checks if Blockchain becomes out of sync * It is a rare event but it saves a user from making too much progress that would not be synced */ src: (context) => (cb) => { const interval = setInterval(async () => { const sessionID = await metamask .getSessionManager() ?.getSessionId(authContext?.farmId as number); if (sessionID !== context.sessionId) { cb("EXPIRED"); } }, 1000 * 20); return () => { clearInterval(interval); }; }, onError: { target: "error", actions: "assignErrorMessage", }, }, on: { ...GAME_EVENT_HANDLERS, SAVE: { target: "autosaving", }, SYNC: { target: "syncing", }, LEVEL_UP: { target: "levelling", }, EXPIRED: { target: "error", actions: assign((_) => ({ errorCode: ERRORS.SESSION_EXPIRED as ErrorCode, })), }, RESET: { target: "resetting", }, }, }, autosaving: { on: { ...GAME_EVENT_HANDLERS, }, invoke: { src: async (context, event) => { const saveAt = (event as any)?.data?.saveAt || new Date(); if (context.actions.length === 0) { return { verified: true, saveAt, farm: context.state }; } const { verified, farm } = await autosave({ farmId: Number(authContext.farmId), sessionId: context.sessionId as string, actions: context.actions, token: authContext.rawToken as string, offset: context.offset, fingerprint: context.fingerprint as string, }); // This gives the UI time to indicate that a save is taking place both when clicking save // and when autosaving await new Promise((res) => setTimeout(res, 1000)); return { saveAt, verified, farm, }; }, onDone: [ { target: "playing", actions: assign((context: Context, event) => { // Actions that occured since the server request const recentActions = context.actions.filter( (action) => action.createdAt.getTime() > event.data.saveAt.getTime() ); return { actions: recentActions, state: updateGame(event.data.farm, context.state), }; }), }, ], onError: { target: "error", actions: "assignErrorMessage", }, }, }, // minting syncing: { invoke: { src: async (context, event) => { // Autosave just in case if (context.actions.length > 0) { await autosave({ farmId: Number(authContext.farmId), sessionId: context.sessionId as string, actions: context.actions, token: authContext.rawToken as string, offset: context.offset, fingerprint: context.fingerprint as string, }); } const { sessionId } = await sync({ farmId: Number(authContext.farmId), sessionId: context.sessionId as string, token: authContext.rawToken as string, captcha: (event as SyncEvent).captcha, }); return { sessionId: sessionId, }; }, onDone: { target: "synced", actions: assign((_, event) => ({ sessionId: event.data.sessionId, actions: [], })), }, onError: [ { target: "playing", cond: (_, event: any) => event.data.message === ERRORS.REJECTED_TRANSACTION, actions: assign((_) => ({ actions: [], })), }, { target: "error", actions: "assignErrorMessage", }, ], }, }, levelling: { invoke: { src: async (context, event) => { // Autosave just in case if (context.actions.length > 0) { await autosave({ farmId: Number(authContext.farmId), sessionId: context.sessionId as string, actions: context.actions, token: authContext.rawToken as string, offset: context.offset, fingerprint: context.fingerprint as string, }); } const { farm } = await levelUp({ farmId: Number(authContext.farmId), sessionId: context.sessionId as string, token: authContext.rawToken as string, fingerprint: context.fingerprint as string, skill: (event as LevelUpEvent).skill, }); return { farm, }; }, onDone: [ { target: "playing", actions: assign((_, event) => ({ // Remove events actions: [], // Update immediately with state from server state: event.data.farm, })), }, ], onError: { target: "error", actions: "assignErrorMessage", }, }, }, resetting: { invoke: { src: async (context, event) => { // Autosave just in case const { success } = await reset({ farmId: Number(authContext.farmId), token: authContext.rawToken as string, fingerprint: context.fingerprint as string, }); return { success, }; }, onDone: [ { target: "loading", }, ], onError: { target: "error", actions: "assignErrorMessage", }, }, }, readonly: {}, error: { on: { CONTINUE: "playing", }, }, synced: { on: { REFRESH: { target: "loading", }, }, }, // withdrawn }, }, { actions: { assignErrorMessage: assign<Context, any>({ errorCode: (_context, event) => event.data.message, actions: [], }), }, } ); }
the_stack
import { SENSITIVE_STRING } from "@aws-sdk/smithy-client"; import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; export enum ChannelMembershipType { DEFAULT = "DEFAULT", HIDDEN = "HIDDEN", } /** * <p>Summary of the membership details of an <code>AppInstanceUser</code>.</p> */ export interface AppInstanceUserMembershipSummary { /** * <p>The type of <code>ChannelMembership</code>.</p> */ Type?: ChannelMembershipType | string; /** * <p>The time at which a message was last read.</p> */ ReadMarkerTimestamp?: Date; } export namespace AppInstanceUserMembershipSummary { /** * @internal */ export const filterSensitiveLog = (obj: AppInstanceUserMembershipSummary): any => ({ ...obj, }); } export enum ErrorCode { AccessDenied = "AccessDenied", BadRequest = "BadRequest", Conflict = "Conflict", Forbidden = "Forbidden", NotFound = "NotFound", PhoneNumberAssociationsExist = "PhoneNumberAssociationsExist", PreconditionFailed = "PreconditionFailed", ResourceLimitExceeded = "ResourceLimitExceeded", ServiceFailure = "ServiceFailure", ServiceUnavailable = "ServiceUnavailable", Throttled = "Throttled", Throttling = "Throttling", Unauthorized = "Unauthorized", Unprocessable = "Unprocessable", VoiceConnectorGroupAssociationsExist = "VoiceConnectorGroupAssociationsExist", } /** * <p>The input parameters don't match the service's restrictions.</p> */ export interface BadRequestException extends __SmithyException, $MetadataBearer { name: "BadRequestException"; $fault: "client"; Code?: ErrorCode | string; Message?: string; } export namespace BadRequestException { /** * @internal */ export const filterSensitiveLog = (obj: BadRequestException): any => ({ ...obj, }); } /** * <p>The details of a user.</p> */ export interface Identity { /** * <p>The ARN in an Identity.</p> */ Arn?: string; /** * <p>The name in an Identity.</p> */ Name?: string; } export namespace Identity { /** * @internal */ export const filterSensitiveLog = (obj: Identity): any => ({ ...obj, ...(obj.Name && { Name: SENSITIVE_STRING }), }); } /** * <p>The membership information, including member ARNs, the channel ARN, and membership * types.</p> */ export interface BatchChannelMemberships { /** * <p>The identifier of the member who invited another member.</p> */ InvitedBy?: Identity; /** * <p>The membership types set for the channel users.</p> */ Type?: ChannelMembershipType | string; /** * <p>The users successfully added to the request.</p> */ Members?: Identity[]; /** * <p>The ARN of the channel to which you're adding users.</p> */ ChannelArn?: string; } export namespace BatchChannelMemberships { /** * @internal */ export const filterSensitiveLog = (obj: BatchChannelMemberships): any => ({ ...obj, ...(obj.InvitedBy && { InvitedBy: Identity.filterSensitiveLog(obj.InvitedBy) }), ...(obj.Members && { Members: obj.Members.map((item) => Identity.filterSensitiveLog(item)) }), }); } export interface BatchCreateChannelMembershipRequest { /** * <p>The ARN of the channel to which you're adding users.</p> */ ChannelArn: string | undefined; /** * <p>The membership type of a user, <code>DEFAULT</code> or <code>HIDDEN</code>. Default * members are always returned as part of <code>ListChannelMemberships</code>. Hidden members * are only returned if the type filter in <code>ListChannelMemberships</code> equals * <code>HIDDEN</code>. Otherwise hidden members are not returned. This is only supported * by moderators.</p> */ Type?: ChannelMembershipType | string; /** * <p>The ARNs of the members you want to add to the channel.</p> */ MemberArns: string[] | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace BatchCreateChannelMembershipRequest { /** * @internal */ export const filterSensitiveLog = (obj: BatchCreateChannelMembershipRequest): any => ({ ...obj, }); } /** * <p>A list of failed member ARNs, error codes, and error messages.</p> */ export interface BatchCreateChannelMembershipError { /** * <p>The ARN of the member that the service couldn't add.</p> */ MemberArn?: string; /** * <p>The error code.</p> */ ErrorCode?: ErrorCode | string; /** * <p>The error message.</p> */ ErrorMessage?: string; } export namespace BatchCreateChannelMembershipError { /** * @internal */ export const filterSensitiveLog = (obj: BatchCreateChannelMembershipError): any => ({ ...obj, }); } export interface BatchCreateChannelMembershipResponse { /** * <p>The list of channel memberships in the response.</p> */ BatchChannelMemberships?: BatchChannelMemberships; /** * <p>If the action fails for one or more of the memberships in the request, a list of the * memberships is returned, along with error codes and error messages.</p> */ Errors?: BatchCreateChannelMembershipError[]; } export namespace BatchCreateChannelMembershipResponse { /** * @internal */ export const filterSensitiveLog = (obj: BatchCreateChannelMembershipResponse): any => ({ ...obj, ...(obj.BatchChannelMemberships && { BatchChannelMemberships: BatchChannelMemberships.filterSensitiveLog(obj.BatchChannelMemberships), }), }); } /** * <p>The client is permanently forbidden from making the request.</p> */ export interface ForbiddenException extends __SmithyException, $MetadataBearer { name: "ForbiddenException"; $fault: "client"; Code?: ErrorCode | string; Message?: string; } export namespace ForbiddenException { /** * @internal */ export const filterSensitiveLog = (obj: ForbiddenException): any => ({ ...obj, }); } /** * <p>The service encountered an unexpected error.</p> */ export interface ServiceFailureException extends __SmithyException, $MetadataBearer { name: "ServiceFailureException"; $fault: "server"; Code?: ErrorCode | string; Message?: string; } export namespace ServiceFailureException { /** * @internal */ export const filterSensitiveLog = (obj: ServiceFailureException): any => ({ ...obj, }); } /** * <p>The service is currently unavailable.</p> */ export interface ServiceUnavailableException extends __SmithyException, $MetadataBearer { name: "ServiceUnavailableException"; $fault: "server"; Code?: ErrorCode | string; Message?: string; } export namespace ServiceUnavailableException { /** * @internal */ export const filterSensitiveLog = (obj: ServiceUnavailableException): any => ({ ...obj, }); } /** * <p>The client exceeded its request rate limit.</p> */ export interface ThrottledClientException extends __SmithyException, $MetadataBearer { name: "ThrottledClientException"; $fault: "client"; Code?: ErrorCode | string; Message?: string; } export namespace ThrottledClientException { /** * @internal */ export const filterSensitiveLog = (obj: ThrottledClientException): any => ({ ...obj, }); } /** * <p>The client is not currently authorized to make the request.</p> */ export interface UnauthorizedClientException extends __SmithyException, $MetadataBearer { name: "UnauthorizedClientException"; $fault: "client"; Code?: ErrorCode | string; Message?: string; } export namespace UnauthorizedClientException { /** * @internal */ export const filterSensitiveLog = (obj: UnauthorizedClientException): any => ({ ...obj, }); } export enum ChannelMode { RESTRICTED = "RESTRICTED", UNRESTRICTED = "UNRESTRICTED", } export enum ChannelPrivacy { PRIVATE = "PRIVATE", PUBLIC = "PUBLIC", } /** * <p>The details of a channel.</p> */ export interface Channel { /** * <p>The name of a channel.</p> */ Name?: string; /** * <p>The ARN of a channel.</p> */ ChannelArn?: string; /** * <p>The mode of the channel.</p> */ Mode?: ChannelMode | string; /** * <p>The channel's privacy setting.</p> */ Privacy?: ChannelPrivacy | string; /** * <p>The channel's metadata.</p> */ Metadata?: string; /** * <p>The <code>AppInstanceUser</code> who created the channel.</p> */ CreatedBy?: Identity; /** * <p>The time at which the <code>AppInstanceUser</code> created the channel.</p> */ CreatedTimestamp?: Date; /** * <p>The time at which a member sent the last message in the channel.</p> */ LastMessageTimestamp?: Date; /** * <p>The time at which a channel was last updated.</p> */ LastUpdatedTimestamp?: Date; } export namespace Channel { /** * @internal */ export const filterSensitiveLog = (obj: Channel): any => ({ ...obj, ...(obj.Name && { Name: SENSITIVE_STRING }), ...(obj.Metadata && { Metadata: SENSITIVE_STRING }), ...(obj.CreatedBy && { CreatedBy: Identity.filterSensitiveLog(obj.CreatedBy) }), }); } /** * <p>The details of a channel ban.</p> */ export interface ChannelBan { /** * <p>The member being banned from the channel.</p> */ Member?: Identity; /** * <p>The ARN of the channel from which a member is being banned.</p> */ ChannelArn?: string; /** * <p>The time at which the ban was created.</p> */ CreatedTimestamp?: Date; /** * <p>The <code>AppInstanceUser</code> who created the ban.</p> */ CreatedBy?: Identity; } export namespace ChannelBan { /** * @internal */ export const filterSensitiveLog = (obj: ChannelBan): any => ({ ...obj, ...(obj.Member && { Member: Identity.filterSensitiveLog(obj.Member) }), ...(obj.CreatedBy && { CreatedBy: Identity.filterSensitiveLog(obj.CreatedBy) }), }); } /** * <p>Summary of the details of a <code>ChannelBan</code>.</p> */ export interface ChannelBanSummary { /** * <p>The member being banned from a channel.</p> */ Member?: Identity; } export namespace ChannelBanSummary { /** * @internal */ export const filterSensitiveLog = (obj: ChannelBanSummary): any => ({ ...obj, ...(obj.Member && { Member: Identity.filterSensitiveLog(obj.Member) }), }); } /** * <p>The details of a channel member.</p> */ export interface ChannelMembership { /** * <p>The identifier of the member who invited another member.</p> */ InvitedBy?: Identity; /** * <p>The membership type set for the channel member.</p> */ Type?: ChannelMembershipType | string; /** * <p>The data of the channel member.</p> */ Member?: Identity; /** * <p>The ARN of the member's channel.</p> */ ChannelArn?: string; /** * <p>The time at which the channel membership was created.</p> */ CreatedTimestamp?: Date; /** * <p>The time at which a channel membership was last updated.</p> */ LastUpdatedTimestamp?: Date; } export namespace ChannelMembership { /** * @internal */ export const filterSensitiveLog = (obj: ChannelMembership): any => ({ ...obj, ...(obj.InvitedBy && { InvitedBy: Identity.filterSensitiveLog(obj.InvitedBy) }), ...(obj.Member && { Member: Identity.filterSensitiveLog(obj.Member) }), }); } /** * <p>Summary of the details of a <code>Channel</code>.</p> */ export interface ChannelSummary { /** * <p>The name of the channel.</p> */ Name?: string; /** * <p>The ARN of the channel.</p> */ ChannelArn?: string; /** * <p>The mode of the channel.</p> */ Mode?: ChannelMode | string; /** * <p>The privacy setting of the channel.</p> */ Privacy?: ChannelPrivacy | string; /** * <p>The metadata of the channel.</p> */ Metadata?: string; /** * <p>The time at which the last message in a channel was sent.</p> */ LastMessageTimestamp?: Date; } export namespace ChannelSummary { /** * @internal */ export const filterSensitiveLog = (obj: ChannelSummary): any => ({ ...obj, ...(obj.Name && { Name: SENSITIVE_STRING }), ...(obj.Metadata && { Metadata: SENSITIVE_STRING }), }); } /** * <p>Summary of the channel membership details of an <code>AppInstanceUser</code>.</p> */ export interface ChannelMembershipForAppInstanceUserSummary { /** * <p>Returns the channel data for an <code>AppInstance</code>.</p> */ ChannelSummary?: ChannelSummary; /** * <p>Returns the channel membership data for an <code>AppInstance</code>.</p> */ AppInstanceUserMembershipSummary?: AppInstanceUserMembershipSummary; } export namespace ChannelMembershipForAppInstanceUserSummary { /** * @internal */ export const filterSensitiveLog = (obj: ChannelMembershipForAppInstanceUserSummary): any => ({ ...obj, ...(obj.ChannelSummary && { ChannelSummary: ChannelSummary.filterSensitiveLog(obj.ChannelSummary) }), }); } /** * <p>Summary of the details of a <code>ChannelMembership</code>.</p> */ export interface ChannelMembershipSummary { /** * <p>A member's summary data.</p> */ Member?: Identity; } export namespace ChannelMembershipSummary { /** * @internal */ export const filterSensitiveLog = (obj: ChannelMembershipSummary): any => ({ ...obj, ...(obj.Member && { Member: Identity.filterSensitiveLog(obj.Member) }), }); } export enum ChannelMessagePersistenceType { NON_PERSISTENT = "NON_PERSISTENT", PERSISTENT = "PERSISTENT", } export enum ChannelMessageType { CONTROL = "CONTROL", STANDARD = "STANDARD", } /** * <p>The details of a message in a channel.</p> */ export interface ChannelMessage { /** * <p>The ARN of the channel.</p> */ ChannelArn?: string; /** * <p>The ID of a message.</p> */ MessageId?: string; /** * <p>The message content.</p> */ Content?: string; /** * <p>The message metadata.</p> */ Metadata?: string; /** * <p>The message type.</p> */ Type?: ChannelMessageType | string; /** * <p>The time at which the message was created.</p> */ CreatedTimestamp?: Date; /** * <p>The time at which a message was edited.</p> */ LastEditedTimestamp?: Date; /** * <p>The time at which a message was updated.</p> */ LastUpdatedTimestamp?: Date; /** * <p>The message sender.</p> */ Sender?: Identity; /** * <p>Hides the content of a message.</p> */ Redacted?: boolean; /** * <p>The persistence setting for a channel message.</p> */ Persistence?: ChannelMessagePersistenceType | string; } export namespace ChannelMessage { /** * @internal */ export const filterSensitiveLog = (obj: ChannelMessage): any => ({ ...obj, ...(obj.Content && { Content: SENSITIVE_STRING }), ...(obj.Metadata && { Metadata: SENSITIVE_STRING }), ...(obj.Sender && { Sender: Identity.filterSensitiveLog(obj.Sender) }), }); } /** * <p>Summary of the messages in a <code>Channel</code>.</p> */ export interface ChannelMessageSummary { /** * <p>The ID of the message.</p> */ MessageId?: string; /** * <p>The content of the message.</p> */ Content?: string; /** * <p>The metadata of the message.</p> */ Metadata?: string; /** * <p>The type of message.</p> */ Type?: ChannelMessageType | string; /** * <p>The time at which the message summary was created.</p> */ CreatedTimestamp?: Date; /** * <p>The time at which a message was last updated.</p> */ LastUpdatedTimestamp?: Date; /** * <p>The time at which a message was last edited.</p> */ LastEditedTimestamp?: Date; /** * <p>The message sender.</p> */ Sender?: Identity; /** * <p>Indicates whether a message was redacted.</p> */ Redacted?: boolean; } export namespace ChannelMessageSummary { /** * @internal */ export const filterSensitiveLog = (obj: ChannelMessageSummary): any => ({ ...obj, ...(obj.Content && { Content: SENSITIVE_STRING }), ...(obj.Metadata && { Metadata: SENSITIVE_STRING }), ...(obj.Sender && { Sender: Identity.filterSensitiveLog(obj.Sender) }), }); } /** * <p>Summary of the details of a moderated channel.</p> */ export interface ChannelModeratedByAppInstanceUserSummary { /** * <p>Summary of the details of a <code>Channel</code>.</p> */ ChannelSummary?: ChannelSummary; } export namespace ChannelModeratedByAppInstanceUserSummary { /** * @internal */ export const filterSensitiveLog = (obj: ChannelModeratedByAppInstanceUserSummary): any => ({ ...obj, ...(obj.ChannelSummary && { ChannelSummary: ChannelSummary.filterSensitiveLog(obj.ChannelSummary) }), }); } /** * <p>The details of a channel moderator.</p> */ export interface ChannelModerator { /** * <p>The moderator's data.</p> */ Moderator?: Identity; /** * <p>The ARN of the moderator's channel.</p> */ ChannelArn?: string; /** * <p>The time at which the moderator was created.</p> */ CreatedTimestamp?: Date; /** * <p>The <code>AppInstanceUser</code> who created the moderator.</p> */ CreatedBy?: Identity; } export namespace ChannelModerator { /** * @internal */ export const filterSensitiveLog = (obj: ChannelModerator): any => ({ ...obj, ...(obj.Moderator && { Moderator: Identity.filterSensitiveLog(obj.Moderator) }), ...(obj.CreatedBy && { CreatedBy: Identity.filterSensitiveLog(obj.CreatedBy) }), }); } /** * <p>Summary of the details of a <code>ChannelModerator</code>.</p> */ export interface ChannelModeratorSummary { /** * <p>The data for a moderator.</p> */ Moderator?: Identity; } export namespace ChannelModeratorSummary { /** * @internal */ export const filterSensitiveLog = (obj: ChannelModeratorSummary): any => ({ ...obj, ...(obj.Moderator && { Moderator: Identity.filterSensitiveLog(obj.Moderator) }), }); } /** * <p>The request could not be processed because of conflict in the current state of the * resource.</p> */ export interface ConflictException extends __SmithyException, $MetadataBearer { name: "ConflictException"; $fault: "client"; Code?: ErrorCode | string; Message?: string; } export namespace ConflictException { /** * @internal */ export const filterSensitiveLog = (obj: ConflictException): any => ({ ...obj, }); } /** * <p>Describes a tag applied to a resource.</p> */ export interface Tag { /** * <p>The key of the tag.</p> */ Key: string | undefined; /** * <p>The value of the tag.</p> */ Value: string | undefined; } export namespace Tag { /** * @internal */ export const filterSensitiveLog = (obj: Tag): any => ({ ...obj, ...(obj.Key && { Key: SENSITIVE_STRING }), ...(obj.Value && { Value: SENSITIVE_STRING }), }); } export interface CreateChannelRequest { /** * <p>The ARN of the channel request.</p> */ AppInstanceArn: string | undefined; /** * <p>The name of the channel.</p> */ Name: string | undefined; /** * <p>The channel mode: <code>UNRESTRICTED</code> or <code>RESTRICTED</code>. Administrators, * moderators, and channel members can add themselves and other members to unrestricted * channels. Only administrators and moderators can add members to restricted channels.</p> */ Mode?: ChannelMode | string; /** * <p>The channel's privacy level: <code>PUBLIC</code> or <code>PRIVATE</code>. Private * channels aren't discoverable by users outside the channel. Public channels are discoverable * by anyone in the <code>AppInstance</code>.</p> */ Privacy?: ChannelPrivacy | string; /** * <p>The metadata of the creation request. Limited to 1KB and UTF-8.</p> */ Metadata?: string; /** * <p>The client token for the request. An <code>Idempotency</code> token.</p> */ ClientRequestToken?: string; /** * <p>The tags for the creation request.</p> */ Tags?: Tag[]; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace CreateChannelRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateChannelRequest): any => ({ ...obj, ...(obj.Name && { Name: SENSITIVE_STRING }), ...(obj.Metadata && { Metadata: SENSITIVE_STRING }), ...(obj.ClientRequestToken && { ClientRequestToken: SENSITIVE_STRING }), ...(obj.Tags && { Tags: obj.Tags.map((item) => Tag.filterSensitiveLog(item)) }), }); } export interface CreateChannelResponse { /** * <p>The ARN of the channel.</p> */ ChannelArn?: string; } export namespace CreateChannelResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateChannelResponse): any => ({ ...obj, }); } /** * <p>The request exceeds the resource limit.</p> */ export interface ResourceLimitExceededException extends __SmithyException, $MetadataBearer { name: "ResourceLimitExceededException"; $fault: "client"; Code?: ErrorCode | string; Message?: string; } export namespace ResourceLimitExceededException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceLimitExceededException): any => ({ ...obj, }); } export interface CreateChannelBanRequest { /** * <p>The ARN of the ban request.</p> */ ChannelArn: string | undefined; /** * <p>The ARN of the member being banned.</p> */ MemberArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace CreateChannelBanRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateChannelBanRequest): any => ({ ...obj, }); } export interface CreateChannelBanResponse { /** * <p>The ARN of the response to the ban request.</p> */ ChannelArn?: string; /** * <p>The <code>ChannelArn</code> and <code>BannedIdentity</code> of the member in the ban * response.</p> */ Member?: Identity; } export namespace CreateChannelBanResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateChannelBanResponse): any => ({ ...obj, ...(obj.Member && { Member: Identity.filterSensitiveLog(obj.Member) }), }); } export interface CreateChannelMembershipRequest { /** * <p>The ARN of the channel to which you're adding users.</p> */ ChannelArn: string | undefined; /** * <p>The ARN of the member you want to add to the channel.</p> */ MemberArn: string | undefined; /** * <p>The membership type of a user, <code>DEFAULT</code> or <code>HIDDEN</code>. Default * members are always returned as part of <code>ListChannelMemberships</code>. Hidden members * are only returned if the type filter in <code>ListChannelMemberships</code> equals * <code>HIDDEN</code>. Otherwise hidden members are not returned. This is only supported * by moderators.</p> */ Type: ChannelMembershipType | string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace CreateChannelMembershipRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateChannelMembershipRequest): any => ({ ...obj, }); } export interface CreateChannelMembershipResponse { /** * <p>The ARN of the channel.</p> */ ChannelArn?: string; /** * <p>The ARN and metadata of the member being added.</p> */ Member?: Identity; } export namespace CreateChannelMembershipResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateChannelMembershipResponse): any => ({ ...obj, ...(obj.Member && { Member: Identity.filterSensitiveLog(obj.Member) }), }); } export interface CreateChannelModeratorRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The ARN of the moderator.</p> */ ChannelModeratorArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace CreateChannelModeratorRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateChannelModeratorRequest): any => ({ ...obj, }); } export interface CreateChannelModeratorResponse { /** * <p>The ARN of the channel.</p> */ ChannelArn?: string; /** * <p>The ARNs of the channel and the moderator.</p> */ ChannelModerator?: Identity; } export namespace CreateChannelModeratorResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateChannelModeratorResponse): any => ({ ...obj, ...(obj.ChannelModerator && { ChannelModerator: Identity.filterSensitiveLog(obj.ChannelModerator) }), }); } export interface DeleteChannelRequest { /** * <p>The ARN of the channel being deleted.</p> */ ChannelArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace DeleteChannelRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteChannelRequest): any => ({ ...obj, }); } export interface DeleteChannelBanRequest { /** * <p>The ARN of the channel from which the <code>AppInstanceUser</code> was banned.</p> */ ChannelArn: string | undefined; /** * <p>The ARN of the <code>AppInstanceUser</code> that you want to reinstate.</p> */ MemberArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace DeleteChannelBanRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteChannelBanRequest): any => ({ ...obj, }); } export interface DeleteChannelMembershipRequest { /** * <p>The ARN of the channel from which you want to remove the user.</p> */ ChannelArn: string | undefined; /** * <p>The ARN of the member that you're removing from the channel.</p> */ MemberArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace DeleteChannelMembershipRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteChannelMembershipRequest): any => ({ ...obj, }); } export interface DeleteChannelMessageRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The ID of the message being deleted.</p> */ MessageId: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace DeleteChannelMessageRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteChannelMessageRequest): any => ({ ...obj, }); } export interface DeleteChannelModeratorRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The ARN of the moderator being deleted.</p> */ ChannelModeratorArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace DeleteChannelModeratorRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteChannelModeratorRequest): any => ({ ...obj, }); } export interface DescribeChannelRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace DescribeChannelRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeChannelRequest): any => ({ ...obj, }); } export interface DescribeChannelResponse { /** * <p>The channel details.</p> */ Channel?: Channel; } export namespace DescribeChannelResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeChannelResponse): any => ({ ...obj, ...(obj.Channel && { Channel: Channel.filterSensitiveLog(obj.Channel) }), }); } export interface DescribeChannelBanRequest { /** * <p>The ARN of the channel from which the user is banned.</p> */ ChannelArn: string | undefined; /** * <p>The ARN of the member being banned.</p> */ MemberArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace DescribeChannelBanRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeChannelBanRequest): any => ({ ...obj, }); } export interface DescribeChannelBanResponse { /** * <p>The details of the ban.</p> */ ChannelBan?: ChannelBan; } export namespace DescribeChannelBanResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeChannelBanResponse): any => ({ ...obj, ...(obj.ChannelBan && { ChannelBan: ChannelBan.filterSensitiveLog(obj.ChannelBan) }), }); } /** * <p>One or more of the resources in the request does not exist in the system.</p> */ export interface NotFoundException extends __SmithyException, $MetadataBearer { name: "NotFoundException"; $fault: "client"; Code?: ErrorCode | string; Message?: string; } export namespace NotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: NotFoundException): any => ({ ...obj, }); } export interface DescribeChannelMembershipRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The ARN of the member.</p> */ MemberArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace DescribeChannelMembershipRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeChannelMembershipRequest): any => ({ ...obj, }); } export interface DescribeChannelMembershipResponse { /** * <p>The details of the membership.</p> */ ChannelMembership?: ChannelMembership; } export namespace DescribeChannelMembershipResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeChannelMembershipResponse): any => ({ ...obj, ...(obj.ChannelMembership && { ChannelMembership: ChannelMembership.filterSensitiveLog(obj.ChannelMembership) }), }); } export interface DescribeChannelMembershipForAppInstanceUserRequest { /** * <p>The ARN of the channel to which the user belongs.</p> */ ChannelArn: string | undefined; /** * <p>The ARN of the user in a channel.</p> */ AppInstanceUserArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace DescribeChannelMembershipForAppInstanceUserRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeChannelMembershipForAppInstanceUserRequest): any => ({ ...obj, }); } export interface DescribeChannelMembershipForAppInstanceUserResponse { /** * <p>The channel to which a user belongs.</p> */ ChannelMembership?: ChannelMembershipForAppInstanceUserSummary; } export namespace DescribeChannelMembershipForAppInstanceUserResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeChannelMembershipForAppInstanceUserResponse): any => ({ ...obj, ...(obj.ChannelMembership && { ChannelMembership: ChannelMembershipForAppInstanceUserSummary.filterSensitiveLog(obj.ChannelMembership), }), }); } export interface DescribeChannelModeratedByAppInstanceUserRequest { /** * <p>The ARN of the moderated channel.</p> */ ChannelArn: string | undefined; /** * <p>The ARN of the <code>AppInstanceUser</code> in the moderated channel.</p> */ AppInstanceUserArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace DescribeChannelModeratedByAppInstanceUserRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeChannelModeratedByAppInstanceUserRequest): any => ({ ...obj, }); } export interface DescribeChannelModeratedByAppInstanceUserResponse { /** * <p>The moderated channel.</p> */ Channel?: ChannelModeratedByAppInstanceUserSummary; } export namespace DescribeChannelModeratedByAppInstanceUserResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeChannelModeratedByAppInstanceUserResponse): any => ({ ...obj, ...(obj.Channel && { Channel: ChannelModeratedByAppInstanceUserSummary.filterSensitiveLog(obj.Channel) }), }); } export interface DescribeChannelModeratorRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The ARN of the channel moderator.</p> */ ChannelModeratorArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace DescribeChannelModeratorRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeChannelModeratorRequest): any => ({ ...obj, }); } export interface DescribeChannelModeratorResponse { /** * <p>The details of the channel moderator.</p> */ ChannelModerator?: ChannelModerator; } export namespace DescribeChannelModeratorResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeChannelModeratorResponse): any => ({ ...obj, ...(obj.ChannelModerator && { ChannelModerator: ChannelModerator.filterSensitiveLog(obj.ChannelModerator) }), }); } export interface GetChannelMessageRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The ID of the message.</p> */ MessageId: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace GetChannelMessageRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetChannelMessageRequest): any => ({ ...obj, }); } export interface GetChannelMessageResponse { /** * <p>The details of and content in the message.</p> */ ChannelMessage?: ChannelMessage; } export namespace GetChannelMessageResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetChannelMessageResponse): any => ({ ...obj, ...(obj.ChannelMessage && { ChannelMessage: ChannelMessage.filterSensitiveLog(obj.ChannelMessage) }), }); } export interface GetMessagingSessionEndpointRequest {} export namespace GetMessagingSessionEndpointRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetMessagingSessionEndpointRequest): any => ({ ...obj, }); } /** * <p>The websocket endpoint used to connect to Amazon Chime SDK messaging.</p> */ export interface MessagingSessionEndpoint { /** * <p>The endpoint to which you establish a websocket connection.</p> */ Url?: string; } export namespace MessagingSessionEndpoint { /** * @internal */ export const filterSensitiveLog = (obj: MessagingSessionEndpoint): any => ({ ...obj, }); } export interface GetMessagingSessionEndpointResponse { /** * <p>The endpoint returned in the response.</p> */ Endpoint?: MessagingSessionEndpoint; } export namespace GetMessagingSessionEndpointResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetMessagingSessionEndpointResponse): any => ({ ...obj, }); } export interface ListChannelBansRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The maximum number of bans that you want returned.</p> */ MaxResults?: number; /** * <p>The token passed by previous API calls until all requested bans are returned.</p> */ NextToken?: string; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace ListChannelBansRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelBansRequest): any => ({ ...obj, ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), }); } export interface ListChannelBansResponse { /** * <p>The ARN of the channel.</p> */ ChannelArn?: string; /** * <p>The token passed by previous API calls until all requested bans are returned.</p> */ NextToken?: string; /** * <p>The information for each requested ban.</p> */ ChannelBans?: ChannelBanSummary[]; } export namespace ListChannelBansResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelBansResponse): any => ({ ...obj, ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), ...(obj.ChannelBans && { ChannelBans: obj.ChannelBans.map((item) => ChannelBanSummary.filterSensitiveLog(item)) }), }); } export interface ListChannelMembershipsRequest { /** * <p>The maximum number of channel memberships that you want returned.</p> */ ChannelArn: string | undefined; /** * <p>The membership type of a user, <code>DEFAULT</code> or <code>HIDDEN</code>. Default * members are always returned as part of <code>ListChannelMemberships</code>. Hidden members * are only returned if the type filter in <code>ListChannelMemberships</code> equals * <code>HIDDEN</code>. Otherwise hidden members are not returned.</p> */ Type?: ChannelMembershipType | string; /** * <p>The maximum number of channel memberships that you want returned.</p> */ MaxResults?: number; /** * <p>The token passed by previous API calls until all requested channel memberships are * returned.</p> */ NextToken?: string; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace ListChannelMembershipsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelMembershipsRequest): any => ({ ...obj, ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), }); } export interface ListChannelMembershipsResponse { /** * <p>The ARN of the channel.</p> */ ChannelArn?: string; /** * <p>The information for the requested channel memberships.</p> */ ChannelMemberships?: ChannelMembershipSummary[]; /** * <p>The token passed by previous API calls until all requested channel memberships are * returned.</p> */ NextToken?: string; } export namespace ListChannelMembershipsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelMembershipsResponse): any => ({ ...obj, ...(obj.ChannelMemberships && { ChannelMemberships: obj.ChannelMemberships.map((item) => ChannelMembershipSummary.filterSensitiveLog(item)), }), ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), }); } export interface ListChannelMembershipsForAppInstanceUserRequest { /** * <p>The ARN of the <code>AppInstanceUser</code>s</p> */ AppInstanceUserArn?: string; /** * <p>The maximum number of users that you want returned.</p> */ MaxResults?: number; /** * <p>The token returned from previous API requests until the number of channel memberships is * reached.</p> */ NextToken?: string; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace ListChannelMembershipsForAppInstanceUserRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelMembershipsForAppInstanceUserRequest): any => ({ ...obj, ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), }); } export interface ListChannelMembershipsForAppInstanceUserResponse { /** * <p>The token passed by previous API calls until all requested users are returned.</p> */ ChannelMemberships?: ChannelMembershipForAppInstanceUserSummary[]; /** * <p>The token passed by previous API calls until all requested users are returned.</p> */ NextToken?: string; } export namespace ListChannelMembershipsForAppInstanceUserResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelMembershipsForAppInstanceUserResponse): any => ({ ...obj, ...(obj.ChannelMemberships && { ChannelMemberships: obj.ChannelMemberships.map((item) => ChannelMembershipForAppInstanceUserSummary.filterSensitiveLog(item) ), }), ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), }); } export enum SortOrder { ASCENDING = "ASCENDING", DESCENDING = "DESCENDING", } export interface ListChannelMessagesRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The order in which you want messages sorted. Default is Descending, based on time * created.</p> */ SortOrder?: SortOrder | string; /** * <p>The initial or starting time stamp for your requested messages.</p> */ NotBefore?: Date; /** * <p>The final or ending time stamp for your requested messages.</p> */ NotAfter?: Date; /** * <p>The maximum number of messages that you want returned.</p> */ MaxResults?: number; /** * <p>The token passed by previous API calls until all requested messages are returned.</p> */ NextToken?: string; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace ListChannelMessagesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelMessagesRequest): any => ({ ...obj, ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), }); } export interface ListChannelMessagesResponse { /** * <p>The ARN of the channel containing the requested messages.</p> */ ChannelArn?: string; /** * <p>The token passed by previous API calls until all requested messages are returned.</p> */ NextToken?: string; /** * <p>The information about, and content of, each requested message.</p> */ ChannelMessages?: ChannelMessageSummary[]; } export namespace ListChannelMessagesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelMessagesResponse): any => ({ ...obj, ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), ...(obj.ChannelMessages && { ChannelMessages: obj.ChannelMessages.map((item) => ChannelMessageSummary.filterSensitiveLog(item)), }), }); } export interface ListChannelModeratorsRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The maximum number of moderators that you want returned.</p> */ MaxResults?: number; /** * <p>The token passed by previous API calls until all requested moderators are * returned.</p> */ NextToken?: string; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace ListChannelModeratorsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelModeratorsRequest): any => ({ ...obj, ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), }); } export interface ListChannelModeratorsResponse { /** * <p>The ARN of the channel.</p> */ ChannelArn?: string; /** * <p>The token passed by previous API calls until all requested moderators are * returned.</p> */ NextToken?: string; /** * <p>The information about and names of each moderator.</p> */ ChannelModerators?: ChannelModeratorSummary[]; } export namespace ListChannelModeratorsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelModeratorsResponse): any => ({ ...obj, ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), ...(obj.ChannelModerators && { ChannelModerators: obj.ChannelModerators.map((item) => ChannelModeratorSummary.filterSensitiveLog(item)), }), }); } export interface ListChannelsRequest { /** * <p>The ARN of the <code>AppInstance</code>.</p> */ AppInstanceArn: string | undefined; /** * <p>The privacy setting. <code>PUBLIC</code> retrieves all the public channels. * <code>PRIVATE</code> retrieves private channels. Only an <code>AppInstanceAdmin</code> * can retrieve private channels. </p> */ Privacy?: ChannelPrivacy | string; /** * <p>The maximum number of channels that you want to return.</p> */ MaxResults?: number; /** * <p>The token passed by previous API calls until all requested channels are returned.</p> */ NextToken?: string; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace ListChannelsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelsRequest): any => ({ ...obj, ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), }); } export interface ListChannelsResponse { /** * <p>The information about each channel.</p> */ Channels?: ChannelSummary[]; /** * <p>The token returned from previous API requests until the number of channels is * reached.</p> */ NextToken?: string; } export namespace ListChannelsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelsResponse): any => ({ ...obj, ...(obj.Channels && { Channels: obj.Channels.map((item) => ChannelSummary.filterSensitiveLog(item)) }), ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), }); } export interface ListChannelsModeratedByAppInstanceUserRequest { /** * <p>The ARN of the user in the moderated channel.</p> */ AppInstanceUserArn?: string; /** * <p>The maximum number of channels in the request.</p> */ MaxResults?: number; /** * <p>The token returned from previous API requests until the number of channels moderated by * the user is reached.</p> */ NextToken?: string; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace ListChannelsModeratedByAppInstanceUserRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelsModeratedByAppInstanceUserRequest): any => ({ ...obj, ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), }); } export interface ListChannelsModeratedByAppInstanceUserResponse { /** * <p>The moderated channels in the request.</p> */ Channels?: ChannelModeratedByAppInstanceUserSummary[]; /** * <p>The token returned from previous API requests until the number of channels moderated by * the user is reached.</p> */ NextToken?: string; } export namespace ListChannelsModeratedByAppInstanceUserResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListChannelsModeratedByAppInstanceUserResponse): any => ({ ...obj, ...(obj.Channels && { Channels: obj.Channels.map((item) => ChannelModeratedByAppInstanceUserSummary.filterSensitiveLog(item)), }), ...(obj.NextToken && { NextToken: SENSITIVE_STRING }), }); } export interface RedactChannelMessageRequest { /** * <p>The ARN of the channel containing the messages that you want to redact.</p> */ ChannelArn: string | undefined; /** * <p>The ID of the message being redacted.</p> */ MessageId: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace RedactChannelMessageRequest { /** * @internal */ export const filterSensitiveLog = (obj: RedactChannelMessageRequest): any => ({ ...obj, }); } export interface RedactChannelMessageResponse { /** * <p>The ARN of the channel containing the messages that you want to redact.</p> */ ChannelArn?: string; /** * <p>The ID of the message being redacted.</p> */ MessageId?: string; } export namespace RedactChannelMessageResponse { /** * @internal */ export const filterSensitiveLog = (obj: RedactChannelMessageResponse): any => ({ ...obj, }); } export interface SendChannelMessageRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The content of the message.</p> */ Content: string | undefined; /** * <p>The type of message, <code>STANDARD</code> or <code>CONTROL</code>.</p> */ Type: ChannelMessageType | string | undefined; /** * <p>Boolean that controls whether the message is persisted on the back end. Required.</p> */ Persistence: ChannelMessagePersistenceType | string | undefined; /** * <p>The optional metadata for each message.</p> */ Metadata?: string; /** * <p>The <code>Idempotency</code> token for each client request.</p> */ ClientRequestToken?: string; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace SendChannelMessageRequest { /** * @internal */ export const filterSensitiveLog = (obj: SendChannelMessageRequest): any => ({ ...obj, ...(obj.Content && { Content: SENSITIVE_STRING }), ...(obj.Metadata && { Metadata: SENSITIVE_STRING }), ...(obj.ClientRequestToken && { ClientRequestToken: SENSITIVE_STRING }), }); } export interface SendChannelMessageResponse { /** * <p>The ARN of the channel.</p> */ ChannelArn?: string; /** * <p>The ID string assigned to each message.</p> */ MessageId?: string; } export namespace SendChannelMessageResponse { /** * @internal */ export const filterSensitiveLog = (obj: SendChannelMessageResponse): any => ({ ...obj, }); } export interface UpdateChannelRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The name of the channel.</p> */ Name: string | undefined; /** * <p>The mode of the update request.</p> */ Mode: ChannelMode | string | undefined; /** * <p>The metadata for the update request.</p> */ Metadata?: string; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace UpdateChannelRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateChannelRequest): any => ({ ...obj, ...(obj.Name && { Name: SENSITIVE_STRING }), ...(obj.Metadata && { Metadata: SENSITIVE_STRING }), }); } export interface UpdateChannelResponse { /** * <p>The ARN of the channel.</p> */ ChannelArn?: string; } export namespace UpdateChannelResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateChannelResponse): any => ({ ...obj, }); } export interface UpdateChannelMessageRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The ID string of the message being updated.</p> */ MessageId: string | undefined; /** * <p>The content of the message being updated.</p> */ Content?: string; /** * <p>The metadata of the message being updated.</p> */ Metadata?: string; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace UpdateChannelMessageRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateChannelMessageRequest): any => ({ ...obj, ...(obj.Content && { Content: SENSITIVE_STRING }), ...(obj.Metadata && { Metadata: SENSITIVE_STRING }), }); } export interface UpdateChannelMessageResponse { /** * <p>The ARN of the channel.</p> */ ChannelArn?: string; /** * <p>The ID string of the message being updated.</p> */ MessageId?: string; } export namespace UpdateChannelMessageResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateChannelMessageResponse): any => ({ ...obj, }); } export interface UpdateChannelReadMarkerRequest { /** * <p>The ARN of the channel.</p> */ ChannelArn: string | undefined; /** * <p>The <code>AppInstanceUserArn</code> of the user that makes the API call.</p> */ ChimeBearer: string | undefined; } export namespace UpdateChannelReadMarkerRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateChannelReadMarkerRequest): any => ({ ...obj, }); } export interface UpdateChannelReadMarkerResponse { /** * <p>The ARN of the channel.</p> */ ChannelArn?: string; } export namespace UpdateChannelReadMarkerResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateChannelReadMarkerResponse): any => ({ ...obj, }); }
the_stack
module TDev { export class UndoState { public savedApp: IndexedString[]; public loc: CodeLocation; public parse(): AST.App { return AST.Parser.parseScript( this.savedApp.map((e) => e.s).join("\n") ); } public toJson() { var usedEntries: any = {} return { savedApp: this.savedApp.map((e: IndexedString) => { if (usedEntries[e.idx + ""]) { return { idx: e.idx, s: null } } else { usedEntries[e.idx + ""] = 1; return e; } }), loc: !this.loc ? null : this.loc.toJson() }; } static fromJson(par: UndoMgr, j: any) { var r = new UndoState(); var entries: any = {} r.savedApp = j.savedApp.map((e: any) => { if (typeof e == "string") return { idx: par.nextId(), s: e } else if (e.s !== null) { var ee = { idx: par.nextId(), s: e.s } entries[e.idx + ""] = ee; return ee; } else return entries[e.idx + ""]; }); r.loc = CodeLocation.fromJson(j.loc); return r; } static eq(l: UndoState, r: UndoState): boolean { var app1 = l.savedApp; var app2 = r.savedApp; if (app1.length != app2.length) return false; for (var i = 0; i < app1.length; ++i) if (app1[i].idx != app2[i].idx) return false; return true; } } export class UndoMgr { public sent = []; private refreshUndoState = undefined; private refreshUndoScript = undefined; //private refreshLock = false; private maxUndo = 20; private mainStates: UndoState[] = []; private blockPush = 0; private calcStates = []; private currentIdx = 1; private logMsg = ""; private fakeAppDecl = { serialize: () => Script.serializeFinal(), nodeType: () => "fakeAppDecl", getName: () => "app" } public currentId() { return this.currentIdx; } public nextId() { return this.currentIdx++; } private updateCache(d: AST.Decl) { var cache = d.cachedSerialized; if (!cache) cache = d.cachedSerialized = { idx: 0, s: null } if (cache.idx > 0) return false; var newS: string; if (d instanceof AST.App) newS = (<AST.App>d).serializeMeta(); else newS = d.serialize() if (cache.idx < 0 && newS === cache.s) { cache.idx = -cache.idx; this.logMsg += d.getName() + ":hit "; return false; } else { cache.s = newS; cache.idx = this.nextId(); this.logMsg += d.getName() + ":upd "; return true; } } public checkCaches() { var err = "" var check = (d: AST.Decl) => { var cache = d.cachedSerialized; if (!cache || cache.idx < 0) return; var newS: string; if (d instanceof AST.App) newS = (<AST.App>d).serializeMeta(); else newS = d.serialize() if (newS !== cache.s) { err += " [mismatch: " + d.nodeType() + " " + d.getName() + "]" debugger; } } check(Script); Script.things.forEach(check); // This one is always updated; no need to check // check(<AST.Decl>this.fakeAppDecl); return err; } private createSavedApp() { var res = [] var updateNum = 0; var add = (d: AST.Decl) => { if (this.updateCache(d)) updateNum++; var c = d.cachedSerialized; res.push({ idx: c.idx, s: c.s }); } add(Script); Script.things.forEach(add); var appDecl = <AST.Decl>this.fakeAppDecl; // always update this if (appDecl.cachedSerialized && appDecl.cachedSerialized.idx > 0) appDecl.cachedSerialized.idx = -appDecl.cachedSerialized.idx; add(appDecl); Ticker.dbg("UndoMgr.createSavedApp " + this.logMsg); this.logMsg = ""; return res; } public getScriptSource() { if (this.mainStates.length == 0) return ""; var u = this.mainStates.peek(); return u.savedApp.map((e) => e.s).join("").replace(/\n+/g, "\n"); } private recordAst() { if (!Collab.AstSession) { return; } if (!Collab.ready) { return; } if (Script.things.length > 0) { var ast = Script.serialize(); // TODO XXX - not efficient this.last_editor_version = Collab.recordAst(ast); } else { // prevent deletion of last thing this.pullIntoEditor(true); } } /* private pushUndoToLog(ast1: string, ast2: string) { if (!Collab.currentCloudAst) { return; } Collab.pushUndoToLog(ast1, ast2); } public refreshFromLog(): Promise { //if (this.refreshLock) // return Promise.as(); var isUndo = !!this.refreshUndoState; if (isUndo) { //console.log("UNDO 1 -----------"); //console.log(UndoScript); //console.log("UNDO 2 -----------"); //console.log(this.refreshUndoScript); //console.log("-----------"); //this.pushToLog(UndoScript, this.refreshUndoScript); var lastS = this.mainStates.peek(); var last = lastS ? lastS.savedApp.map((e) => e.s).join("\n") : undefined; //this.refreshLock = true; this.pushUndoToLog(this.refreshUndoScript, (last ? last : this.refreshUndoScript)); } else { //this.refreshLock = true; this.pushToLog(true); } return this.pullIntoEditor(isUndo); } */ private previouspull: Promise = Promise.as(); private last_editor_version: any = undefined; public pullIntoEditor(force: boolean = false): Promise { return this.previouspull = this.previouspull.thenalways(() => { if (!Collab.AstSession) { return; } if (this.last_editor_version && !force && Collab.astEquals(Collab.currentCloudAst, this.last_editor_version)) { //this.refreshLock = false; return Promise.as(); } // TODO XXX - is this efficient? //if (Collab.currentCloudAst[1] == Script.serialize()) { //this.refreshLock = false; // return Promise.as(); //} var newast = Collab.currentCloudAst; Util.log(">>> pullIntoEditor " + Collab.astdesc(newast)); //this.refreshLock = false; // TODO XXX - is it okay to unlock here? return TheEditor.loadScriptTextAsync(ScriptEditorWorldInfo, newast[1], TheEditor.serializeState(), false).then( () => { // if (!isUndo) { TheEditor.renderDefaultDecl(true, true); TheEditor.queueNavRefresh(); this.last_editor_version = newast; // } else { // if (!this.refreshUndoState.loc || // may happen when replaying a tutorial // !TheEditor.loadLocation(this.refreshUndoState.loc.rebind(), false)) // TheEditor.renderDefaultDecl(); // TheEditor.undoLoaded(); // this.refreshUndoState = null; // this.refreshUndoScript = null; // } }); }); } public pushMainUndoState(disableLog= false) { //Util.log(">>> pushMainUndoState()"); if (!disableLog) { this.recordAst(); } Ticker.dbg("UndoMgr.pushMain"); if (this.blockPush > 0) return; try { this.blockPush++; var u = new UndoState(); u.savedApp = this.createSavedApp(); u.loc = TheEditor.currentLocation(); var prev = this.mainStates.peek(); if (!!prev && UndoState.eq(prev, u)) { if (!!u.loc) { prev.loc = u.loc; this.observeChange(); } return; } if (this.mainStates.length > this.maxUndo) { for (var i = 1; i < this.mainStates.length; ++i) this.mainStates[i - 1] = this.mainStates[i]; this.mainStates[i - 1] = u; } else { this.mainStates.push(u); } this.observeChange(); // TODO XXX - we disable autosave for the collaborative editing demo if (!TDev.Collab.enableUndo) TheEditor.scheduleSaveToCloudAsync(true).done(); } finally { this.blockPush--; } } public applyMainUndoStateAsync(u: UndoState) { this.blockPush++; try { return this.reloadUndoStateAsync(u); } finally { this.blockPush--; } } public popMainUndoStateAsync() { if (this.mainStates.length == 0) return Promise.as(); this.pushMainUndoState(true); this.blockPush++; try { this.mainStates.pop(); // pop the original state var u = this.mainStates.pop(); return this.reloadUndoStateAsync(u); } finally { this.blockPush--; } } private reloadUndoStateAsync(u: UndoState) { if (TDev.Collab.enableUndo && !!this.refreshUndoState) return Promise.as(); // nothing if (!u || !u.savedApp) return Promise.as(); // nothing to do var script = u.savedApp.map((e) => e.s).join("\n"); Util.assert(script && script.charAt(0) != '{'); this.refreshUndoState = u; this.refreshUndoScript = script; //if (TDev.Collab.enableUndo) return this.refreshFromLog(); return TheEditor.loadScriptTextAsync(ScriptEditorWorldInfo, script, TheEditor.serializeState()).then(() => { if (!u.loc || // may happen when replaying a tutorial !TheEditor.loadLocation(u.loc.rebind())) TheEditor.renderDefaultDecl(); TheEditor.undoLoaded(); }); } public clear() { this.mainStates = []; this.calcStates = []; this.onStateChange = null; } public toJson() { return { states: this.mainStates.map((s: UndoState) => s.toJson()), calcStates: this.calcStates }; } private load(j: any) { this.mainStates = (j.states || []).map((j: any) => UndoState.fromJson(this, j)); this.calcStates = j.calcStates || []; } public clearCalc() { this.calcStates = []; } public pushCalcState(s: any) { this.recordAst(); this.calcStates.push(s); } public peekCalcState() { return this.calcStates.peek(); } public popCalcState() { return this.calcStates.pop(); } public setStateChange(onStateChange: (state: UndoState) => void) { this.onStateChange = onStateChange; if (!!this.onStateChange) { if (this.mainStates.length == 0) this.pushMainUndoState(); this.observeChange(); } } private onStateChange: (state: UndoState) => void = null; private observeChange() { TheEditor.live.poke(); if (!!this.onStateChange && this.mainStates.length > 0) { var s = this.mainStates.peek(); this.onStateChange(s); } } } }
the_stack
import { ExtensionFragDepth } from '../globals' import { defaults } from '../utils' import Representation, { RepresentationParameters } from './representation' import Volume from '../surface/volume' import FilteredVolume from '../surface/filtered-volume' import SphereBuffer, { SphereBufferData, SphereBufferParameters } from '../buffer/sphere-buffer' import PointBuffer from '../buffer/point-buffer' import Surface from '../surface/surface'; import Viewer from '../viewer/viewer'; import SphereGeometryBuffer from '../buffer/spheregeometry-buffer'; export interface DotDataFields { color?: boolean, radius?: boolean, scale?: boolean } /** * Dot representation parameter object. Extends {@link RepresentationParameters} * * @typedef {Object} DotRepresentationParameters - dot representation parameters * * @property {String} thresholdType - Meaning of the threshold values. Either *value* for the literal value or *sigma* as a factor of the sigma of the data. For volume data only. * @property {Number} thresholdMin - Minimum value to be displayed. For volume data only. * @property {Number} thresholdMax - Maximum value to be displayed. For volume data only. * @property {Number} thresholdOut - Show only values falling outside of the treshold minumum and maximum. For volume data only. */ export interface DotRepresentationParameters extends RepresentationParameters { thresholdType: 'value'|'value'|'sigma'|'sigma' thresholdMin: number thresholdMax: number thresholdOut: boolean dotType: ''|'sphere'|'point' radiusType: ''|'value'|'abs-value'|'value-min'|'deviation'|'size'|'radius' //TODO had to add 'radius' because of test in line 333 radius: number scale: number sphereDetail: number disableImpostor: boolean pointSize: number sizeAttenuation: boolean sortParticles: boolean useTexture: boolean alphaTest: number forceTransparent: boolean edgeBleach: number } /** * Dot representation */ class DotRepresentation extends Representation { protected thresholdType: 'value'|'value'|'sigma'|'sigma' protected thresholdMin: number protected thresholdMax: number protected thresholdOut: boolean protected dotType: ''|'sphere'|'point' protected radiusType: ''|'value'|'abs-value'|'value-min'|'deviation'|'size'|'radius' //TODO had to add 'radius' because of test in line 333 protected radius: number protected scale: number protected sphereDetail: number protected disableImpostor: boolean protected pointSize: number protected sizeAttenuation: boolean protected sortParticles: boolean protected useTexture: boolean protected alphaTest: number protected forceTransparent: boolean protected edgeBleach: number protected surface: Surface|undefined protected volume: FilteredVolume|undefined protected dotBuffer: SphereBuffer|PointBuffer /** * Create Dot representation object * @param {Surface|Volume} surface - the surface or volume to be represented * @param {Viewer} viewer - a viewer object * @param {DotRepresentationParameters} params - dot representation parameters */ constructor (surface: Surface, viewer: Viewer, params: Partial<DotRepresentationParameters>) { super(surface, viewer, params) this.type = 'dot' this.parameters = Object.assign({ thresholdType: { type: 'select', rebuild: true, options: { 'value': 'value', 'sigma': 'sigma' } }, thresholdMin: { type: 'number', precision: 3, max: Infinity, min: -Infinity, rebuild: true }, thresholdMax: { type: 'number', precision: 3, max: Infinity, min: -Infinity, rebuild: true }, thresholdOut: { type: 'boolean', rebuild: true }, dotType: { type: 'select', rebuild: true, options: { '': '', 'sphere': 'sphere', 'point': 'point' } }, radiusType: { type: 'select', options: { '': '', 'value': 'value', 'abs-value': 'abs-value', 'value-min': 'value-min', 'deviation': 'deviation', 'size': 'size' } }, radius: { type: 'number', precision: 3, max: 10.0, min: 0.001, property: 'size' }, scale: { type: 'number', precision: 3, max: 10.0, min: 0.001 }, sphereDetail: true, disableImpostor: true, pointSize: { type: 'number', precision: 1, max: 100, min: 0, buffer: true }, sizeAttenuation: { type: 'boolean', buffer: true }, sortParticles: { type: 'boolean', rebuild: true }, useTexture: { type: 'boolean', buffer: true }, alphaTest: { type: 'range', step: 0.001, max: 1, min: 0, buffer: true }, forceTransparent: { type: 'boolean', buffer: true }, edgeBleach: { type: 'range', step: 0.001, max: 1, min: 0, buffer: true } }, this.parameters, { colorScheme: { type: 'select', update: 'color', options: { '': '', 'value': 'value', 'uniform': 'uniform', 'random': 'random' } } }) if (surface instanceof Volume) { this.surface = undefined this.volume = new FilteredVolume(surface) } else { this.surface = surface this.volume = undefined } this.init(params) } init (params: Partial<DotRepresentationParameters>) { var p = params || {} p.colorScheme = defaults(p.colorScheme, 'uniform') p.colorValue = defaults(p.colorValue, 0xDDDDDD) this.thresholdType = defaults(p.thresholdType, 'sigma') this.thresholdMin = defaults(p.thresholdMin, 2.0) this.thresholdMax = defaults(p.thresholdMax, Infinity) this.thresholdOut = defaults(p.thresholdOut, false) this.dotType = defaults(p.dotType, 'point') this.radius = defaults(p.radius, 0.1) this.scale = defaults(p.scale, 1.0) this.pointSize = defaults(p.pointSize, 1) this.sizeAttenuation = defaults(p.sizeAttenuation, true) this.sortParticles = defaults(p.sortParticles, false) this.useTexture = defaults(p.useTexture, false) this.alphaTest = defaults(p.alphaTest, 0.5) this.forceTransparent = defaults(p.forceTransparent, false) this.edgeBleach = defaults(p.edgeBleach, 0.0) super.init(p) this.build() } attach (callback: () => void) { this.bufferList.forEach(buffer => { this.viewer.add(buffer) }) this.setVisibility(this.visible) callback() } create () { var dotData: SphereBufferData|{} = {} if (this.volume) { var volume = this.volume var thresholdMin, thresholdMax if (this.thresholdType === 'sigma') { thresholdMin = volume.getValueForSigma(this.thresholdMin) thresholdMax = volume.getValueForSigma(this.thresholdMax) } else { thresholdMin = this.thresholdMin thresholdMax = this.thresholdMax } volume.setFilter(thresholdMin, thresholdMax, this.thresholdOut) Object.assign(dotData, { position: volume.getDataPosition(), color: volume.getDataColor(this.getColorParams()) }) if (this.dotType === 'sphere') { Object.assign(dotData, { radius: volume.getDataSize(this.radius, this.scale), picking: volume.getDataPicking() }) } } else { var surface = this.surface Object.assign(dotData, { position: (surface as Surface).getPosition(), color: (surface as Surface).getColor(this.getColorParams()) }) if (this.dotType === 'sphere') { Object.assign(dotData, { radius: (surface as Surface).getSize(this.radius, this.scale), picking: (surface as Surface).getPicking() }) } } if (this.dotType === 'sphere') { this.dotBuffer = new SphereBuffer( dotData as SphereBufferData, this.getBufferParams({ sphereDetail: this.sphereDetail, disableImpostor: this.disableImpostor, dullInterior: false }) as SphereBufferParameters ) as SphereGeometryBuffer } else { this.dotBuffer = new PointBuffer( dotData, this.getBufferParams({ pointSize: this.pointSize, sizeAttenuation: this.sizeAttenuation, sortParticles: this.sortParticles, useTexture: this.useTexture, alphaTest: this.alphaTest, forceTransparent: this.forceTransparent, edgeBleach: this.edgeBleach }) ) } this.bufferList.push(this.dotBuffer as SphereGeometryBuffer) } update (what: DotDataFields = {}) { if (this.bufferList.length === 0) return const dotData: SphereBufferData|{} = {} if (what.color) { if (this.volume) { Object.assign(dotData, { color: this.volume.getDataColor( this.getColorParams() ) }) } else { Object.assign(dotData, { color: (this.surface as Surface).getColor( this.getColorParams() ) }) } } if (this.dotType === 'sphere' && (what.radius || what.scale)) { if (this.volume) { Object.assign(dotData, { radius: this.volume.getDataSize( this.radius, this.scale ) }) } else { Object.assign(dotData, { radius: (this.surface as Surface).getSize( this.radius, this.scale ) }) } } (this.dotBuffer as SphereGeometryBuffer).setAttributes(dotData) } setParameters (params: Partial<DotRepresentationParameters>, what: DotDataFields = {}, rebuild: boolean) { if (params && params.thresholdType !== undefined && this.volume instanceof Volume ) { if (this.thresholdType === 'value' && params.thresholdType === 'sigma' ) { this.thresholdMin = this.volume.getSigmaForValue( this.thresholdMin ) this.thresholdMax = this.volume.getSigmaForValue( this.thresholdMax ) } else if (this.thresholdType === 'sigma' && params.thresholdType === 'value' ) { this.thresholdMin = this.volume.getValueForSigma( this.thresholdMin ) this.thresholdMax = this.volume.getValueForSigma( this.thresholdMax ) } this.thresholdType = params.thresholdType } if (params && params.radiusType !== undefined) { if (params.radiusType === 'radius') { this.radius = 0.1 } else { this.radius = parseFloat(params.radiusType) } what.radius = true if (this.dotType === 'sphere' && (!ExtensionFragDepth || this.disableImpostor) ) { rebuild = true } } if (params && params.radius !== undefined) { what.radius = true if (this.dotType === 'sphere' && (!ExtensionFragDepth || this.disableImpostor) ) { rebuild = true } } if (params && params.scale !== undefined) { what.scale = true if (this.dotType === 'sphere' && (!ExtensionFragDepth || this.disableImpostor) ) { rebuild = true } } super.setParameters(params, what, rebuild) return this } } export default DotRepresentation
the_stack
module Cats { var tsconfig = require("tsconfig"); export interface CompilerOptions { [key: string]: any; noLib?: boolean; target?: string; } export interface TSConfig { compilerOptions?: CompilerOptions; compileOnSave?: boolean; validateOnSave?: boolean; files?: string[]; exclude?: string[]; filesGlob?: string[]; customBuild?: any; customRun?: any; main?: any; name?: string; tslint?: any; codeFormat?:any; documentation?:any; [key: string]: any; } /** * The project hold the information related to a single TypeScript project. * This include a reference to a workerthread that does much of the TypeScript * intellisense. */ export class Project extends qx.event.Emitter { // The home directory of the project name: string; private tsfiles: Array<string> = []; public projectDir; // The singleton TSWorker handler instance iSense: TSWorkerProxy; private refreshInterval: number; config:TSConfig; /** * Create a new project. */ constructor(public tsConfigFile:string) { super(); this.projectDir = OS.File.PATH.dirname(tsConfigFile); this.refresh(); // @TODO optimize only refresh in case of changes this.refreshInterval = setInterval(() => { this.refreshTodoList() }, 60000); } private readConfigFile(fileName) { try { return tsconfig.readFileSync(fileName); } catch (err) { IDE.console.error(`Error reading config file ${fileName}`); } } /** * Save the project configuration */ updateConfig(config: ProjectConfiguration) { return ; /* this.settings.value = config; this.emit("config", config); if (this.config.tslint.useLint) this.linter = new Linter(this); this.settings.store(); this.iSense.setSettings(this.config.compiler, this.config.codeFormat); */ } refreshTodoList() { this.iSense.getTodoItems((err, data) => { IDE.todoList.setData(data, this); }); } /** * Close the project */ close() { if (IDE.editorTabView.hasUnsavedChanges()) { var dialog = new Gui.ConfirmDialog("You have some unsaved changes that will get lost.\n Continue anyway ?"); dialog.onConfirm = () => { this._close(); }; } else { this._close(); } } /** * Close the project without confirmation. * (Internal, do not use directly) */ _close() { // Lets clear the various output panes. IDE.editorTabView.closeAll(); IDE.fileNavigator.clear(); IDE.outlineNavigator.clear(); IDE.problemResult.clear(); IDE.todoList.clear(); if (this.iSense) this.iSense.stop(); clearInterval(this.refreshInterval); IDE.projects = []; } /** * Show the errors on a project level */ validate(verbose = true) { this.iSense.getAllDiagnostics((err, data) => { if (data) { IDE.problemResult.setData(data,this); if ((data.length === 0) && verbose) { IDE.console.log(`Project ${this.name} has no errors`); } } }); } /** * Build this project either with the built-in capabilities or by calling * an external build tool. */ build() { IDE.console.log("Start building project " + this.name + " ..."); if (this.config.customBuild && this.config.customBuild.command) { // IDE.resultbar.selectOption(2); var cmd = this.config.customBuild.command; var options = this.config.customBuild.options || { cwd: null }; if (!options.cwd) { options.cwd = this.projectDir; } var child = OS.File.runCommand(cmd, options); } else { this.iSense.compile((err: Error, data: CompileResults) => { this.showCompilationResults(data); if (data.errors && (data.errors.length > 0)) return; var files = data.outputFiles; files.forEach((file) => { if (!OS.File.PATH.isAbsolute(file.name)) { file.name = OS.File.PATH.join(this.projectDir,file.name); file.name = OS.File.PATH.normalize(file.name); } OS.File.writeTextFile(file.name, file.text); }); IDE.console.log("Done building project " + this.name + "."); }); } } /** * Refresh the project and loads required artifacts * again from the filesystem to be fully in sync */ refresh() { this.config = this.readConfigFile(this.tsConfigFile); IDE.console.log(`Found TypeScript project configuration at ${this.tsConfigFile} containing ${this.config.files.length} files`); this.tsfiles = this.config.files; this.name = this.config.name || OS.File.PATH.basename(this.projectDir); if (!this.config.compilerOptions) this.config.compilerOptions = {}; if (this.iSense) this.iSense.stop(); this.iSense = new TSWorkerProxy(); var content = JSON.stringify(this.config); this.iSense.setConfigFile(this.tsConfigFile,content); if (!this.config.compilerOptions.noLib) { let libFile:string; switch (this.config.compilerOptions.target) { case "es6": case "ES6": libFile = "resource/typings/lib.es6.d.ts"; break; case "es7": case "ES7": libFile = "resource/typings/lib.es7.d.ts"; break; default: libFile = "resource/typings/lib.d.ts"; break; } var fullName = OS.File.join(IDE.catsHomeDir, libFile); var libdts = OS.File.readTextFile(fullName); this.addScript(fullName, libdts); } this.loadProjectSourceFiles(); this.refreshTodoList(); } /** * Compile without actually saving the resulting files */ trialCompile() { this.iSense.compile((err: Error, data: CompileResults) => { this.showCompilationResults(data); }); } private showCompilationResults(data: CompileResults) { if (data.errors && (data.errors.length > 0)) { IDE.problemResult.setData(data.errors, this); return; } IDE.problemResult.clear(); IDE.console.log("Successfully generated " + data.outputFiles.length + " file(s)."); } /** * Run this project either with the built-in capabilities (only for web apps) or by calling * and external command (for example node). */ run() { if (this.config.customRun && this.config.customRun.command) { const cmd = this.config.customRun.command; var options = this.config.customRun.options || { cwd: null }; if (!options.cwd) { options.cwd = this.projectDir; } OS.File.runCommand(cmd, options); } else { const GUI = require('nw.gui'); const main = this.config.main; if (!main) { alert("Please specify the main html file or customRun in the project settings."); return; } const startPage = this.getStartURL(); console.info("Opening file: " + startPage); const win2 = GUI.Window.open(startPage, { toolbar: true, // nodejs: true, // "new-instance": true, webkit: { "page-cache": false } }); } } /** * Get the URL for running the project */ private getStartURL(): string { const url = OS.File.join(this.projectDir, this.config.main); return "file://" + url; } hasScriptFile(fileName: string) { return this.tsfiles.indexOf(fileName) > -1; } updateScript(fullName: string, content: string) { this.iSense.updateScript(fullName, content); } addScript(fullName: string, content: string) { this.iSense.addScript(fullName, content); if (!this.hasScriptFile(fullName)) this.tsfiles.push(fullName); } getScripts(): Array<string> { return this.tsfiles; } /** * Load the source files that are part of this project. Typically * files ending with ts, tsx or js. */ private loadProjectSourceFiles() { this.config.files.forEach((file) => { try { var fullName = OS.File.switchToForwardSlashes(file); // OS.File.join(this.projectDir, file); var content = OS.File.readTextFile(fullName); this.addScript(fullName, content); } catch (err) { console.error("Got error while handling file " + fullName); console.error(err); } }); } } }
the_stack
import { IExecuteFunctions, } from 'n8n-core'; import { IBinaryKeyData, IDataObject, ILoadOptionsFunctions, INodeExecutionData, INodePropertyOptions, INodeType, INodeTypeDescription, NodeApiError, NodeOperationError, } from 'n8n-workflow'; import { createMessage, downloadAttachments, makeRecipient, microsoftApiRequest, microsoftApiRequestAllItems } from './GenericFunctions'; import { draftFields, draftOperations, } from './DraftDescription'; import { draftMessageSharedFields, } from './DraftMessageSharedDescription'; import { messageFields, messageOperations, } from './MessageDescription'; import { messageAttachmentFields, messageAttachmentOperations, } from './MessageAttachmentDescription'; import { folderFields, folderOperations, } from './FolderDescription'; import { folderMessageFields, folderMessageOperations, } from './FolderMessageDecription'; export class MicrosoftOutlook implements INodeType { description: INodeTypeDescription = { displayName: 'Microsoft Outlook', name: 'microsoftOutlook', group: ['transform'], icon: 'file:outlook.svg', version: 1, subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', description: 'Consume Microsoft Outlook API', defaults: { name: 'Microsoft Outlook', }, inputs: ['main'], outputs: ['main'], credentials: [ { name: 'microsoftOutlookOAuth2Api', required: true, }, ], properties: [ { displayName: 'Resource', name: 'resource', type: 'options', default: 'message', options: [ { name: 'Draft', value: 'draft', }, { name: 'Folder', value: 'folder', }, { name: 'Folder Message', value: 'folderMessage', }, { name: 'Message', value: 'message', }, { name: 'Message Attachment', value: 'messageAttachment', }, ], }, // Draft ...draftOperations, ...draftFields, // Message ...messageOperations, ...messageFields, // Message Attachment ...messageAttachmentOperations, ...messageAttachmentFields, // Folder ...folderOperations, ...folderFields, // Folder Message ...folderMessageOperations, ...folderMessageFields, // Draft & Message ...draftMessageSharedFields, ], }; methods = { loadOptions: { // Get all the categories to display them to user so that he can // select them easily async getCategories(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> { const returnData: INodePropertyOptions[] = []; const categories = await microsoftApiRequestAllItems.call(this, 'value', 'GET', '/outlook/masterCategories'); for (const category of categories) { returnData.push({ name: category.displayName as string, value: category.id as string, }); } return returnData; }, }, }; async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> { const items = this.getInputData(); const returnData: IDataObject[] = []; const length = items.length as unknown as number; const qs: IDataObject = {}; let responseData; const resource = this.getNodeParameter('resource', 0) as string; const operation = this.getNodeParameter('operation', 0) as string; if (['draft', 'message'].includes(resource)) { if (operation === 'delete') { for (let i = 0; i < length; i++) { try { const messageId = this.getNodeParameter('messageId', i) as string; responseData = await microsoftApiRequest.call( this, 'DELETE', `/messages/${messageId}`, ); returnData.push({ success: true }); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if (operation === 'get') { for (let i = 0; i < length; i++) { try { const messageId = this.getNodeParameter('messageId', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (additionalFields.fields) { qs['$select'] = additionalFields.fields; } if (additionalFields.filter) { qs['$filter'] = additionalFields.filter; } responseData = await microsoftApiRequest.call( this, 'GET', `/messages/${messageId}`, undefined, qs, ); if (additionalFields.dataPropertyAttachmentsPrefixName) { const prefix = additionalFields.dataPropertyAttachmentsPrefixName as string; const data = await downloadAttachments.call(this, responseData, prefix); returnData.push.apply(returnData, data as unknown as IDataObject[]); } else { returnData.push(responseData); } if (additionalFields.dataPropertyAttachmentsPrefixName) { return [returnData as INodeExecutionData[]]; } } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if (operation === 'update') { for (let i = 0; i < length; i++) { try { const messageId = this.getNodeParameter('messageId', i) as string; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; // Create message from optional fields const body: IDataObject = createMessage(updateFields); responseData = await microsoftApiRequest.call( this, 'PATCH', `/messages/${messageId}`, body, {}, ); returnData.push(responseData); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } } if (resource === 'draft') { if (operation === 'create') { for (let i = 0; i < length; i++) { try { const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; const subject = this.getNodeParameter('subject', i) as string; const bodyContent = this.getNodeParameter('bodyContent', i, '') as string; additionalFields.subject = subject; additionalFields.bodyContent = bodyContent || ' '; // Create message object from optional fields const body: IDataObject = createMessage(additionalFields); if (additionalFields.attachments) { const attachments = (additionalFields.attachments as IDataObject).attachments as IDataObject[]; // // Handle attachments body['attachments'] = attachments.map(attachment => { const binaryPropertyName = attachment.binaryPropertyName as string; if (items[i].binary === undefined) { throw new NodeOperationError(this.getNode(), 'No binary data exists on item!'); } //@ts-ignore if (items[i].binary[binaryPropertyName] === undefined) { throw new NodeOperationError(this.getNode(), `No binary data property "${binaryPropertyName}" does not exists on item!`); } const binaryData = (items[i].binary as IBinaryKeyData)[binaryPropertyName]; return { '@odata.type': '#microsoft.graph.fileAttachment', name: binaryData.fileName, contentBytes: binaryData.data, }; }); } responseData = await microsoftApiRequest.call( this, 'POST', `/messages`, body, {}, ); returnData.push(responseData); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if (operation === 'send') { for (let i = 0; i < length; i++) { try { const messageId = this.getNodeParameter('messageId', i); const additionalFields = this.getNodeParameter('additionalFields', i, {}) as IDataObject; if (additionalFields && additionalFields.recipients) { const recipients = ((additionalFields.recipients as string).split(',') as string[]).filter(email => !!email); if (recipients.length !== 0) { await microsoftApiRequest.call( this, 'PATCH', `/messages/${messageId}`, { toRecipients: recipients.map((recipient: string) => makeRecipient(recipient)) }, ); } } responseData = await microsoftApiRequest.call( this, 'POST', `/messages/${messageId}/send`, ); returnData.push({ success: true }); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } } if (resource === 'message') { if (operation === 'reply') { for (let i = 0; i < length; i++) { try { const messageId = this.getNodeParameter('messageId', i) as string; const replyType = this.getNodeParameter('replyType', i) as string; const comment = this.getNodeParameter('comment', i) as string; const send = this.getNodeParameter('send', i, false) as boolean; const additionalFields = this.getNodeParameter('additionalFields', i, {}) as IDataObject; const body: IDataObject = {}; let action = 'createReply'; if (replyType === 'replyAll') { body.comment = comment; action = 'createReplyAll'; } else { body.comment = comment; body.message = {}; Object.assign(body.message, createMessage(additionalFields)); //@ts-ignore delete body.message.attachments; } responseData = await microsoftApiRequest.call( this, 'POST', `/messages/${messageId}/${action}`, body, ); if (additionalFields.attachments) { const attachments = (additionalFields.attachments as IDataObject).attachments as IDataObject[]; // // Handle attachments const data = attachments.map(attachment => { const binaryPropertyName = attachment.binaryPropertyName as string; if (items[i].binary === undefined) { throw new NodeOperationError(this.getNode(), 'No binary data exists on item!'); } //@ts-ignore if (items[i].binary[binaryPropertyName] === undefined) { throw new NodeOperationError(this.getNode(), `No binary data property "${binaryPropertyName}" does not exists on item!`); } const binaryData = (items[i].binary as IBinaryKeyData)[binaryPropertyName]; return { '@odata.type': '#microsoft.graph.fileAttachment', name: binaryData.fileName, contentBytes: binaryData.data, }; }); for (const attachment of data) { await microsoftApiRequest.call( this, 'POST', `/messages/${responseData.id}/attachments`, attachment, {}, ); } } if (send === true) { await microsoftApiRequest.call( this, 'POST', `/messages/${responseData.id}/send`, ); } returnData.push(responseData); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if (operation === 'getMime') { for (let i = 0; i < length; i++) { try { const messageId = this.getNodeParameter('messageId', i) as string; const dataPropertyNameDownload = this.getNodeParameter('binaryPropertyName', i) as string; const response = await microsoftApiRequest.call( this, 'GET', `/messages/${messageId}/$value`, undefined, {}, undefined, {}, { encoding: null, resolveWithFullResponse: true }, ); let mimeType: string | undefined; if (response.headers['content-type']) { mimeType = response.headers['content-type']; } const newItem: INodeExecutionData = { json: items[i].json, binary: {}, }; if (items[i].binary !== undefined) { // Create a shallow copy of the binary data so that the old // data references which do not get changed still stay behind // but the incoming data does not get changed. Object.assign(newItem.binary, items[i].binary); } items[i] = newItem; const fileName = `${messageId}.eml`; const data = Buffer.from(response.body as string, 'utf8'); items[i].binary![dataPropertyNameDownload] = await this.helpers.prepareBinaryData(data as unknown as Buffer, fileName, mimeType); } catch (error) { if (this.continueOnFail()) { items[i].json = { error: error.message }; continue; } throw error; } } } if (operation === 'getAll') { let additionalFields: IDataObject = {}; for (let i = 0; i < length; i++) { try { const returnAll = this.getNodeParameter('returnAll', i) as boolean; additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (additionalFields.fields) { qs['$select'] = additionalFields.fields; } if (additionalFields.filter) { qs['$filter'] = additionalFields.filter; } const endpoint = '/messages'; if (returnAll === true) { responseData = await microsoftApiRequestAllItems.call( this, 'value', 'GET', endpoint, undefined, qs, ); } else { qs['$top'] = this.getNodeParameter('limit', i) as number; responseData = await microsoftApiRequest.call( this, 'GET', endpoint, undefined, qs, ); responseData = responseData.value; } if (additionalFields.dataPropertyAttachmentsPrefixName) { const prefix = additionalFields.dataPropertyAttachmentsPrefixName as string; const data = await downloadAttachments.call(this, responseData, prefix); returnData.push.apply(returnData, data as unknown as IDataObject[]); } else { returnData.push.apply(returnData, responseData); } } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } if (additionalFields.dataPropertyAttachmentsPrefixName) { return [returnData as INodeExecutionData[]]; } } if (operation === 'move') { for (let i = 0; i < length; i++) { try { const messageId = this.getNodeParameter('messageId', i) as string; const destinationId = this.getNodeParameter('folderId', i) as string; const body: IDataObject = { destinationId, }; responseData = await microsoftApiRequest.call( this, 'POST', `/messages/${messageId}/move`, body, ); returnData.push({ success: true }); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if (operation === 'send') { for (let i = 0; i < length; i++) { try { const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; const toRecipients = this.getNodeParameter('toRecipients', i) as string; const subject = this.getNodeParameter('subject', i) as string; const bodyContent = this.getNodeParameter('bodyContent', i, '') as string; additionalFields.subject = subject; additionalFields.bodyContent = bodyContent || ' '; additionalFields.toRecipients = toRecipients; const saveToSentItems = additionalFields.saveToSentItems === undefined ? true : additionalFields.saveToSentItems; delete additionalFields.saveToSentItems; // Create message object from optional fields const message: IDataObject = createMessage(additionalFields); if (additionalFields.attachments) { const attachments = (additionalFields.attachments as IDataObject).attachments as IDataObject[]; // // Handle attachments message['attachments'] = attachments.map(attachment => { const binaryPropertyName = attachment.binaryPropertyName as string; if (items[i].binary === undefined) { throw new NodeOperationError(this.getNode(), 'No binary data exists on item!'); } //@ts-ignore if (items[i].binary[binaryPropertyName] === undefined) { throw new NodeOperationError(this.getNode(), `No binary data property "${binaryPropertyName}" does not exists on item!`); } const binaryData = (items[i].binary as IBinaryKeyData)[binaryPropertyName]; return { '@odata.type': '#microsoft.graph.fileAttachment', name: binaryData.fileName, contentBytes: binaryData.data, }; }); } const body: IDataObject = { message, saveToSentItems, }; responseData = await microsoftApiRequest.call( this, 'POST', `/sendMail`, body, {}, ); returnData.push({ success: true }); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } } if (resource === 'messageAttachment') { if (operation === 'add') { for (let i = 0; i < length; i++) { try { const messageId = this.getNodeParameter('messageId', i) as string; const binaryPropertyName = this.getNodeParameter('binaryPropertyName', 0) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (items[i].binary === undefined) { throw new NodeOperationError(this.getNode(), 'No binary data exists on item!'); } //@ts-ignore if (items[i].binary[binaryPropertyName] === undefined) { throw new NodeOperationError(this.getNode(), `No binary data property "${binaryPropertyName}" does not exists on item!`); } const binaryData = (items[i].binary as IBinaryKeyData)[binaryPropertyName]; const dataBuffer = await this.helpers.getBinaryDataBuffer(i, binaryPropertyName); const fileName = additionalFields.fileName === undefined ? binaryData.fileName : additionalFields.fileName; if (!fileName) { throw new NodeOperationError(this.getNode(), 'File name is not set. It has either to be set via "Additional Fields" or has to be set on the binary property!'); } // Check if the file is over 3MB big if (dataBuffer.length > 3e6) { // Maximum chunk size is 4MB const chunkSize = 4e6; const body: IDataObject = { AttachmentItem: { attachmentType: 'file', name: fileName, size: dataBuffer.length, }, }; // Create upload session responseData = await microsoftApiRequest.call( this, 'POST', `/messages/${messageId}/attachments/createUploadSession`, body, ); const uploadUrl = responseData.uploadUrl; if (uploadUrl === undefined) { throw new NodeApiError(this.getNode(), responseData, { message: 'Failed to get upload session' }); } for (let bytesUploaded = 0; bytesUploaded < dataBuffer.length; bytesUploaded += chunkSize) { // Upload the file chunk by chunk const nextChunk = Math.min(bytesUploaded + chunkSize, dataBuffer.length); const contentRange = `bytes ${bytesUploaded}-${nextChunk - 1}/${dataBuffer.length}`; const data = dataBuffer.subarray(bytesUploaded, nextChunk); responseData = await this.helpers.request( uploadUrl, { method: 'PUT', headers: { 'Content-Type': 'application/octet-stream', 'Content-Length': data.length, 'Content-Range': contentRange, }, body: data, }); } } else { const body: IDataObject = { '@odata.type': '#microsoft.graph.fileAttachment', name: fileName, contentBytes: binaryData.data, }; responseData = await microsoftApiRequest.call( this, 'POST', `/messages/${messageId}/attachments`, body, {}, ); } returnData.push({ success: true }); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if (operation === 'download') { for (let i = 0; i < length; i++) { try { const messageId = this.getNodeParameter('messageId', i) as string; const attachmentId = this.getNodeParameter('attachmentId', i) as string; const dataPropertyNameDownload = this.getNodeParameter('binaryPropertyName', i) as string; // Get attachment details first const attachmentDetails = await microsoftApiRequest.call( this, 'GET', `/messages/${messageId}/attachments/${attachmentId}`, undefined, { '$select': 'id,name,contentType' }, ); let mimeType: string | undefined; if (attachmentDetails.contentType) { mimeType = attachmentDetails.contentType; } const fileName = attachmentDetails.name; const response = await microsoftApiRequest.call( this, 'GET', `/messages/${messageId}/attachments/${attachmentId}/$value`, undefined, {}, undefined, {}, { encoding: null, resolveWithFullResponse: true }, ); const newItem: INodeExecutionData = { json: items[i].json, binary: {}, }; if (items[i].binary !== undefined) { // Create a shallow copy of the binary data so that the old // data references which do not get changed still stay behind // but the incoming data does not get changed. Object.assign(newItem.binary, items[i].binary); } items[i] = newItem; const data = Buffer.from(response.body as string, 'utf8'); items[i].binary![dataPropertyNameDownload] = await this.helpers.prepareBinaryData(data as unknown as Buffer, fileName, mimeType); } catch (error) { if (this.continueOnFail()) { items[i].json = { error: error.message }; continue; } throw error; } } } if (operation === 'get') { for (let i = 0; i < length; i++) { try { const messageId = this.getNodeParameter('messageId', i) as string; const attachmentId = this.getNodeParameter('attachmentId', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; // Have sane defaults so we don't fetch attachment data in this operation qs['$select'] = 'id,lastModifiedDateTime,name,contentType,size,isInline'; if (additionalFields.fields) { qs['$select'] = additionalFields.fields; } responseData = await microsoftApiRequest.call( this, 'GET', `/messages/${messageId}/attachments/${attachmentId}`, undefined, qs, ); returnData.push(responseData); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if (operation === 'getAll') { for (let i = 0; i < length; i++) { try { const messageId = this.getNodeParameter('messageId', i) as string; const returnAll = this.getNodeParameter('returnAll', i) as boolean; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; // Have sane defaults so we don't fetch attachment data in this operation qs['$select'] = 'id,lastModifiedDateTime,name,contentType,size,isInline'; if (additionalFields.fields) { qs['$select'] = additionalFields.fields; } if (additionalFields.filter) { qs['$filter'] = additionalFields.filter; } const endpoint = `/messages/${messageId}/attachments`; if (returnAll === true) { responseData = await microsoftApiRequestAllItems.call( this, 'value', 'GET', endpoint, undefined, qs, ); } else { qs['$top'] = this.getNodeParameter('limit', i) as number; responseData = await microsoftApiRequest.call( this, 'GET', endpoint, undefined, qs, ); responseData = responseData.value; } returnData.push.apply(returnData, responseData as IDataObject[]); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } } if (resource === 'folder') { if (operation === 'create') { for (let i = 0; i < length; i++) { try { const displayName = this.getNodeParameter('displayName', i) as string; const folderType = this.getNodeParameter('folderType', i) as string; const body: IDataObject = { displayName, }; let endpoint = '/mailFolders'; if (folderType === 'searchFolder') { endpoint = '/mailFolders/searchfolders/childFolders'; const includeNestedFolders = this.getNodeParameter('includeNestedFolders', i); const sourceFolderIds = this.getNodeParameter('sourceFolderIds', i); const filterQuery = this.getNodeParameter('filterQuery', i); Object.assign(body, { '@odata.type': 'microsoft.graph.mailSearchFolder', includeNestedFolders, sourceFolderIds, filterQuery, }); } responseData = await microsoftApiRequest.call( this, 'POST', endpoint, body, ); returnData.push(responseData); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if (operation === 'delete') { for (let i = 0; i < length; i++) { try { const folderId = this.getNodeParameter('folderId', i) as string; responseData = await microsoftApiRequest.call( this, 'DELETE', `/mailFolders/${folderId}`, ); returnData.push({ success: true }); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if (operation === 'get') { for (let i = 0; i < length; i++) { try { const folderId = this.getNodeParameter('folderId', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (additionalFields.fields) { qs['$select'] = additionalFields.fields; } if (additionalFields.filter) { qs['$filter'] = additionalFields.filter; } responseData = await microsoftApiRequest.call( this, 'GET', `/mailFolders/${folderId}`, {}, qs, ); returnData.push(responseData); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if (operation === 'getAll') { for (let i = 0; i < length; i++) { try { const returnAll = this.getNodeParameter('returnAll', i) as boolean; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (additionalFields.fields) { qs['$select'] = additionalFields.fields; } if (additionalFields.filter) { qs['$filter'] = additionalFields.filter; } if (returnAll === true) { responseData = await microsoftApiRequestAllItems.call( this, 'value', 'GET', '/mailFolders', {}, qs, ); } else { qs['$top'] = this.getNodeParameter('limit', i) as number; responseData = await microsoftApiRequest.call( this, 'GET', '/mailFolders', {}, qs, ); responseData = responseData.value; } returnData.push.apply(returnData, responseData as IDataObject[]); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if (operation === 'getChildren') { for (let i = 0; i < length; i++) { try { const folderId = this.getNodeParameter('folderId', i) as string; const returnAll = this.getNodeParameter('returnAll', i) as boolean; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (additionalFields.fields) { qs['$select'] = additionalFields.fields; } if (additionalFields.filter) { qs['$filter'] = additionalFields.filter; } if (returnAll) { responseData = await microsoftApiRequestAllItems.call( this, 'value', 'GET', `/mailFolders/${folderId}/childFolders`, qs, ); } else { qs['$top'] = this.getNodeParameter('limit', i) as number; responseData = await microsoftApiRequest.call( this, 'GET', `/mailFolders/${folderId}/childFolders`, undefined, qs, ); responseData = responseData.value; } returnData.push.apply(returnData, responseData as IDataObject[]); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if (operation === 'update') { for (let i = 0; i < length; i++) { try { const folderId = this.getNodeParameter('folderId', i) as string; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; const body: IDataObject = { ...updateFields, }; responseData = await microsoftApiRequest.call( this, 'PATCH', `/mailFolders/${folderId}`, body, ); returnData.push(responseData); } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } } if (resource === 'folderMessage') { for (let i = 0; i < length; i++) { try { if (operation === 'getAll') { const folderId = this.getNodeParameter('folderId', i) as string; const returnAll = this.getNodeParameter('returnAll', i) as boolean; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (additionalFields.fields) { qs['$select'] = additionalFields.fields; } if (additionalFields.filter) { qs['$filter'] = additionalFields.filter; } const endpoint = `/mailFolders/${folderId}/messages`; if (returnAll) { responseData = await microsoftApiRequestAllItems.call( this, 'value', 'GET', endpoint, qs, ); } else { qs['$top'] = this.getNodeParameter('limit', i) as number; responseData = await microsoftApiRequest.call( this, 'GET', endpoint, undefined, qs, ); responseData = responseData.value; } returnData.push.apply(returnData, responseData as IDataObject[]); } } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } } if ((resource === 'message' && operation === 'getMime') || (resource === 'messageAttachment' && operation === 'download')) { return this.prepareOutputData(items); } else { return [this.helpers.returnJsonArray(returnData)]; } } }
the_stack
import { ContainerGroup, DeFiDRpcError, GenesisKeys, MasterNodeRegTestContainer } from '@defichain/testcontainers' import { ContainerAdapterClient } from '../../container_adapter_client' import { MasternodeState, MasternodeTimeLock } from '../../../src/category/masternode' import { AddressType } from '../../../src/category/wallet' import { RpcApiError } from '@defichain/jellyfish-api-core' describe('Masternode', () => { const container = new MasterNodeRegTestContainer() const client = new ContainerAdapterClient(container) beforeAll(async () => { await container.start() await container.waitForReady() await container.waitForWalletCoinbaseMaturity() }) afterAll(async () => { await container.stop() }) it('should createMasternode with bech32 address', async () => { const balance = await container.call('getbalance') expect(balance >= 2).toBeTruthy() const masternodesLengthBefore = Object.keys(await client.masternode.listMasternodes()).length const ownerAddress = await client.wallet.getNewAddress() const hex = await client.masternode.createMasternode(ownerAddress) expect(typeof hex).toStrictEqual('string') expect(hex.length).toStrictEqual(64) await container.generate(1) const masternodesAfter = await client.masternode.listMasternodes() const masternodesLengthAfter = Object.keys(masternodesAfter).length expect(masternodesLengthAfter).toStrictEqual(masternodesLengthBefore + 1) const mn = Object.values(masternodesAfter).find(mn => mn.ownerAuthAddress === ownerAddress) if (mn === undefined) { throw new Error('should not reach here') } expect(mn.ownerAuthAddress).toStrictEqual(ownerAddress) expect(mn.operatorAuthAddress).toStrictEqual(ownerAddress) expect(typeof mn.creationHeight).toStrictEqual('number') expect(typeof mn.resignHeight).toStrictEqual('number') expect(typeof mn.resignTx).toStrictEqual('string') expect(typeof mn.banTx).toStrictEqual('string') expect(mn.state).toStrictEqual(MasternodeState.PRE_ENABLED) expect(typeof mn.state).toStrictEqual('string') expect(typeof mn.mintedBlocks).toStrictEqual('number') expect(typeof mn.ownerIsMine).toStrictEqual('boolean') expect(mn.ownerIsMine).toStrictEqual(true) expect(typeof mn.localMasternode).toStrictEqual('boolean') expect(typeof mn.operatorIsMine).toStrictEqual('boolean') expect(mn.operatorIsMine).toStrictEqual(true) }) it('should createMasternode with operator bech32 address', async () => { const balance = await container.call('getbalance') expect(balance >= 2).toBeTruthy() const masternodesLengthBefore = Object.keys(await client.masternode.listMasternodes()).length const ownerAddress = await client.wallet.getNewAddress() const operatorAddress = await client.wallet.getNewAddress() const hex = await client.masternode.createMasternode(ownerAddress, operatorAddress) expect(typeof hex).toStrictEqual('string') expect(hex.length).toStrictEqual(64) await container.generate(1) const masternodesAfter = await client.masternode.listMasternodes() const masternodesLengthAfter = Object.keys(masternodesAfter).length expect(masternodesLengthAfter).toStrictEqual(masternodesLengthBefore + 1) const mn = Object.values(masternodesAfter).find(mn => mn.ownerAuthAddress === ownerAddress) if (mn === undefined) { throw new Error('should not reach here') } expect(mn.ownerAuthAddress).toStrictEqual(ownerAddress) expect(mn.operatorAuthAddress).toStrictEqual(operatorAddress) }) it('should createMasternode with timelock', async () => { const balance = await container.call('getbalance') expect(balance >= 2).toBeTruthy() const masternodesLengthBefore = Object.keys(await client.masternode.listMasternodes()).length const ownerAddress = await client.wallet.getNewAddress() const hex = await client.masternode.createMasternode( ownerAddress, '', { utxos: [], timelock: MasternodeTimeLock.FIVE_YEAR } ) expect(typeof hex).toStrictEqual('string') expect(hex.length).toStrictEqual(64) await container.generate(1) const masternodesAfter = await client.masternode.listMasternodes() const masternodesLengthAfter = Object.keys(masternodesAfter).length expect(masternodesLengthAfter).toStrictEqual(masternodesLengthBefore + 1) const mn = Object.values(masternodesAfter).find(mn => mn.ownerAuthAddress === ownerAddress) if (mn === undefined) { throw new Error('should not reach here') } expect(mn.ownerAuthAddress).toStrictEqual(ownerAddress) expect(mn.operatorAuthAddress).toStrictEqual(ownerAddress) expect(mn.timelock).toStrictEqual('5 years') }) it('should createMasternode with utxos', async () => { const balance = await container.call('getbalance') expect(balance >= 2).toBeTruthy() const ownerAddress = await client.wallet.getNewAddress() await container.fundAddress(ownerAddress, 10) const utxos = await container.call('listunspent') const utxo = utxos.find((utxo: any) => utxo.address === ownerAddress) const txid = await client.masternode.createMasternode( ownerAddress, ownerAddress, { utxos: [{ txid: utxo.txid, vout: utxo.vout }] } ) expect(typeof txid).toStrictEqual('string') expect(txid.length).toStrictEqual(64) await container.generate(1) const rawtx = await container.call('getrawtransaction', [txid, true]) expect(rawtx.vin[0].txid).toStrictEqual(utxo.txid) }) it('should createMasternode with legacy address', async () => { const balance = await container.call('getbalance') expect(balance >= 2).toBeTruthy() const masternodesLengthBefore = Object.keys(await client.masternode.listMasternodes()).length const ownerAddress = await client.wallet.getNewAddress('', AddressType.LEGACY) const hex = await client.masternode.createMasternode(ownerAddress) expect(typeof hex).toStrictEqual('string') expect(hex.length).toStrictEqual(64) await container.generate(1) const masternodesAfter = await client.masternode.listMasternodes() const masternodesLengthAfter = Object.keys(masternodesAfter).length expect(masternodesLengthAfter).toStrictEqual(masternodesLengthBefore + 1) const mn = Object.values(masternodesAfter).find(mn => mn.ownerAuthAddress === ownerAddress) if (mn === undefined) { throw new Error('should not reach here') } expect(mn.ownerAuthAddress).toStrictEqual(ownerAddress) }) it('should be failed as collateral locked in mempool', async () => { const ownerAddress = await client.wallet.getNewAddress('', AddressType.LEGACY) const nodeId = await client.masternode.createMasternode(ownerAddress) const rawTx = await client.rawtx.getRawTransaction(nodeId, true) const spendTx = await container.call('createrawtransaction', [ [{ txid: nodeId, vout: 1 }], [{ [ownerAddress]: 1 }] ]) const signedTx = await container.call('signrawtransactionwithwallet', [spendTx]) expect(signedTx.complete).toBeTruthy() const promise = container.call('sendrawtransaction', [signedTx.hex]) await expect(promise).rejects.toThrow(DeFiDRpcError) await expect(promise).rejects.toThrow(`collateral-locked-in-mempool, tried to spend collateral of non-created mn or token ${rawTx.txid}, cheater?`) }) it('should be failed as collateral locked', async () => { const ownerAddress = await client.wallet.getNewAddress('', AddressType.LEGACY) const nodeId = await client.masternode.createMasternode(ownerAddress) await container.generate(1) const rawTx = await client.rawtx.getRawTransaction(nodeId, true) const spendTx = await container.call('createrawtransaction', [ [{ txid: nodeId, vout: 1 }], [{ [ownerAddress]: 1 }] ]) const signedTx = await container.call('signrawtransactionwithwallet', [spendTx]) expect(signedTx.complete).toBeTruthy() const promise = container.call('sendrawtransaction', [signedTx.hex]) await expect(promise).rejects.toThrow(DeFiDRpcError) await expect(promise).rejects.toThrow(`bad-txns-collateral-locked, tried to spend locked collateral for ${rawTx.txid}`) }) it('should be failed as p2sh address is not allowed', async () => { const ownerAddress = await client.wallet.getNewAddress('', AddressType.P2SH_SEGWIT) const promise = client.masternode.createMasternode(ownerAddress) await expect(promise).rejects.toThrow(RpcApiError) await expect(promise).rejects.toThrow(`operatorAddress (${ownerAddress}) does not refer to a P2PKH or P2WPKH address`) }) it('should be failed as invalid address is not allowed', async () => { const invalidAddress = 'INVALID_ADDRESS' const promise = client.masternode.createMasternode(invalidAddress) await expect(promise).rejects.toThrow(RpcApiError) await expect(promise).rejects.toThrow(`operatorAddress (${invalidAddress}) does not refer to a P2PKH or P2WPKH address`) }) it('should be failed as min 2 DFI (regtest) is needed', async () => { const balanceBefore = await container.call('getbalance') await client.wallet.sendToAddress('bcrt1ql0ys2ahu4e9uhjn2l0mehhh4e0mmh7npyhx0re', balanceBefore - 1) const balanceAfter = await container.call('getbalance') expect(balanceAfter < 2).toBeTruthy() const ownerAddress = await client.wallet.getNewAddress('', AddressType.LEGACY) const promise = client.masternode.createMasternode(ownerAddress) await expect(promise).rejects.toThrow('Insufficient funds') }) }) describe('Multinodes masternodes', () => { const group = new ContainerGroup([ new MasterNodeRegTestContainer(GenesisKeys[0]), new MasterNodeRegTestContainer(GenesisKeys[1]) ]) const clientA = new ContainerAdapterClient(group.get(0)) const clientB = new ContainerAdapterClient(group.get(1)) beforeAll(async () => { await group.start() await group.get(0).waitForWalletCoinbaseMaturity() }) afterAll(async () => { await group.stop() }) it('should be failed as address is not owned by the wallet', async () => { const collateral1 = await group.get(1).getNewAddress() const promise = clientA.masternode.createMasternode(collateral1) await expect(promise).rejects.toThrow(RpcApiError) await expect(promise).rejects.toThrow(`Address (${collateral1}) is not owned by the wallet`) }) // timelock 10 -> 4, 5 -> 3, 0 -> 2 it.skip('should createMasternode targetMultiplier checker', async () => { // TODO(canonbrother): due to the sporadic flaky nature of anchor test, we have disabled it now so that it does not // impact our CI workflow const addrA0 = await clientA.wallet.getNewAddress('mnA0', AddressType.LEGACY) const mnIdA0 = await clientA.masternode.createMasternode(addrA0) await group.waitForMempoolSync(mnIdA0) const addrA5 = await clientA.wallet.getNewAddress('mnA5', AddressType.LEGACY) const mnIdA5 = await clientA.masternode.createMasternode(addrA5, '', { utxos: [], timelock: MasternodeTimeLock.FIVE_YEAR }) await group.waitForMempoolSync(mnIdA5) const addrA10 = await clientA.wallet.getNewAddress('mnA10', AddressType.LEGACY) const mnIdA10 = await clientA.masternode.createMasternode(addrA10, '', { utxos: [], timelock: MasternodeTimeLock.TEN_YEAR }) await group.waitForMempoolSync(mnIdA10) const addrB0 = await clientB.wallet.getNewAddress('mnB0', AddressType.LEGACY) const mnIdB0 = await clientB.masternode.createMasternode(addrB0) await group.waitForMempoolSync(mnIdB0) { await group.get(0).generate(1) await group.get(1).generate(1) await group.waitForSync() const mnA0 = (await clientA.masternode.getMasternode(mnIdA0))[mnIdA0] expect(mnA0.targetMultipliers).toStrictEqual(undefined) const mnA5 = (await clientA.masternode.getMasternode(mnIdA5))[mnIdA5] expect(mnA5.targetMultipliers).toStrictEqual(undefined) const mnA10 = (await clientA.masternode.getMasternode(mnIdA10))[mnIdA10] expect(mnA10.targetMultipliers).toStrictEqual(undefined) const mnB0 = (await clientB.masternode.getMasternode(mnIdB0))[mnIdB0] expect(mnB0.targetMultipliers).toStrictEqual(undefined) } { await group.get(0).generate(20) await group.get(1).generate(20) await group.waitForSync() const mnA0 = (await clientA.masternode.getMasternode(mnIdA0))[mnIdA0] expect(mnA0.targetMultipliers).toStrictEqual([1, 1]) const mnA5 = (await clientA.masternode.getMasternode(mnIdA5))[mnIdA5] expect(mnA5.targetMultipliers).toStrictEqual([1, 1, 1]) const mnA10 = (await clientA.masternode.getMasternode(mnIdA10))[mnIdA10] expect(mnA10.targetMultipliers).toStrictEqual([1, 1, 1, 1]) const mnB0 = (await clientB.masternode.getMasternode(mnIdB0))[mnIdB0] expect(mnB0.targetMultipliers).toStrictEqual([1, 1]) } { // time travel a day await clientA.misc.setMockTime(Date.now() + 1e3 * 60 * 60 * 24) await clientB.misc.setMockTime(Date.now() + 1e3 * 60 * 60 * 24) await group.get(0).generate(1) await group.get(1).generate(1) await group.waitForSync() const mnA0 = (await clientA.masternode.getMasternode(mnIdA0))[mnIdA0] expect(mnA0.targetMultipliers).toBeDefined() expect(mnA0.targetMultipliers?.length).toStrictEqual(2) expect(mnA0.targetMultipliers?.every(tm => tm >= 4)).toBeTruthy() // [4, 4] const mnA5 = (await clientA.masternode.getMasternode(mnIdA5))[mnIdA5] expect(mnA5.targetMultipliers).toBeDefined() expect(mnA5.targetMultipliers?.length).toStrictEqual(3) expect(mnA5.targetMultipliers?.every(tm => tm >= 4)).toBeTruthy() // [4, 4, 4] const mnA10 = (await clientA.masternode.getMasternode(mnIdA10))[mnIdA10] expect(mnA10.targetMultipliers).toBeDefined() expect(mnA10.targetMultipliers?.length).toStrictEqual(4) expect(mnA10.targetMultipliers?.every(tm => tm >= 4)).toBeTruthy() // [4, 4, 4, 4] const mnB0 = (await clientB.masternode.getMasternode(mnIdB0))[mnIdB0] expect(mnB0.targetMultipliers).toBeDefined() expect(mnB0.targetMultipliers?.length).toStrictEqual(2) expect(mnB0.targetMultipliers?.every(tm => tm >= 4)).toBeTruthy() // [4, 4] } { // time travel a week await clientA.misc.setMockTime(Date.now() + 1e3 * 60 * 60 * 24 * 7) await clientB.misc.setMockTime(Date.now() + 1e3 * 60 * 60 * 24 * 7) await group.get(0).generate(1) await group.get(1).generate(1) await group.waitForSync() const mnA0 = (await clientA.masternode.getMasternode(mnIdA0))[mnIdA0] expect(mnA0.targetMultipliers).toBeDefined() expect(mnA0.targetMultipliers?.length).toStrictEqual(2) expect(mnA0.targetMultipliers?.every(tm => tm >= 28)).toBeTruthy() // [28, 28] const mnA5 = (await clientA.masternode.getMasternode(mnIdA5))[mnIdA5] expect(mnA5.targetMultipliers).toBeDefined() expect(mnA5.targetMultipliers?.length).toStrictEqual(3) expect(mnA5.targetMultipliers?.every(tm => tm >= 28)).toBeTruthy() // [28, 28, 28] const mnA10 = (await clientA.masternode.getMasternode(mnIdA10))[mnIdA10] expect(mnA10.targetMultipliers).toBeDefined() expect(mnA10.targetMultipliers?.length).toStrictEqual(4) expect(mnA10.targetMultipliers?.every(tm => tm >= 28)).toBeTruthy() // [28, 28, 28, 28] const mnB0 = (await clientB.masternode.getMasternode(mnIdB0))[mnIdB0] expect(mnB0.targetMultipliers).toBeDefined() expect(mnB0.targetMultipliers?.length).toStrictEqual(2) expect(mnB0.targetMultipliers?.every(tm => tm >= 28)).toBeTruthy() // [28, 28] } { // time travel 30 days, max tm - 57 await clientA.misc.setMockTime(Date.now() + 1e3 * 60 * 60 * 24 * 30) await clientB.misc.setMockTime(Date.now() + 1e3 * 60 * 60 * 24 * 30) await group.get(0).generate(1) await group.get(1).generate(1) await group.waitForSync() const mnA0 = (await clientA.masternode.getMasternode(mnIdA0))[mnIdA0] expect(mnA0.targetMultipliers).toStrictEqual([57, 57]) const mnA5 = (await clientA.masternode.getMasternode(mnIdA5))[mnIdA5] expect(mnA5.targetMultipliers).toStrictEqual([57, 57, 57]) const mnA10 = (await clientA.masternode.getMasternode(mnIdA10))[mnIdA10] expect(mnA10.targetMultipliers).toStrictEqual([57, 57, 57, 57]) const mnB0 = (await clientB.masternode.getMasternode(mnIdB0))[mnIdB0] expect(mnB0.targetMultipliers).toStrictEqual([57, 57]) } }) })
the_stack
import { AggregatedResult, TestResult } from "@jest/test-result"; import { Config } from "@jest/types"; import dateformat from "dateformat"; import fs from "fs"; import mkdirp from "mkdirp"; import path from "path"; import { IJestHTMLReporterConfig, IJestHTMLReporterConfigOptions, IJestHTMLReporterConsole, JestHTMLReporterProps, JestHTMLReporterSortType, } from "src/types"; import stripAnsi from "strip-ansi"; import xmlbuilder, { XMLElement } from "xmlbuilder"; import sorting from "./sorting"; class HTMLReporter { public testData: AggregatedResult; public consoleLogList: IJestHTMLReporterConsole[]; public jestConfig: Config.GlobalConfig; public config: IJestHTMLReporterConfig; constructor(data: JestHTMLReporterProps) { this.testData = data.testData; this.jestConfig = data.jestConfig; this.consoleLogList = data.consoleLogs; this.setupConfig(data.options); } public async generate() { try { const report = await this.renderTestReport(); const outputPath = this.replaceRootDirInPath( this.jestConfig ? this.jestConfig.rootDir : "", this.getConfigValue("outputPath") as string ); await mkdirp(path.dirname(outputPath)); if (this.getConfigValue("append") as boolean) { await this.appendToFile(outputPath, report.toString()); } else { await fs.writeFileSync(outputPath, report.toString()); } this.logMessage("success", `Report generated (${outputPath})`); return report; } catch (e) { this.logMessage("error", e); } } public async renderTestReport() { // Generate the content of the test report const reportContent = await this.renderTestReportContent(); // -- // Boilerplate Option if (!!this.getConfigValue("boilerplate")) { const boilerplateContent = await fs.readFileSync( this.getConfigValue("boilerplate") as string, "utf8" ); return boilerplateContent.replace( "{jesthtmlreporter-content}", reportContent && reportContent.toString() ); } // -- // Create HTML and apply reporter content const report = xmlbuilder.create({ html: {} }); const headTag = report.ele("head"); headTag.ele("meta", { charset: "utf-8" }); headTag.ele("title", {}, this.getConfigValue("pageTitle")); // Default to the currently set theme let stylesheetFilePath: string = path.join( __dirname, `../style/${this.getConfigValue("theme")}.css` ); // Overriding stylesheet if (this.getConfigValue("styleOverridePath")) { stylesheetFilePath = this.getConfigValue("styleOverridePath") as string; } // Decide whether to inline the CSS or not const inlineCSS: boolean = !this.getConfigValue("useCssFile") && !!!this.getConfigValue("styleOverridePath"); if (inlineCSS) { const stylesheetContent = await fs.readFileSync( stylesheetFilePath, "utf8" ); headTag.raw(`<style type="text/css">${stylesheetContent}</style>`); } else { headTag.ele("link", { rel: "stylesheet", type: "text/css", href: stylesheetFilePath, }); } const reportBody = report.ele("body"); // Add the test report to the body if (reportContent) { reportBody.raw(reportContent.toString()); } // Add any given custom script to the end of the body if (!!this.getConfigValue("customScriptPath")) { reportBody.raw( `<script src="${this.getConfigValue("customScriptPath")}"></script>` ); } return report; } public renderTestSuiteInfo(parent: XMLElement, suite: TestResult) { const suiteInfo = parent.ele("div", { class: "suite-info" }); // Suite Path suiteInfo.ele("div", { class: "suite-path" }, suite.testFilePath); // Suite execution time const executionTime = (suite.perfStats.end - suite.perfStats.start) / 1000; suiteInfo.ele( "div", { class: `suite-time${ executionTime > (this.getConfigValue("executionTimeWarningThreshold") as number) ? " warn" : "" }`, }, `${executionTime}s` ); } public renderSuiteFailure(parent: XMLElement, suite: TestResult, i: number) { const suiteContainer = parent.ele("div", { id: `suite-${i + 1}`, class: "suite-container", }); // Suite Information this.renderTestSuiteInfo(suiteContainer, suite); // Test Container const suiteTests = suiteContainer.ele("div", { class: "suite-tests", }); const testResult = suiteTests.ele("div", { class: "test-result failed", }); const failureMsgDiv = testResult.ele( "div", { class: "failureMessages suiteFailure", }, " " ); failureMsgDiv.ele( "pre", { class: "failureMsg" }, stripAnsi(suite.failureMessage) ); } public async renderTestReportContent() { try { if (!this.testData || Object.entries(this.testData).length === 0) { throw Error("No test data provided"); } // HTML Body const reportBody: XMLElement = xmlbuilder.begin().element("div", { id: "jesthtml-content", }); /** * Page Header */ const header = reportBody.ele("header"); // Page Title header.ele("h1", { id: "title" }, this.getConfigValue("pageTitle")); // Logo const logo = this.getConfigValue("logo"); if (logo) { header.ele("img", { id: "logo", src: logo }); } /** * Meta-Data */ const metaDataContainer = reportBody.ele("div", { id: "metadata-container", }); // Timestamp if (this.testData.startTime && !isNaN(this.testData.startTime)) { const timestamp = new Date(this.testData.startTime); if (timestamp) { const formattedTimestamp = dateformat( timestamp, this.getConfigValue("dateFormat") as string ); metaDataContainer.ele( "div", { id: "timestamp" }, `Started: ${formattedTimestamp}` ); } } // Summary const summaryContainer = metaDataContainer.ele("div", { id: "summary" }); // Suite Summary const suiteSummary = summaryContainer.ele("div", { id: "suite-summary" }); suiteSummary.ele( "div", { class: "summary-total" }, `Suites (${this.testData.numTotalTestSuites})` ); suiteSummary.ele( "div", { class: `summary-passed${ this.testData.numPassedTestSuites === 0 ? " summary-empty" : "" }`, }, `${this.testData.numPassedTestSuites} passed` ); suiteSummary.ele( "div", { class: `summary-failed${ this.testData.numFailedTestSuites === 0 ? " summary-empty" : "" }`, }, `${this.testData.numFailedTestSuites} failed` ); suiteSummary.ele( "div", { class: `summary-pending${ this.testData.numPendingTestSuites === 0 ? " summary-empty" : "" }`, }, `${this.testData.numPendingTestSuites} pending` ); if ( this.testData.snapshot && this.testData.snapshot.unchecked > 0 && this.getConfigValue("includeObsoleteSnapshots") ) { suiteSummary.ele( "div", { class: "summary-obsolete-snapshots", }, `${this.testData.snapshot.unchecked} obsolete snapshots` ); } // Test Summary const testSummary = summaryContainer.ele("div", { id: "test-summary" }); testSummary.ele( "div", { class: "summary-total" }, `Tests (${this.testData.numTotalTests})` ); testSummary.ele( "div", { class: `summary-passed${ this.testData.numPassedTests === 0 ? " summary-empty" : "" }`, }, `${this.testData.numPassedTests} passed` ); testSummary.ele( "div", { class: `summary-failed${ this.testData.numFailedTests === 0 ? " summary-empty" : "" }`, }, `${this.testData.numFailedTests} failed` ); testSummary.ele( "div", { class: `summary-pending${ this.testData.numPendingTests === 0 ? " summary-empty" : "" }`, }, `${this.testData.numPendingTests} pending` ); /** * Apply any given sorting method to the test results */ const sortedTestResults = sorting( this.testData.testResults, this.getConfigValue("sort") as JestHTMLReporterSortType ); /** * Setup ignored test result statuses */ const statusIgnoreFilter = this.getConfigValue( "statusIgnoreFilter" ) as string; let ignoredStatuses: string[] = []; if (statusIgnoreFilter) { ignoredStatuses = statusIgnoreFilter .replace(/\s/g, "") .toLowerCase() .split(","); } /** * Test Suites */ if (sortedTestResults) { sortedTestResults.map((suite, i) => { // Ignore this suite if there are no results if (!suite.testResults || suite.testResults.length <= 0) { if ( suite.failureMessage && this.getConfigValue("includeSuiteFailure") ) { this.renderSuiteFailure(reportBody, suite, i); } return; } const suiteContainer = reportBody.ele("div", { id: `suite-${i + 1}`, class: "suite-container", }); // Suite Information this.renderTestSuiteInfo(suiteContainer, suite); // Test Container const suiteTests = suiteContainer.ele("div", { class: "suite-tests", }); // Test Results suite.testResults // Filter out the test results with statuses that equals the statusIgnoreFilter .filter((s) => !ignoredStatuses.includes(s.status)) .forEach(async (test) => { const testResult = suiteTests.ele("div", { class: `test-result ${test.status}`, }); // Test Info const testInfo = testResult.ele("div", { class: "test-info" }); // Suite Name testInfo.ele( "div", { class: "test-suitename" }, test.ancestorTitles && test.ancestorTitles.length > 0 ? test.ancestorTitles.join(" > ") : " " ); // Test Title testInfo.ele("div", { class: "test-title" }, test.title); // Test Status testInfo.ele("div", { class: "test-status" }, test.status); // Test Duration testInfo.ele( "div", { class: "test-duration" }, `${test.duration / 1000}s` ); // Test Failure Messages if ( test.failureMessages && test.failureMessages.length > 0 && this.getConfigValue("includeFailureMsg") ) { const failureMsgDiv = testResult.ele( "div", { class: "failureMessages", }, " " ); test.failureMessages.forEach((failureMsg) => { failureMsgDiv.ele( "pre", { class: "failureMsg" }, stripAnsi(failureMsg) ); }); } }); // All console.logs caught during the test run if ( this.consoleLogList && this.consoleLogList.length > 0 && this.getConfigValue("includeConsoleLog") ) { this.renderSuiteConsoleLogs(suite, suiteContainer); } if ( suite.snapshot && suite.snapshot.unchecked > 0 && this.getConfigValue("includeObsoleteSnapshots") ) { this.renderSuiteObsoleteSnapshots(suiteContainer, suite); } }); } return reportBody; } catch (e) { this.logMessage("error", e); } } public renderSuiteConsoleLogs( suite: TestResult, suiteContainer: xmlbuilder.XMLElement ) { // Filter out the logs for this test file path const filteredConsoleLogs = this.consoleLogList.find( (logs) => logs.filePath === suite.testFilePath ); if (filteredConsoleLogs && filteredConsoleLogs.logs.length > 0) { // Console Log Container const consoleLogContainer = suiteContainer.ele("div", { class: "suite-consolelog", }); // Console Log Header consoleLogContainer.ele( "div", { class: "suite-consolelog-header" }, "Console Log" ); // Apply the logs to the body filteredConsoleLogs.logs.forEach((log) => { const logElement = consoleLogContainer.ele("div", { class: "suite-consolelog-item", }); logElement.ele( "pre", { class: "suite-consolelog-item-origin" }, stripAnsi(log.origin) ); logElement.ele( "pre", { class: "suite-consolelog-item-message" }, stripAnsi(log.message) ); }); } } public renderSuiteObsoleteSnapshots( suiteContainer: xmlbuilder.XMLElement, suite: TestResult ) { // Obsolete snapshots Container const snapshotContainer = suiteContainer.ele("div", { class: "suite-obsolete-snapshots", }); // Obsolete snapshots Header snapshotContainer.ele( "div", { class: "suite-obsolete-snapshots-header" }, "Obsolete snapshots" ); const keysElement = snapshotContainer.ele("div", { class: "suite-obsolete-snapshots-item", }); keysElement.ele( "pre", { class: "suite-obsolete-snapshots-item-message" }, suite.snapshot.uncheckedKeys.join("\n") ); } /** * Fetch and setup configuration */ public setupConfig( options: IJestHTMLReporterConfigOptions ): IJestHTMLReporterConfig { // Extract config values and make sure that the config object actually exist const { append, boilerplate, customScriptPath, dateFormat, executionTimeWarningThreshold, logo, includeConsoleLog, includeFailureMsg, includeSuiteFailure, includeObsoleteSnapshots, outputPath, pageTitle, theme, sort, statusIgnoreFilter, styleOverridePath, useCssFile, } = options || {}; this.config = { append: { defaultValue: false, environmentVariable: "JEST_HTML_REPORTER_APPEND", configValue: append, }, boilerplate: { defaultValue: null, environmentVariable: "JEST_HTML_REPORTER_BOILERPLATE", configValue: boilerplate, }, customScriptPath: { defaultValue: null, environmentVariable: "JEST_HTML_REPORTER_CUSTOM_SCRIPT_PATH", configValue: customScriptPath, }, dateFormat: { defaultValue: "yyyy-mm-dd HH:MM:ss", environmentVariable: "JEST_HTML_REPORTER_DATE_FORMAT", configValue: dateFormat, }, executionTimeWarningThreshold: { defaultValue: 5, environmentVariable: "JEST_HTML_REPORTER_EXECUTION_TIME_WARNING_THRESHOLD", configValue: executionTimeWarningThreshold, }, logo: { defaultValue: null, environmentVariable: "JEST_HTML_REPORTER_LOGO", configValue: logo, }, includeFailureMsg: { defaultValue: false, environmentVariable: "JEST_HTML_REPORTER_INCLUDE_FAILURE_MSG", configValue: includeFailureMsg, }, includeSuiteFailure: { defaultValue: false, environmentVariable: "JEST_HTML_REPORTER_INCLUDE_SUITE_FAILURE", configValue: includeSuiteFailure, }, includeObsoleteSnapshots: { defaultValue: false, environmentVariable: "JEST_HTML_REPORTER_INCLUDE_OBSOLETE_SNAPSHOTS", configValue: includeObsoleteSnapshots, }, includeConsoleLog: { defaultValue: false, environmentVariable: "JEST_HTML_REPORTER_INCLUDE_CONSOLE_LOG", configValue: includeConsoleLog, }, outputPath: { defaultValue: path.join(process.cwd(), "test-report.html"), environmentVariable: "JEST_HTML_REPORTER_OUTPUT_PATH", configValue: outputPath, }, pageTitle: { defaultValue: "Test Report", environmentVariable: "JEST_HTML_REPORTER_PAGE_TITLE", configValue: pageTitle, }, theme: { defaultValue: "defaultTheme", environmentVariable: "JEST_HTML_REPORTER_THEME", configValue: theme, }, sort: { defaultValue: null, environmentVariable: "JEST_HTML_REPORTER_SORT", configValue: sort, }, statusIgnoreFilter: { defaultValue: null, environmentVariable: "JEST_HTML_REPORTER_STATUS_FILTER", configValue: statusIgnoreFilter, }, styleOverridePath: { defaultValue: null, environmentVariable: "JEST_HTML_REPORTER_STYLE_OVERRIDE_PATH", configValue: styleOverridePath, }, useCssFile: { defaultValue: false, environmentVariable: "JEST_HTML_REPORTER_USE_CSS_FILE", configValue: useCssFile, }, }; // Attempt to collect and assign config settings from jesthtmlreporter.config.json try { const jesthtmlreporterconfig = fs.readFileSync( path.join(process.cwd(), "jesthtmlreporter.config.json"), "utf8" ); if (jesthtmlreporterconfig) { const parsedConfig = JSON.parse(jesthtmlreporterconfig); for (const key of Object.keys(parsedConfig)) { if (this.config[key as keyof IJestHTMLReporterConfig]) { this.config[key as keyof IJestHTMLReporterConfig].configValue = parsedConfig[key]; } } return this.config; } } catch (e) { /** do nothing */ } // If above method did not work we attempt to check package.json try { const packageJson = fs.readFileSync( path.join(process.cwd(), "package.json"), "utf8" ); if (packageJson) { const parsedConfig = JSON.parse(packageJson)["jest-html-reporter"]; for (const key of Object.keys(parsedConfig)) { if (this.config[key as keyof IJestHTMLReporterConfig]) { this.config[key as keyof IJestHTMLReporterConfig].configValue = parsedConfig[key]; } } return this.config; } } catch (e) { /** do nothing */ } } /** * Returns the configurated value from the config in the following priority order: * Environment Variable > JSON configured value > Default value * @param key */ public getConfigValue(key: keyof IJestHTMLReporterConfig) { const option = this.config[key]; if (!option) { return; } if (process.env[option.environmentVariable]) { return process.env[option.environmentVariable]; } return option.configValue || option.defaultValue; } /** * Appends the report to the given file and attempts to integrate the report into any existing HTML. * @param filePath * @param content */ public async appendToFile(filePath: string, content: any) { let parsedContent = content; // Check if the file exists or not const fileToAppend = await fs.readFileSync(filePath, "utf8"); // The file exists - we need to strip all unecessary html if (fileToAppend) { const contentSearch = /<body>(.*?)<\/body>/gm.exec(content); if (contentSearch) { const [strippedContent] = contentSearch; parsedContent = strippedContent; } // Then we need to add the stripped content just before the </body> tag let newContent = fileToAppend; const closingBodyTag = /<\/body>/gm.exec(fileToAppend); const indexOfClosingBodyTag = closingBodyTag ? closingBodyTag.index : 0; newContent = [ fileToAppend.slice(0, indexOfClosingBodyTag), parsedContent, fileToAppend.slice(indexOfClosingBodyTag), ].join(""); return fs.writeFileSync(filePath, newContent); } return fs.appendFileSync(filePath, parsedContent); } /** * Replaces <rootDir> in the file path with the actual path, as performed within Jest * Copy+paste from https://github.com/facebook/jest/blob/master/packages/jest-config/src/utils.ts * @param rootDir * @param filePath */ public replaceRootDirInPath( rootDir: Config.Path, filePath: Config.Path ): string { if (!/^<rootDir>/.test(filePath)) { return filePath; } return path.resolve( rootDir, path.normalize("./" + filePath.substr("<rootDir>".length)) ); } /** * Method for logging to the terminal * @param type * @param message * @param ignoreConsole */ public logMessage( type: "default" | "success" | "error" = "default", message: string ) { const logTypes = { default: "\x1b[37m%s\x1b[0m", success: "\x1b[32m%s\x1b[0m", error: "\x1b[31m%s\x1b[0m", }; const logColor = !logTypes[type] ? logTypes.default : logTypes[type]; const logMsg = `jest-html-reporter >> ${message}`; // Let's log messages to the terminal only if we aren't testing this very module if (process.env.JEST_WORKER_ID === undefined) { console.log(logColor, logMsg); } return { logColor, logMsg }; // Return for testing purposes } } export default HTMLReporter;
the_stack
import React, { useCallback } from 'react' import styled from '../../../../design/lib/styled' // import { useSet } from 'react-use' import { usePage } from '../../../../cloud/lib/stores/pageStore' import { PageStoreWithTeam } from '../../../../cloud/interfaces/pageStore' // import Icon from '../../../../shared/components/atoms/Icon' // import { mdiChevronRight, mdiCheck, mdiChevronDown } from '@mdi/js' // import Banner from '../../../../shared/components/atoms/Banner' import { SettingsTabTypes } from './types' import ModalContainer from './atoms/ModalContainer' import NavigationBarBackButton from '../../atoms/NavigationBarBackButton' import Button from '../../../../design/components/atoms/Button' import { sendPostMessage } from '../../../lib/nativeMobile' import { boostHubBaseUrl } from '../../../../cloud/lib/consts' import MobileFormControl from '../../atoms/MobileFormControl' // type TabType = 'free' | 'standard' | 'pro' interface SpaceUpgradeTabProps { setActiveTab: (tabType: SettingsTabTypes | null) => void } const SpaceUpgradeTab = ({ setActiveTab }: SpaceUpgradeTabProps) => { const { subscription, // currentUserPermissions } = usePage<PageStoreWithTeam>() // const [, { has: isTabOpen, toggle: toggleTab }] = useSet<TabType>() const openWebApp = useCallback(() => { sendPostMessage({ type: 'open-link', url: boostHubBaseUrl, }) }, []) return ( <ModalContainer left={<NavigationBarBackButton onClick={() => setActiveTab(null)} />} title='Settings' closeLabel='Done' > <Container> <div className='temp'> <p> Currently updating subscription plan is not available from mobile app. Please use the link below to update it. </p> <p> Current subscription plan:{' '} {subscription == null ? 'Not Available' : `${subscription.plan} (${subscription.status})`} </p> <MobileFormControl> <Button onClick={openWebApp}> Open Web App ({boostHubBaseUrl}) </Button> </MobileFormControl> </div> </Container> </ModalContainer> ) // if ( // currentUserPermissions == null || // currentUserPermissions.role !== 'admin' // ) { // return ( // <Container> // <Banner variant='danger'>Only Admin can change plan</Banner> // </Container> // ) // } // return ( // <ModalContainer // left={<NavigationBarBackButton onClick={() => setActiveTab(null)} />} // title='Settings' // closeLabel='Done' // > // <Container> // <div className='planItem'> // <div className='planItem__header'> // <button // className='planItem__header__titleButton' // onClick={() => toggleTab('free')} // > // <Icon // size={20} // className='planItem__header__titleButton__foldIcon' // path={isTabOpen('free') ? mdiChevronDown : mdiChevronRight} // /> // Free // </button> // <button // className='planItem__header__upgradeButton' // disabled={subscription == null} // onClick={() => setActiveTab('space-upgrade-confirm-free')} // > // {subscription == null ? 'Current' : 'Downgrade'} // </button> // </div> // {isTabOpen('free') && ( // <div className='planItem__body'> // <div className='planItem__body__price'> // <span className='planItem__body__price__value'>$0</span> // </div> // <ul className='planItem__body__featureList'> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} /> // 10 docs per team // </li> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} /> // Unlimited members // </li> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} /> // 100MB storage per member // </li> // </ul> // <a // className='planItem__body__learnMoreButton' // href='https://boostnote.io/pricing' // target='_blank' // rel='noopener noreferrer' // > // Learn more // </a> // </div> // )} // </div> // <div className='planItem'> // <div className='planItem__header'> // <button // className='planItem__header__titleButton' // onClick={() => toggleTab('standard')} // > // <Icon // className='planItem__header__titleButton__foldIcon' // path={isTabOpen('standard') ? mdiChevronDown : mdiChevronRight} // /> // Standard // </button> // <button // className='planItem__header__upgradeButton' // disabled={ // subscription != null && subscription.plan === 'standard' // } // onClick={() => setActiveTab('space-upgrade-confirm-standard')} // > // {subscription == null // ? 'Upgrade' // : subscription.plan === 'pro' // ? 'Downgrade' // : 'Current'} // </button> // </div> // {isTabOpen('standard') && ( // <div className='planItem__body'> // <div className='planItem__body__price'> // <span className='planItem__body__price__value'>$3</span> // <span className='planItem__body__price__unit'> // per person per month // </span> // </div> // <ul className='planItem__body__featureList'> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} /> // Collaborative workspace // </li> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} /> // Unlimited documents // </li> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} /> // Unlimited members // </li> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} /> // 1GB storage per member // </li> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} />7 days revision history // </li> // </ul> // <a // className='planItem__body__learnMoreButton' // href='https://boostnote.io/pricing' // target='_blank' // rel='noopener noreferrer' // > // Learn more // </a> // </div> // )} // </div> // <div className='planItem'> // <div className='planItem__header'> // <button // className='planItem__header__titleButton' // onClick={() => toggleTab('pro')} // > // <Icon // size={20} // className='planItem__header__titleButton__foldIcon' // path={isTabOpen('pro') ? mdiChevronDown : mdiChevronRight} // /> // Pro // </button> // <button // className='planItem__header__upgradeButton' // disabled={subscription != null && subscription.plan === 'pro'} // onClick={() => setActiveTab('space-upgrade-confirm-pro')} // > // {subscription == null || subscription.plan === 'standard' // ? 'Upgrade' // : 'Current'} // </button> // </div> // {isTabOpen('pro') && ( // <div className='planItem__body'> // <div className='planItem__body__price'> // <span className='planItem__body__price__value'>$8</span> // <span className='planItem__body__price__unit'> // per person per month // </span> // </div> // <ul className='planItem__body__featureList'> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} /> // Everything in Standard // </li> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} /> // Guest invite // </li> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} /> // Password/Expiration date for sharing // </li> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} /> // 10GB storage per member // </li> // <li className='planItem__body__featureList__item'> // <Icon size={20} path={mdiCheck} /> // Priority support // </li> // </ul> // <a // className='planItem__body__learnMoreButton' // href='https://boostnote.io/pricing' // target='_blank' // rel='noopener noreferrer' // > // Learn more // </a> // </div> // )} // </div> // </Container> // </ModalContainer> // ) } export default SpaceUpgradeTab const Container = styled.div` padding: ${({ theme }) => theme.sizes.spaces.sm}px 0; .temp { padding: ${({ theme }) => theme.sizes.spaces.sm}px; } .planItem { } .planItem__header { height: 30px; display: flex; align-items: center; padding: 0 ${({ theme }) => theme.sizes.spaces.sm}px; width: 100%; border: none; border-bottom: solid 1px ${({ theme }) => theme.colors.border.main}; background-color: ${({ theme }) => theme.colors.background.primary}; color: ${({ theme }) => theme.colors.text.secondary}; } .planItem__header__titleButton { padding: 0; height: 30px; flex: 1; display: flex; align-items: center; border: none; background-color: transparent; color: ${({ theme }) => theme.colors.text.secondary}; } .planItem__header__titleButton__foldIcon { margin-right: ${({ theme }) => theme.sizes.spaces.xsm}px; } .planItem__header__upgradeButton { padding: 0; height: 30px; border: none; background-color: transparent; color: ${({ theme }) => theme.colors.text.link}; &:disabled { color: ${({ theme }) => theme.colors.text.disabled}; } } .planItem__body { padding-bottom: ${({ theme }) => theme.sizes.spaces.sm}px; } .planItem__body__price { padding: ${({ theme }) => theme.sizes.spaces.sm}px ${({ theme }) => theme.sizes.spaces.sm}px; } .planItem__body__price__value { padding-right: ${({ theme }) => theme.sizes.spaces.sm}px; color: ${({ theme }) => theme.colors.text.primary}; font-size: ${({ theme }) => theme.sizes.fonts.l}px; font-weight: bold; } .planItem__body__price__unit { color: ${({ theme }) => theme.colors.text.subtle}; font-weight: bold; } .planItem__body__featureList { list-style: none; padding: 0; margin: 0; } .planItem__body__featureList__item { display: flex; align-items: center; padding: ${({ theme }) => theme.sizes.spaces.sm}px ${({ theme }) => theme.sizes.spaces.sm}px; } .planItem__body__learnMoreButton { display: inline-block; padding: ${({ theme }) => theme.sizes.spaces.sm}px ${({ theme }) => theme.sizes.spaces.sm}px; border: none; background-color: transparent; color: ${({ theme }) => theme.colors.text.subtle}; text-decoration: none; } `
the_stack
import { validateAuthorizationHeader, getAuthenticationScopes, AuthScopeValues } from './authentication' import { ValidationError, DoesNotExist, PayloadTooLargeError, PreconditionFailedError } from './errors' import { ProofChecker } from './ProofChecker' import { AuthTimestampCache } from './revocations' import { Readable } from 'stream' import { DriverModel, PerformWriteArgs, WriteResult, PerformRenameArgs, PerformDeleteArgs, PerformListFilesArgs, ListFilesStatResult, ListFilesResult } from './driverModel' import { HubConfigInterface } from './config' import { logger, generateUniqueID, bytesToMegabytes, megabytesToBytes, monitorStreamProgress } from './utils' export class HubServer { driver: DriverModel proofChecker: ProofChecker whitelist?: Array<string> serverName: string readURL?: string requireCorrectHubUrl: boolean validHubUrls?: Array<string> authTimestampCache: AuthTimestampCache config: HubConfigInterface maxFileUploadSizeMB: number maxFileUploadSizeBytes: number constructor(driver: DriverModel, proofChecker: ProofChecker, config: HubConfigInterface) { this.driver = driver this.proofChecker = proofChecker this.config = config this.whitelist = config.whitelist this.serverName = config.serverName this.validHubUrls = config.validHubUrls this.readURL = config.readURL this.requireCorrectHubUrl = config.requireCorrectHubUrl || false this.authTimestampCache = new AuthTimestampCache(this.getReadURLPrefix(), driver, config.authTimestampCacheSize) this.maxFileUploadSizeMB = (config.maxFileUploadSize || 20) // megabytes to bytes this.maxFileUploadSizeBytes = megabytesToBytes(this.maxFileUploadSizeMB) } async handleAuthBump(address: string, oldestValidTimestamp: number, requestHeaders: { authorization?: string }) { this.validate(address, requestHeaders) await this.authTimestampCache.setAuthTimestamp(address, oldestValidTimestamp) } // throws exception on validation error // otherwise returns void. validate(address: string, requestHeaders: { authorization?: string }, oldestValidTokenTimestamp?: number) { const signingAddress = validateAuthorizationHeader(requestHeaders.authorization, this.serverName, address, this.requireCorrectHubUrl, this.validHubUrls, oldestValidTokenTimestamp) if (this.whitelist && !(this.whitelist.includes(signingAddress))) { throw new ValidationError(`Address ${signingAddress} not authorized for writes`) } } async handleListFiles(address: string, page: string | undefined, stat: boolean, requestHeaders: { authorization?: string }) { const oldestValidTokenTimestamp = await this.authTimestampCache.getAuthTimestamp(address) const scopes = getAuthenticationScopes(requestHeaders.authorization) const isArchivalRestricted = this.isArchivalRestricted(scopes) this.validate(address, requestHeaders, oldestValidTokenTimestamp) const listFilesArgs: PerformListFilesArgs = { pathPrefix: address, page: page } let listFileResult: ListFilesResult | ListFilesStatResult if (stat) { listFileResult = await this.driver.listFilesStat(listFilesArgs) } else { listFileResult = await this.driver.listFiles(listFilesArgs) } // Filter historical files from results. if (isArchivalRestricted && listFileResult.entries.length > 0) { if (stat) { listFileResult.entries = (listFileResult as ListFilesStatResult).entries .filter(entry => !this.isHistoricalFile(entry.name)) } else { listFileResult.entries = (listFileResult as ListFilesResult).entries .filter(entry => !this.isHistoricalFile(entry)) } // Detect empty page due to all files being historical files. if (listFileResult.entries.length === 0 && listFileResult.page) { // Insert a null marker entry to indicate that there are more results // even though the entry array is empty. listFileResult.entries.push(null) } } return listFileResult } getReadURLPrefix() { if (this.readURL) { return this.readURL } else { return this.driver.getReadURLPrefix() } } getFileName(filePath: string) { const pathParts = filePath.split('/') const fileName = pathParts[pathParts.length - 1] return fileName } getHistoricalFileName(filePath: string) { const fileName = this.getFileName(filePath) const filePathPrefix = filePath.slice(0, filePath.length - fileName.length) const historicalName = `.history.${Date.now()}.${generateUniqueID()}.${fileName}` const historicalPath = `${filePathPrefix}${historicalName}` return historicalPath } isHistoricalFile(filePath: string) { const fileName = this.getFileName(filePath) const isHistoricalFile = fileName.startsWith('.history.') return isHistoricalFile } async handleDelete( address: string, path: string, requestHeaders: { authorization?: string } ) { const oldestValidTokenTimestamp = await this.authTimestampCache.getAuthTimestamp(address) this.validate(address, requestHeaders, oldestValidTokenTimestamp) // can the caller delete? if so, in what paths? const scopes = getAuthenticationScopes(requestHeaders.authorization) const isArchivalRestricted = this.checkArchivalRestrictions(address, path, scopes) if (scopes.deletePrefixes.length > 0 || scopes.deletePaths.length > 0) { // we're limited to a set of prefixes and paths. // does the given path match any prefixes? let match = !!scopes.deletePrefixes.find((p) => (path.startsWith(p))) if (!match) { // check for exact paths match = !!scopes.deletePaths.find((p) => (path === p)) } if (!match) { // not authorized to write to this path throw new ValidationError(`Address ${address} not authorized to delete from ${path} by scopes`) } } await this.proofChecker.checkProofs(address, path, this.getReadURLPrefix()) if (isArchivalRestricted){ // if archival restricted then just rename the canonical file to the historical file const historicalPath = this.getHistoricalFileName(path) const renameCommand: PerformRenameArgs = { path: path, storageTopLevel: address, newPath: historicalPath } await this.driver.performRename(renameCommand) } else { const deleteCommand: PerformDeleteArgs = { storageTopLevel: address, path } await this.driver.performDelete(deleteCommand) } } async handleRequest( address: string, path: string, requestHeaders: { 'content-type'?: string, 'content-length'?: string | number, 'if-match'?: string, 'if-none-match'?: string, authorization?: string }, stream: Readable ): Promise<WriteResult> { const oldestValidTokenTimestamp = await this.authTimestampCache.getAuthTimestamp(address) this.validate(address, requestHeaders, oldestValidTokenTimestamp) let contentType = requestHeaders['content-type'] if (contentType === null || contentType === undefined) { contentType = 'application/octet-stream' } // can the caller write? if so, in what paths? const scopes = getAuthenticationScopes(requestHeaders.authorization) const isArchivalRestricted = this.checkArchivalRestrictions(address, path, scopes) if (scopes.writePrefixes.length > 0 || scopes.writePaths.length > 0) { // we're limited to a set of prefixes and paths. // does the given path match any prefixes? let match = !!scopes.writePrefixes.find((p) => (path.startsWith(p))) if (!match) { // check for exact paths match = !!scopes.writePaths.find((p) => (path === p)) } if (!match) { // not authorized to write to this path throw new ValidationError(`Address ${address} not authorized to write to ${path} by scopes`) } } const ifMatchTag = requestHeaders['if-match'] const ifNoneMatchTag = requestHeaders['if-none-match'] // only one match-tag header should be set if (ifMatchTag && ifNoneMatchTag) { throw new PreconditionFailedError('Request should not contain both if-match and if-none-match headers') } // only support using if-none-match for file creation, values that aren't the wildcard are prohibited if (ifNoneMatchTag && ifNoneMatchTag !== '*') { throw new PreconditionFailedError('Misuse of the if-none-match header. Expected to be * on write requests.') } // handle etag matching if not supported at the driver level if (!this.driver.supportsETagMatching) { // allow overwrites if tag is wildcard if (ifMatchTag && ifMatchTag !== '*') { const currentETag = (await this.driver.performStat({ path: path, storageTopLevel: address })).etag if (ifMatchTag !== currentETag) { throw new PreconditionFailedError( 'The provided ETag does not match that of the resource on the server' ) } } else if (ifNoneMatchTag && ifNoneMatchTag === '*') { // only proceed with writing file if the file does not already exist const statResult = await this.driver.performStat({ path: path, storageTopLevel: address }) if (statResult.exists) { throw new PreconditionFailedError('The entity you are trying to create already exists') } } } await this.proofChecker.checkProofs(address, path, this.getReadURLPrefix()) const contentLengthHeader = requestHeaders['content-length'] as string const contentLengthBytes = parseInt(contentLengthHeader) const isLengthFinite = Number.isFinite(contentLengthBytes) && contentLengthBytes > 0 // If a valid content-length is specified check to immediately return error if (isLengthFinite && contentLengthBytes > this.maxFileUploadSizeBytes) { const errMsg = `Max file upload size is ${this.maxFileUploadSizeMB} megabytes. ` + `Rejected Content-Length of ${bytesToMegabytes(contentLengthBytes, 4)} megabytes` logger.warn(`${errMsg}, address: ${address}`) throw new PayloadTooLargeError(errMsg) } if (isArchivalRestricted) { const historicalPath = this.getHistoricalFileName(path) try { await this.driver.performRename({ path: path, storageTopLevel: address, newPath: historicalPath }) } catch (error) { if (error instanceof DoesNotExist) { // ignore logger.debug( '404 on putFileArchival rename attempt -- usually this is okay and ' + 'only indicates that this is the first time the file was written: ' + `${address}/${path}` ) } else { logger.error(`Error performing historical file rename: ${address}/${path}`) logger.error(error) throw error } } } // Use the client reported content-length if available, otheriwse fallback to the // max configured length. const maxContentLength = Number.isFinite(contentLengthBytes) && contentLengthBytes > 0 ? contentLengthBytes : this.maxFileUploadSizeBytes // Create a PassThrough stream to monitor streaming chunk sizes. const { monitoredStream, pipelinePromise } = monitorStreamProgress(stream, totalBytes => { if (totalBytes > maxContentLength) { const errMsg = `Max file upload size is ${this.maxFileUploadSizeMB} megabytes. ` + `Rejected POST body stream of ${bytesToMegabytes(totalBytes, 4)} megabytes` // Log error -- this situation is indicative of a malformed client request // where the reported Content-Size is less than the upload size. logger.warn(`${errMsg}, address: ${address}`) // Destroy the request stream -- cancels reading from the client // and cancels uploading to the storage driver. const error = new PayloadTooLargeError(errMsg) stream.destroy(error) throw error } }) const writeCommand: PerformWriteArgs = { storageTopLevel: address, path, stream: monitoredStream, contentType, contentLength: contentLengthBytes, ifMatch: ifMatchTag, ifNoneMatch: ifNoneMatchTag } const [writeResponse] = await Promise.all([this.driver.performWrite(writeCommand), pipelinePromise]) const readURL = writeResponse.publicURL const driverPrefix = this.driver.getReadURLPrefix() const readURLPrefix = this.getReadURLPrefix() if (readURLPrefix !== driverPrefix && readURL.startsWith(driverPrefix)) { const postFix = readURL.slice(driverPrefix.length) return { publicURL: `${readURLPrefix}${postFix}`, etag: writeResponse.etag } } return writeResponse } isArchivalRestricted(scopes: AuthScopeValues) { return scopes.writeArchivalPaths.length > 0 || scopes.writeArchivalPrefixes.length > 0 } checkArchivalRestrictions(address: string, path: string, scopes: AuthScopeValues) { const isArchivalRestricted = this.isArchivalRestricted(scopes) if (isArchivalRestricted) { // we're limited to a set of prefixes and paths. // does the given path match any prefixes? let match = !!scopes.writeArchivalPrefixes.find((p) => (path.startsWith(p))) if (!match) { // check for exact paths match = !!scopes.writeArchivalPaths.find((p) => (path === p)) } if (!match) { // not authorized to write to this path throw new ValidationError(`Address ${address} not authorized to modify ${path} by scopes`) } } return isArchivalRestricted } }
the_stack
import BlocksoftCryptoLog from '../../common/BlocksoftCryptoLog' import { BlocksoftBlockchainTypes } from '../../blockchains/BlocksoftBlockchainTypes' import { BlocksoftTransferDispatcher } from '../../blockchains/BlocksoftTransferDispatcher' import { BlocksoftTransferPrivate } from './BlocksoftTransferPrivate' import { BlocksoftDictTypes } from '../../common/BlocksoftDictTypes' import config from '../../../app/config/config' type DataCache = { [key in BlocksoftDictTypes.Code]: { key: string, memo : string | boolean, time: number } } const CACHE_DOUBLE_TO: DataCache = {} as DataCache const CACHE_VALID_TIME = 120000 // 2 minute const CACHE_DOUBLE_BSE = {} export namespace BlocksoftTransfer { export const getTransferAllBalance = async function(data: BlocksoftBlockchainTypes.TransferData, additionalData: BlocksoftBlockchainTypes.TransferAdditionalData = {}): Promise<BlocksoftBlockchainTypes.TransferAllBalanceResult> { if (config.debug.sendLogs) { console.log(`${data.currencyCode} BlocksoftTransfer.getTransferAllBalance`, JSON.parse(JSON.stringify(data)), JSON.parse(JSON.stringify(additionalData))) } if (typeof data.derivationPath !== 'undefined' && data.derivationPath) { data.derivationPath = data.derivationPath.replace(/quote/g, '\'') } data.isTransferAll = true let transferAllCount try { BlocksoftCryptoLog.log(`${data.currencyCode} BlocksoftTransfer.getTransferAllBalance started ${data.addressFrom} `) const processor = BlocksoftTransferDispatcher.getTransferProcessor(data.currencyCode) const additionalDataTmp = { ...additionalData } let privateData = {} as BlocksoftBlockchainTypes.TransferPrivateData if (processor.needPrivateForFee()) { privateData = await BlocksoftTransferPrivate.initTransferPrivate(data, additionalData) } additionalDataTmp.mnemonic = '***' transferAllCount = await (BlocksoftTransferDispatcher.getTransferProcessor(data.currencyCode)).getTransferAllBalance(data, privateData, additionalDataTmp) BlocksoftCryptoLog.log(`${data.currencyCode} BlocksoftTransfer.getTransferAllBalance got ${data.addressFrom} result is ok`) if (config.debug.sendLogs) { console.log(`${data.currencyCode} BlocksoftTransfer.getTransferAllBalance result`, JSON.parse(JSON.stringify(transferAllCount))) } } catch (e) { if (e.message.indexOf('SERVER_RESPONSE_') === -1 && e.message.indexOf('UI_') === -1) { // noinspection ES6MissingAwait BlocksoftCryptoLog.err(`${data.currencyCode} BlocksoftTransfer.getTransferAllBalance ` + e.message) throw new Error('server.not.responding.all.balance.' + data.currencyCode + ' ' + e.message) } else { if (config.debug.appErrors) { console.log(`${data.currencyCode} BlocksoftTransfer.getTransferAllBalance error ` + e.message) } throw e } } return transferAllCount } export const getFeeRate = async function(data: BlocksoftBlockchainTypes.TransferData, additionalData: BlocksoftBlockchainTypes.TransferAdditionalData = {}): Promise<BlocksoftBlockchainTypes.FeeRateResult> { if (config.debug.sendLogs) { console.log('BlocksoftTransfer.getFeeRate', JSON.parse(JSON.stringify(data)), JSON.parse(JSON.stringify(additionalData))) } if (typeof data.derivationPath === 'undefined' || !data.derivationPath) { throw new Error('BlocksoftTransfer.getFeeRate requires derivationPath ' + JSON.stringify(data)) } data.derivationPath = data.derivationPath.replace(/quote/g, '\'') let feesCount try { BlocksoftCryptoLog.log(`${data.currencyCode} BlocksoftTransfer.getFeeRate started ${data.addressFrom} `) const processor = BlocksoftTransferDispatcher.getTransferProcessor(data.currencyCode) const additionalDataTmp = { ...additionalData } let privateData = {} as BlocksoftBlockchainTypes.TransferPrivateData if (processor.needPrivateForFee()) { privateData = await BlocksoftTransferPrivate.initTransferPrivate(data, additionalData) } additionalDataTmp.mnemonic = '***' feesCount = await processor.getFeeRate(data, privateData, additionalDataTmp) feesCount.countedTime = new Date().getTime() } catch (e) { if (config.debug.cryptoErrors) { console.log('BlocksoftTransfer.getFeeRate error ', e) } if (e.message.indexOf('SERVER_RESPONSE_') === -1 && e.message.indexOf('UI_') === -1) { // noinspection ES6MissingAwait BlocksoftCryptoLog.err(`${data.currencyCode} BlocksoftTransfer.getFeeRate error ` + data.addressFrom + ' => ' + data.addressTo + ' ' + data.amount + ' ' + e.message) throw new Error('server.not.responding.network.prices.' + data.currencyCode + ' ' + e.message) } else { throw e } } return feesCount } export const sendTx = async function(data: BlocksoftBlockchainTypes.TransferData, uiData: BlocksoftBlockchainTypes.TransferUiData, additionalData: BlocksoftBlockchainTypes.TransferAdditionalData): Promise<BlocksoftBlockchainTypes.SendTxResult> { if (config.debug.sendLogs) { console.log('BlocksoftTransfer.sendTx', data, uiData) } data.derivationPath = data.derivationPath.replace(/quote/g, '\'') const bseOrderId = typeof uiData !== 'undefined' && uiData && typeof uiData.selectedFee !== 'undefined' && typeof uiData.selectedFee.bseOrderId !== 'undefined' ? uiData.selectedFee.bseOrderId : false const uiErrorConfirmed = typeof uiData !== 'undefined' && uiData && typeof uiData.uiErrorConfirmed !== 'undefined' && uiData.uiErrorConfirmed const memo = typeof data !== 'undefined' && data && typeof data.memo !== 'undefined' ? data.memo : false try { if (data.transactionReplaceByFee || data.transactionRemoveByFee || data.transactionSpeedUp) { // do nothing } else { if (bseOrderId) { // bse order if (typeof CACHE_DOUBLE_BSE[bseOrderId] !== 'undefined') { if (!uiErrorConfirmed) { throw new Error('UI_CONFIRM_DOUBLE_BSE_SEND') } } } // usual tx if (typeof CACHE_DOUBLE_TO[data.currencyCode] !== 'undefined') { if (!uiErrorConfirmed) { if (data.addressTo && CACHE_DOUBLE_TO[data.currencyCode].key === data.addressTo && CACHE_DOUBLE_TO[data.currencyCode].memo === memo) { const time = new Date().getTime() const diff = time - CACHE_DOUBLE_TO[data.currencyCode].time if (diff < CACHE_VALID_TIME) { CACHE_DOUBLE_TO[data.currencyCode].time = time throw new Error('UI_CONFIRM_DOUBLE_SEND') } } } } } } catch (e) { if (config.debug.cryptoErrors) { console.log(`${data.currencyCode} BlocksoftTransfer.sendTx check double error ` + e.message, e) } if (e.message.indexOf('SERVER_RESPONSE_') === -1 && e.message.indexOf('UI_') === -1) { BlocksoftCryptoLog.err(`${data.currencyCode} BlocksoftTransfer.sendTx error ` + e.message) } throw e } let txResult try { BlocksoftCryptoLog.log(`${data.currencyCode} BlocksoftTransfer.sendTx started ${data.addressFrom} `) const processor = BlocksoftTransferDispatcher.getTransferProcessor(data.currencyCode) const privateData = await BlocksoftTransferPrivate.initTransferPrivate(data, additionalData) txResult = await processor.sendTx(data, privateData, uiData) BlocksoftCryptoLog.log(`${data.currencyCode} BlocksoftTransfer.sendTx got ${data.addressFrom} result is ok`) if (typeof uiData === 'undefined' || typeof uiData.selectedFee === 'undefined' || typeof uiData.selectedFee.rawOnly === 'undefined' || !uiData.selectedFee.rawOnly) { CACHE_DOUBLE_TO[data.currencyCode] = { key: data.addressTo, memo, time: new Date().getTime() } } if (bseOrderId) { CACHE_DOUBLE_BSE[bseOrderId] = true } // if (typeof uiData.selectedFee !== 'undefined') } catch (e) { if (config.debug.cryptoErrors) { console.log('BlocksoftTransfer.sendTx error ' + e.message, e) } if (e.message.indexOf('SERVER_RESPONSE_') === -1 && e.message.indexOf('UI_') === -1 && e.message.indexOf('connect() timed') === -1) { // noinspection ES6MissingAwait BlocksoftCryptoLog.err(`${data.currencyCode} BlocksoftTransfer.sendTx ` + e.message) } throw e } return txResult } export const sendRawTx = async function(data: BlocksoftBlockchainTypes.DbAccount, rawTxHex: string, txRBF: any, logData: any): Promise<string> { let txResult = '' try { BlocksoftCryptoLog.log(`${data.currencyCode} BlocksoftTransfer.sendRawTx started ${data.address} `) const processor = BlocksoftTransferDispatcher.getTransferProcessor(data.currencyCode) if (typeof processor.sendRawTx === 'undefined') { return 'none' } txResult = await processor.sendRawTx(data, rawTxHex, txRBF, logData) BlocksoftCryptoLog.log(`${data.currencyCode} BlocksoftTransfer.sendRawTx got ${data.address} result is ok`) } catch (e) { if (config.debug.cryptoErrors) { console.log(`${data.currencyCode} BlocksoftTransfer.sendRawTx error `, e) } BlocksoftCryptoLog.log(`${data.currencyCode} BlocksoftTransfer.sendRawTx error ` + e.message) throw e } return txResult } export const setMissingTx = async function(data: BlocksoftBlockchainTypes.DbAccount, dbTransaction: BlocksoftBlockchainTypes.DbTransaction): Promise<boolean> { let txResult = false try { BlocksoftCryptoLog.log(`${data.currencyCode} BlocksoftTransfer.setMissing started ${data.address} `) const processor = BlocksoftTransferDispatcher.getTransferProcessor(data.currencyCode) if (typeof processor.setMissingTx === 'undefined') { return false } txResult = await processor.setMissingTx(data, dbTransaction) BlocksoftCryptoLog.log(`${data.currencyCode} BlocksoftTransfer.setMissing got ${data.address} result is ok`) } catch (e) { BlocksoftCryptoLog.err(`${data.currencyCode} BlocksoftTransfer.setMissing error ` + e.message) } return txResult } export const canRBF = function(data: BlocksoftBlockchainTypes.DbAccount, dbTransaction: BlocksoftBlockchainTypes.DbTransaction, source: string): boolean { let txResult = false try { // BlocksoftCryptoLog.log(`BlocksoftTransfer.canRBF ${data.currencyCode} from ${source} started ${data.address} `) const processor = BlocksoftTransferDispatcher.getTransferProcessor(typeof data.currencyCode !== 'undefined' ? data.currencyCode : dbTransaction.currencyCode) if (typeof processor.canRBF === 'undefined') { return false } txResult = processor.canRBF(data, dbTransaction, source) // BlocksoftCryptoLog.log(`BlocksoftTransfer.canRBF ${data.currencyCode} from ${source} got ${data.address} result is ${JSON.stringify(txResult)}`) } catch (e) { BlocksoftCryptoLog.err(`${data.currencyCode} BlocksoftTransfer.canRBF error from ${source} ` + e.message) } return txResult } export const checkSendAllModal = function(data: { currencyCode: any }) { let checkSendAllModalResult = false try { // BlocksoftCryptoLog.log(`BlocksoftTransfer.checkSendAllModal ${data.currencyCode} started `) const processor = BlocksoftTransferDispatcher.getTransferProcessor(data.currencyCode) if (typeof processor.checkSendAllModal === 'undefined') { return false } checkSendAllModalResult = processor.checkSendAllModal(data) // BlocksoftCryptoLog.log(`BlocksoftTransfer.checkSendAllModal ${data.currencyCode} got result is ok ` + JSON.stringify(checkSendAllModalResult)) } catch (e) { BlocksoftCryptoLog.err(`${data.currencyCode} BlocksoftTransfer.checkSendAllModal error ` + e.message) } return checkSendAllModalResult } }
the_stack
import * as ts from 'typescript'; const yargs = require('yargs/yargs'); const { hideBin } = require('yargs/helpers'); type ObjectMemberAsJson = { [key: string]: string; } type ObjectMembersAsJson = { properties: ObjectMemberAsJson, getters: ObjectMemberAsJson, methods: ObjectMemberAsJson, } type ClassAsJson = { name: string } & ObjectMembersAsJson type MemberContext = 'class'|'literal' type TypeContext = 'methodReturn' class TypeNotSupportedError extends Error { constructor(message?: string) { super(message || 'This type is currently not supported.'); } } interface SupportChecker { supportsMethodName(methodName: string): boolean; } class JsSupportChecker { supportsMethodName(methodName: string): boolean { return true; } } class PhpSupportChecker { supportsMethodName(methodName: string): boolean { return !methodName.includes('$'); } } interface DocumentationFormatter { formatProperty(name: string, type: string, context: MemberContext): string formatGetter(name: string, type: string): string formatAnonymousFunction(parameters: string, returnType: string): string formatFunction(name: string, parameters: string, returnType: string): string formatParameter(name: string, type: string, isVariadic: boolean, isOptional: boolean): string formatTypeAny(): string formatTypeUnknown(): string formatTypeVoid(): string formatTypeUndefined(): string formatTypeNull(): string formatTypeBoolean(): string formatTypeNumber(): string formatTypeString(): string formatTypeReference(type: string): string formatGeneric(parentType: string, argumentTypes: string[], context?: TypeContext): string formatQualifiedName(left: string, right: string): string formatIndexedAccessType(object: string, index: string): string formatLiteralType(value: string): string formatUnion(types: string[]): string formatIntersection(types: string[]): string formatObject(members: string[]): string formatArray(type: string): string } class JsDocumentationFormatter implements DocumentationFormatter { formatProperty(name: string, type: string, context: MemberContext): string { return `${name}: ${type}`; } formatGetter(name: string, type: string): string { return `${name}: ${type}`; } formatAnonymousFunction(parameters: string, returnType: string): string { return `(${parameters}) => ${returnType}`; } formatFunction(name: string, parameters: string, returnType: string): string { return `${name}(${parameters}): ${returnType}`; } formatParameter(name: string, type: string, isVariadic: boolean, isOptional: boolean): string { return `${isVariadic ? '...' : ''}${name}${isOptional ? '?' : ''}: ${type}`; } formatTypeAny(): string { return 'any'; } formatTypeUnknown(): string { return 'unknown'; } formatTypeVoid(): string { return 'void'; } formatTypeUndefined(): string { return 'undefined'; } formatTypeNull(): string { return 'null'; } formatTypeBoolean(): string { return 'boolean'; } formatTypeNumber(): string { return 'number'; } formatTypeString(): string { return 'string'; } formatTypeReference(type: string): string { return type; } formatGeneric(parentType: string, argumentTypes: string[], context?: TypeContext): string { return `${parentType}<${argumentTypes.join(', ')}>`; } formatQualifiedName(left: string, right: string): string { return `${left}.${right}`; } formatIndexedAccessType(object: string, index: string): string { return `${object}[${index}]`; } formatLiteralType(value: string): string { return `'${value}'`; } formatUnion(types: string[]): string { return types.join(' | '); } formatIntersection(types: string[]): string { return types.join(' & '); } formatObject(members: string[]): string { return `{ ${members.join(', ')} }`; } formatArray(type: string): string { return `${type}[]`; } } class PhpDocumentationFormatter implements DocumentationFormatter { static readonly allowedJsClasses = ['Promise', 'Record', 'Map']; constructor( private readonly resourcesNamespace: string, private readonly resources: string[], ) {} formatProperty(name: string, type: string, context: MemberContext): string { return context === 'class' ? `${type} ${name}` : `${name}: ${type}`; } formatGetter(name: string, type: string): string { return `${type} ${name}`; } formatAnonymousFunction(parameters: string, returnType: string): string { return `callable(${parameters}): ${returnType}`; } formatFunction(name: string, parameters: string, returnType: string): string { return `${returnType} ${name}(${parameters})`; } formatParameter(name: string, type: string, isVariadic: boolean, isOptional: boolean): string { if (isVariadic && type.endsWith('[]')) { type = type.slice(0, -2); } const defaultValue = isOptional ? ' = null' : ''; return `${type} ${isVariadic ? '...' : ''}\$${name}${defaultValue}`; } formatTypeAny(): string { return 'mixed'; } formatTypeUnknown(): string { return 'mixed'; } formatTypeVoid(): string { return 'void'; } formatTypeUndefined(): string { return 'null'; } formatTypeNull(): string { return 'null'; } formatTypeBoolean(): string { return 'bool'; } formatTypeNumber(): string { return 'float'; } formatTypeString(): string { return 'string'; } formatTypeReference(type: string): string { // Allow some specific JS classes to be used in phpDoc if (PhpDocumentationFormatter.allowedJsClasses.includes(type)) { return type; } // Prefix PHP resources with their namespace if (this.resources.includes(type)) { return `\\${this.resourcesNamespace}\\${type}`; } // If the type ends with "options" then convert it to an associative array if (/options$/i.test(type)) { return 'array<string, mixed>'; } // Types ending with "Fn" are always callables or strings if (type.endsWith('Fn')) { return this.formatUnion(['callable', 'string']); } if (type === 'Function') { return 'callable'; } if (type === 'PuppeteerLifeCycleEvent') { return 'string'; } if (type === 'Serializable') { return this.formatUnion(['int', 'float', 'string', 'bool', 'null', 'array']); } if (type === 'SerializableOrJSHandle') { return this.formatUnion([this.formatTypeReference('Serializable'), this.formatTypeReference('JSHandle')]); } if (type === 'HandleType') { return this.formatUnion([this.formatTypeReference('JSHandle'), this.formatTypeReference('ElementHandle')]); } return 'mixed'; } formatGeneric(parentType: string, argumentTypes: string[], context?: TypeContext): string { // Avoid generics with "mixed" as parent type if (parentType === 'mixed') { return 'mixed'; } // Unwrap promises for method return types if (context === 'methodReturn' && parentType === 'Promise' && argumentTypes.length === 1) { return argumentTypes[0]; } // Transform Record and Map types to associative arrays if (['Record', 'Map'].includes(parentType) && argumentTypes.length === 2) { parentType = 'array'; } return `${parentType}<${argumentTypes.join(', ')}>`; } formatQualifiedName(left: string, right: string): string { return `mixed`; } formatIndexedAccessType(object: string, index: string): string { return `mixed`; } formatLiteralType(value: string): string { return `'${value}'`; } private prepareUnionOrIntersectionTypes(types: string[]): string[] { // Replace "void" type by "null" types = types.map(type => type === 'void' ? 'null' : type) // Remove duplicates const uniqueTypes = new Set(types); return Array.from(uniqueTypes.values()); } formatUnion(types: string[]): string { const result = this.prepareUnionOrIntersectionTypes(types).join('|'); // Convert enums to string type if (/^('\w+'\|)*'\w+'$/.test(result)) { return 'string'; } return result; } formatIntersection(types: string[]): string { return this.prepareUnionOrIntersectionTypes(types).join('&'); } formatObject(members: string[]): string { return `array{ ${members.join(', ')} }`; } formatArray(type: string): string { return `${type}[]`; } } class DocumentationGenerator { constructor( private readonly supportChecker: SupportChecker, private readonly formatter: DocumentationFormatter, ) {} private hasModifierForNode( node: ts.Node, modifier: ts.KeywordSyntaxKind ): boolean { if (!node.modifiers) { return false; } return node.modifiers.some((node) => node.kind === modifier); } private isNodeAccessible(node: ts.Node): boolean { // @ts-ignore if (node.name && this.getNamedDeclarationAsString(node).startsWith('_')) { return false; } return ( this.hasModifierForNode(node, ts.SyntaxKind.PublicKeyword) || (!this.hasModifierForNode(node, ts.SyntaxKind.ProtectedKeyword) && !this.hasModifierForNode(node, ts.SyntaxKind.PrivateKeyword)) ); } private isNodeStatic(node: ts.Node): boolean { return this.hasModifierForNode(node, ts.SyntaxKind.StaticKeyword); } public getClassDeclarationAsJson(node: ts.ClassDeclaration): ClassAsJson { return Object.assign( { name: this.getNamedDeclarationAsString(node) }, this.getMembersAsJson(node.members, 'class'), ); } private getMembersAsJson(members: ts.NodeArray<ts.NamedDeclaration>, context: MemberContext): ObjectMembersAsJson { const json: ObjectMembersAsJson = { properties: {}, getters: {}, methods: {}, }; for (const member of members) { if (!this.isNodeAccessible(member) || this.isNodeStatic(member)) { continue; } const name = member.name ? this.getNamedDeclarationAsString(member) : null; if (ts.isPropertySignature(member) || ts.isPropertyDeclaration(member)) { json.properties[name] = this.getPropertySignatureOrDeclarationAsString(member, context); } else if (ts.isGetAccessorDeclaration(member)) { json.getters[name] = this.getGetAccessorDeclarationAsString(member); } else if (ts.isMethodDeclaration(member)) { if (!this.supportChecker.supportsMethodName(name)) { continue; } json.methods[name] = this.getSignatureDeclarationBaseAsString(member); } } return json; } private getPropertySignatureOrDeclarationAsString( node: ts.PropertySignature | ts.PropertyDeclaration, context: MemberContext ): string { const type = this.getTypeNodeAsString(node.type); const name = this.getNamedDeclarationAsString(node); return this.formatter.formatProperty(name, type, context); } private getGetAccessorDeclarationAsString( node: ts.GetAccessorDeclaration ): string { const type = this.getTypeNodeAsString(node.type); const name = this.getNamedDeclarationAsString(node); return this.formatter.formatGetter(name, type); } private getSignatureDeclarationBaseAsString( node: ts.SignatureDeclarationBase ): string { const name = node.name && this.getNamedDeclarationAsString(node); const parameters = node.parameters .map(parameter => this.getParameterDeclarationAsString(parameter)) .join(', '); const returnType = this.getTypeNodeAsString(node.type, name ? 'methodReturn' : undefined); return name ? this.formatter.formatFunction(name, parameters, returnType) : this.formatter.formatAnonymousFunction(parameters, returnType); } private getParameterDeclarationAsString(node: ts.ParameterDeclaration): string { const name = this.getNamedDeclarationAsString(node); const type = this.getTypeNodeAsString(node.type); const isVariadic = node.dotDotDotToken !== undefined; const isOptional = node.questionToken !== undefined; return this.formatter.formatParameter(name, type, isVariadic, isOptional); } private getTypeNodeAsString(node: ts.TypeNode, context?: TypeContext): string { if (node.kind === ts.SyntaxKind.AnyKeyword) { return this.formatter.formatTypeAny(); } else if (node.kind === ts.SyntaxKind.UnknownKeyword) { return this.formatter.formatTypeUnknown(); } else if (node.kind === ts.SyntaxKind.VoidKeyword) { return this.formatter.formatTypeVoid(); } else if (node.kind === ts.SyntaxKind.UndefinedKeyword) { return this.formatter.formatTypeUndefined(); } else if (node.kind === ts.SyntaxKind.NullKeyword) { return this.formatter.formatTypeNull(); } else if (node.kind === ts.SyntaxKind.BooleanKeyword) { return this.formatter.formatTypeBoolean(); } else if (node.kind === ts.SyntaxKind.NumberKeyword) { return this.formatter.formatTypeNumber(); } else if (node.kind === ts.SyntaxKind.StringKeyword) { return this.formatter.formatTypeString(); } else if (ts.isTypeReferenceNode(node)) { return this.getTypeReferenceNodeAsString(node, context); } else if (ts.isIndexedAccessTypeNode(node)) { return this.getIndexedAccessTypeNodeAsString(node); } else if (ts.isLiteralTypeNode(node)) { return this.getLiteralTypeNodeAsString(node); } else if (ts.isUnionTypeNode(node)) { return this.getUnionTypeNodeAsString(node, context); } else if (ts.isIntersectionTypeNode(node)) { return this.getIntersectionTypeNodeAsString(node, context); } else if (ts.isTypeLiteralNode(node)) { return this.getTypeLiteralNodeAsString(node); } else if (ts.isArrayTypeNode(node)) { return this.getArrayTypeNodeAsString(node, context); } else if (ts.isFunctionTypeNode(node)) { return this.getSignatureDeclarationBaseAsString(node); } else { throw new TypeNotSupportedError(); } } private getTypeReferenceNodeAsString(node: ts.TypeReferenceNode, context?: TypeContext): string { return this.getGenericTypeReferenceNodeAsString(node, context) || this.getSimpleTypeReferenceNodeAsString(node); } private getGenericTypeReferenceNodeAsString(node: ts.TypeReferenceNode, context?: TypeContext): string | null { if (!node.typeArguments || node.typeArguments.length === 0) { return null; } const parentType = this.getSimpleTypeReferenceNodeAsString(node); const argumentTypes = node.typeArguments.map((node) => this.getTypeNodeAsString(node)); return this.formatter.formatGeneric(parentType, argumentTypes, context); } private getSimpleTypeReferenceNodeAsString(node: ts.TypeReferenceNode): string { return ts.isIdentifier(node.typeName) ? this.formatter.formatTypeReference(this.getIdentifierAsString(node.typeName)) : this.getQualifiedNameAsString(node.typeName); } private getQualifiedNameAsString(node: ts.QualifiedName): string { const right = this.getIdentifierAsString(node.right); const left = ts.isIdentifier(node.left) ? this.getIdentifierAsString(node.left) : this.getQualifiedNameAsString(node.left); return this.formatter.formatQualifiedName(left, right); } private getIndexedAccessTypeNodeAsString( node: ts.IndexedAccessTypeNode ): string { const object = this.getTypeNodeAsString(node.objectType); const index = this.getTypeNodeAsString(node.indexType); return this.formatter.formatIndexedAccessType(object, index); } private getLiteralTypeNodeAsString(node: ts.LiteralTypeNode): string { if (node.literal.kind === ts.SyntaxKind.NullKeyword) { return this.formatter.formatTypeNull(); } else if (node.literal.kind === ts.SyntaxKind.BooleanKeyword) { return this.formatter.formatTypeBoolean(); } else if (ts.isLiteralExpression(node.literal)) { return this.formatter.formatLiteralType(node.literal.text); } throw new TypeNotSupportedError(); } private getUnionTypeNodeAsString(node: ts.UnionTypeNode, context?: TypeContext): string { const types = node.types.map(typeNode => this.getTypeNodeAsString(typeNode, context)); return this.formatter.formatUnion(types); } private getIntersectionTypeNodeAsString(node: ts.IntersectionTypeNode, context?: TypeContext): string { const types = node.types.map(typeNode => this.getTypeNodeAsString(typeNode, context)); return this.formatter.formatIntersection(types); } private getTypeLiteralNodeAsString(node: ts.TypeLiteralNode): string { const members = this.getMembersAsJson(node.members, 'literal'); const stringMembers = Object.values(members).map(Object.values); const flattenMembers = stringMembers.reduce((acc, val) => acc.concat(val), []); return this.formatter.formatObject(flattenMembers); } private getArrayTypeNodeAsString(node: ts.ArrayTypeNode, context?: TypeContext): string { const type = this.getTypeNodeAsString(node.elementType, context); return this.formatter.formatArray(type); } private getNamedDeclarationAsString(node: ts.NamedDeclaration): string { if (!ts.isIdentifier(node.name)) { throw new TypeNotSupportedError(); } return this.getIdentifierAsString(node.name); } private getIdentifierAsString(node: ts.Identifier): string { return String(node.escapedText); } } const { argv } = yargs(hideBin(process.argv)) .command('$0 <language> <definition-files...>') .option('resources-namespace', { type: 'string', default: '' }) .option('resources', { type: 'array', default: [] }) .option('pretty', { type: 'boolean', default: false }) let supportChecker, formatter; switch (argv.language.toUpperCase()) { case 'JS': supportChecker = new JsSupportChecker(); formatter = new JsDocumentationFormatter(); break; case 'PHP': supportChecker = new PhpSupportChecker(); formatter = new PhpDocumentationFormatter(argv.resourcesNamespace, argv.resources); break; default: console.error(`Unsupported "${argv.language}" language.`); process.exit(1); } const docGenerator = new DocumentationGenerator(supportChecker, formatter); const program = ts.createProgram(argv.definitionFiles, {}); const classes = {}; for (const fileName of argv.definitionFiles) { const sourceFile = program.getSourceFile(fileName); ts.forEachChild(sourceFile, node => { if (ts.isClassDeclaration(node)) { const classAsJson = docGenerator.getClassDeclarationAsJson(node); classes[classAsJson.name] = classAsJson; } }); } process.stdout.write(JSON.stringify(classes, null, argv.pretty ? 2 : null));
the_stack
const conversations = [ { name: 'rallylongmailname@wix.com', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://i.pravatar.cc/150?img=1', leftTitleBadge: 'badgeOfficial' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', thumbnail: 'https://i.pravatar.cc/150?img=2', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://i.pravatar.cc/150?img=3', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://i.pravatar.cc/150?img=4', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://i.pravatar.cc/150?img=5', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://i.pravatar.cc/150?img=6', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Sir Robert Walpole', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'A. Schwarzenegger', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Spencer Compton', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'Arnold S.', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Henry Pelham', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'Arnold Schwarz', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Duke of Newcastle', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'Arni Zenegger', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'John Stuart', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'Nold Gger', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'George Grenville', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'Ard Benegger', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Charles Watson-Wentworth', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'A.B. Schwa', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'William Pitt', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'Roni Arnold', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Augustus FitzRoy', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'Old Schwarzenegger', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Frederick North', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'Bold Schwarzenegger', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Charles Watson-Wentworth', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'Mold Schwarzenegger', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'William Petty', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'Cold Schwarzenegger', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'William Cavendish-Bentinck', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'Hold Schwarzenegger', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Henry Addington', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'Bold Schwarz', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'William Grenville', text: 'Made a purchase in the total of 7.00$', timestamp: '7/14/2016', thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', leftTitleBadge: 'badgeOfficial' }, { name: 'S. Zenegger', text: 'Get to the chopper', timestamp: 'Jul 19th 214' }, { name: 'Johnny Gibson', text: 'Do you also carry these shoes in black?', timestamp: '36 min', count: '5', // thumbnail: 'https://static.wixstatic.com/media/87994e3d0dda4479a7f4d8c803e1323e.jpg/v1/fit/w_750,h_750/87994e3d0dda4479a7f4d8c803e1323e.jpg', isNew: false }, { name: 'Jennifer Clark', text: 'This might be the subject\nAnd the content is on a new line', timestamp: '2 hours', count: '1', thumbnail: 'https://static.wixstatic.com/media/c1ca83a468ae4c998fe4fddea60ea84d.jpg/v1/fit/w_750,h_750/c1ca83a468ae4c998fe4fddea60ea84d.jpg', isNew: true }, { name: 'Rebecka', text: 'Yep', timestamp: '3 hours', count: '12', thumbnail: 'https://static.wixstatic.com/media/43cddb4301684a01a26eaea100162934.jpeg/v1/fit/w_750,h_750/43cddb4301684a01a26eaea100162934.jpeg', isNew: true, leftTitleBadge: 'badgeOfficial' }, { name: 'Murphy', text: 'Do you have international shipping?', timestamp: '1 Day', count: '2', thumbnail: 'https://static.wixstatic.com/media/84e86e9bec8d46dd8296c510629a8d97.jpg/v1/fit/w_750,h_750/84e86e9bec8d46dd8296c510629a8d97.jpg', isNew: false }, { name: 'Matttt', text: 'will get to you next week with that', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/b27921b8c46841b48032f11c16d6e009.jpg/v1/fit/w_750,h_750/b27921b8c46841b48032f11c16d6e009.jpg', isNew: true, leftTitleBadge: 'twitterOn' }, { name: 'Brad Taylor', text: 'Will I be able to receive it before July 3rd?', timestamp: '1 Week', count: '99', thumbnail: 'https://static.wixstatic.com/media/7c69c135804b473c9788266540cd90d3.jpg/v1/fit/w_750,h_750/7c69c135804b473c9788266540cd90d3.jpg', isNew: false }, { name: 'Lina Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/a7adbc41a9f24a64803cac9aec2deb6b.jpg/v1/fit/w_750,h_750/a7adbc41a9f24a64803cac9aec2deb6b.jpg', isNew: true, leftTitleBadge: 'facebookOn' }, { name: 'Marissa Mayer', text: 'When will you have them back in stock?', timestamp: '1 Week', count: '', thumbnail: '', isNew: true }, { name: 'Elliot Brown', text: '2 - 3 weeks', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/66003687fdce4e6197cbaf816ca8fd17.jpg/v1/fit/w_750,h_750/66003687fdce4e6197cbaf816ca8fd17.jpg', isNew: true }, { name: 'Vanessa Campbell', text: 'Do you have these in other colors?', timestamp: '1 Week', count: '', thumbnail: 'https://static.wixstatic.com/media/d4367b20ae2e4036b18c34262d5ed031.jpg/v1/fit/w_750,h_750/d4367b20ae2e4036b18c34262d5ed031.jpg', isNew: true, leftTitleBadge: 'twitterOn' } ]; export default conversations;
the_stack
import './CBlock.module.scss'; import { getRandStr, getStoreItem, isServer, setStoreItem, TBlockContentProvider, TCromwellBlock, TCromwellBlockData, TCromwellBlockProps, } from '@cromwell/core'; import React, { Component } from 'react'; import { BlockContentConsumer, blockCssClass, BlockStoreConsumer, getBlockHtmlId, getBlockHtmlType, getDynamicLoader, getHtmlPluginBlockName, } from '../../constants'; import { CContainer } from '../CContainer/CContainer'; import { CEditor } from '../CEditor/CEditor'; import { CGallery } from '../CGallery/CGallery'; import { CHTML } from '../CHTML/CHTML'; import { CImage } from '../CImage/CImage'; import { CPlugin } from '../CPlugin/CPlugin'; import { CText } from '../CText/CText'; /** @internal */ export class CBlock<TContentBlock = React.Component> extends Component<TCromwellBlockProps<TContentBlock>> implements TCromwellBlock<TContentBlock> { private data?: TCromwellBlockData; private htmlId: string; private contentInstance: React.Component & TContentBlock; private childBlocks: TCromwellBlockData[] = []; private hasBeenMoved?: boolean = false; private blockRef = React.createRef<HTMLDivElement>(); private movedBlockRef = React.createRef<HTMLDivElement>(); private rerenderResolver?: (() => void | undefined); private rerenderPromise: Promise<void> | undefined; private unmounted: boolean = false; public movedCompForceUpdate?: () => void; private pageInstances: Record<string, TCromwellBlock | undefined> | undefined; private childResolvers: Record<string, ((block: TCromwellBlock) => void) | undefined> = {}; private childPromises: Record<string, (Promise<TCromwellBlock>) | undefined> = {}; private instanceId = getRandStr(12); public getInstanceId = () => this.instanceId; private didUpdateListeners: Record<string, (() => void)> = {}; public getData = () => { this.readConfig(); const { ...restProps } = this.props; return Object.assign({}, restProps, this.data); } public getBlockRef = () => this.blockRef; public getContentInstance = () => this.contentInstance; public setContentInstance = (contentInstance) => this.contentInstance = contentInstance; public getBlockInstance = (id: string): TCromwellBlock | undefined => { return this.pageInstances?.[id]; } public setBlockInstance = (id: string, inst: TCromwellBlock | undefined) => { if (this.pageInstances) { this.pageInstances[id] = inst; } } public registerGlobalBlockInstance = () => { let instances = getStoreItem('blockInstances'); if (!instances) { instances = {}; setStoreItem('blockInstances', instances); } instances[this.props.id] = this as any; } constructor(props: TCromwellBlockProps<TContentBlock>) { super(props); this.registerGlobalBlockInstance(); this.readConfig(); this.props.blockRef?.(this); } componentDidMount() { this.didUpdate(); this.contextComponentDidUpdate?.(); } componentDidUpdate() { this.didUpdate(); this.contextComponentDidUpdate?.(); } componentWillUnmount() { this.didUpdate(); this.unmounted = true; const data = this.getData(); const blockInst = this.getBlockInstance(data.id); if (blockInst?.getInstanceId() === this.instanceId) { this.setBlockInstance(data.id, undefined); } } private contextComponentDidUpdate: undefined | (() => void) = undefined; private didUpdate = async () => { this.props.blockRef?.(this); if (this.movedBlockRef.current) { this.movedBlockRef.current.removeAttribute('class'); this.movedBlockRef.current.removeAttribute('id'); this.movedBlockRef.current.style.display = 'none'; } if (this.rerenderResolver) { this.rerenderResolver(); this.rerenderResolver = undefined; this.rerenderPromise = undefined; } Object.values(this.didUpdateListeners).forEach(func => func()); } public addDidUpdateListener = (id: string, func: () => void) => { this.didUpdateListeners[id] = func; } public rerender = () => { if (this.unmounted) return; if (!this.rerenderPromise) this.rerenderPromise = new Promise(done => { this.rerenderResolver = done; }); this.contentInstance?.forceUpdate?.(); this.movedCompForceUpdate?.(); this.forceUpdate(); return this.rerenderPromise; } private readConfig() { this.data = undefined; if (this.props.type) this.data = { id: this.props.id, type: this.props.type }; this.htmlId = getBlockHtmlId(this.props.id); this.childBlocks = []; const pageConfig = getStoreItem('pageConfig'); if (pageConfig && pageConfig.modifications && Array.isArray(pageConfig.modifications)) { pageConfig.modifications.forEach(d => { if (d.id == this.props.id) { this.data = d; } if (this.props.id == d.parentId && d.id) { // Save blocks that targeted at this component. // This component will draw them this.childBlocks.push(d); } }); } this.hasBeenMoved = false; if (this.data?.parentId && !this.data?.isVirtual) { this.hasBeenMoved = true; } return this; } private getVirtualBlock = (b: TCromwellBlockData): JSX.Element => { const data = this.getData(); const defProps = { id: b.id, key: b.id + '_virtual', jsxParentId: data?.id, } if (b.type === 'HTML') { return <CHTML {...defProps} /> } if (b.type === 'image') { return <CImage {...defProps} /> } if (b.type === 'container') { return <CContainer {...defProps} /> } if (b.type === 'text') { return <CText {...defProps} /> } if (b.type === 'gallery') { return <CGallery {...defProps} /> } if (b.type === 'plugin') { return <CPlugin {...defProps} /> } if (b.type === 'editor') { return <CEditor {...defProps} /> } return ( <CBlock {...defProps} /> ) } public notifyChildRegistered(childInst) { const childId = childInst.getData()?.id; if (childId) { const resolver = this.childResolvers[childId]; if (resolver) { this.childResolvers[childId] = undefined; this.childPromises[childId] = undefined; resolver(childInst); } } } public getChildBlocks(): React.ReactNode[] { this.childBlocks = this.childBlocks.sort((a, b) => (a?.index ?? 0) - (b?.index ?? 0)); return this.childBlocks.map((block) => { if (block.isVirtual) { return this.getVirtualBlock(block); } if (isServer()) { return null; } const blockInst = this.getBlockInstance(block.id); // Works only for initialized components at the time of render of this component. // If some JSX component was moved from other place as child of this // and at time of execution wasn't constructed by React, then // `blockInst` will be `undefined` and nothing will return at the first render, if (blockInst) { return blockInst.consumerRender(); } else { // Child wasn't initialized yet. Return dynamic loader // and wait until child notifies this parent component // to render its content. Works only client-side. At server all elements // will be at their original position. next/dynamic doesn't work with SSR // this way. const childPromise = new Promise<TCromwellBlock>(done => { this.childResolvers[block.id] = done; }); this.childPromises[block.id] = childPromise; const DynamicComp = getDynamicLoader()(async (): Promise<React.ComponentType> => { const child = await childPromise; return () => { return child.consumerRender() ?? null; } }); return <DynamicComp key={block.id + 'dynamicComp'} />; } }); } public getDefaultContent(setClasses?: (classes: string) => void): React.ReactNode | null { const data = this.getData(); const jsxChildren = this.props.content?.(this.data, this.blockRef, inst => this.contentInstance = inst, setClasses, ); if (data?.type === 'container') { return ( <> {this.getChildBlocks()} {jsxChildren} </> ) } if (this.props.content) { return jsxChildren; } return this.props.children; } public contentRender(getContent?: TBlockContentProvider['getter'] | null, className?: string): React.ReactNode | null { const data = this.getData(); if (this.data?.isDeleted) { return null; } let customBlockClasses; const getCustomClasses = (classes: string) => customBlockClasses = classes; const blockContent = getContent ? getContent(this as any) : this.getDefaultContent(getCustomClasses); const elementClassName = blockCssClass + (this.data && this.data.type ? ' ' + getBlockHtmlType(this.data.type) : '') + (this.props.className ? ` ${this.props.className}` : '') + (this.data && this.data.type && this.data.type === 'plugin' && this.data.plugin && this.data.plugin.pluginName ? ` ${getHtmlPluginBlockName(this.data.plugin.pluginName)}` : '') + (className ? ' ' + className : '') + (customBlockClasses && customBlockClasses !== '' ? ' ' + customBlockClasses : ''); let blockStyles: React.CSSProperties = {}; // Interpretation of PageBuilder's UI styles const eSt = data?.editorStyles; if (eSt) { if (eSt.align) { if (eSt.align === 'center') { blockStyles.marginLeft = 'auto'; blockStyles.marginRight = 'auto'; } if (eSt.align === 'left') { blockStyles.marginRight = 'auto'; blockStyles.marginLeft = '0'; } if (eSt.align === 'right') { blockStyles.marginLeft = 'auto'; blockStyles.marginRight = '0'; } } if (eSt.offsetBottom !== undefined) { blockStyles.marginBottom = eSt.offsetBottom + 'px'; } if (eSt.offsetTop !== undefined) { blockStyles.marginTop = eSt.offsetTop + 'px'; } if (eSt.offsetLeft !== undefined) { blockStyles.marginLeft = eSt.offsetLeft + 'px'; } if (eSt.offsetRight !== undefined) { blockStyles.marginRight = eSt.offsetRight + 'px'; } if (eSt.maxWidth !== undefined) { blockStyles.maxWidth = eSt.maxWidth + 'px'; } } // Merge with custom css from config if (data.style) { try { const stylesParsed = typeof data.style === 'string' ? JSON.parse(data.style) : data.style; blockStyles = { ...blockStyles, ...stylesParsed, } } catch (e) { console.error('CBlock: provided style prop is not JSON: ' + data.style, e); } } return ( <div id={this.htmlId} key={this.hasBeenMoved ? this.htmlId + '_moved' : this.htmlId + '_orig'} onClick={this.props.onClick} style={blockStyles} className={elementClassName} ref={this.blockRef} >{blockContent}</div> ); } public consumerRender(): JSX.Element | null { return (<BlockContentConsumer key={this.htmlId + '_consumer'}> {(content) => { this.contextComponentDidUpdate = content?.componentDidUpdate; return this.contentRender(content?.getter, content?.blockClass) }} </BlockContentConsumer>); } render(): React.ReactNode | null { this.readConfig(); // console.log('CBlock::render id: ' + this.props.id, this.hasBeenMoved, this.getData()); return (<BlockStoreConsumer key={this.htmlId + '_render'}> {(value) => { this.pageInstances = value?.instances; if (!isServer()) (window as any).pageInstances = this.pageInstances; if (this.pageInstances && (!this.pageInstances[this.props.id] || this.pageInstances[this.props.id]?.getInstanceId() !== this.getInstanceId())) { this.setBlockInstance(this.props.id, this as any); if (this.data?.parentId && this.hasBeenMoved) { const parentInst = this.getBlockInstance(this.data?.parentId); if (parentInst) { parentInst.notifyChildRegistered(this as any); } } } if (this.hasBeenMoved && !isServer()) { return null; } return this.consumerRender(); }} </BlockStoreConsumer>); } }
the_stack
import { inject, ComponentFixture, TestBed, fakeAsync, tick, flush, } from '@angular/core/testing'; import { NgModule, Component, Directive, ViewChild, ViewContainerRef, Inject, TemplateRef, } from '@angular/core'; import {CommonModule} from '@angular/common'; import { MDC_SNACKBAR_DATA, MdcSnackbar, MdcSnackbarComponent, MdcSnackbarConfig, MdcSnackbarModule, MdcSnackbarRef } from './index'; import {OverlayContainer} from '@angular-mdc/web/overlay'; describe('MdcSnackbar', () => { let snackBar: MdcSnackbar; let overlayContainer: OverlayContainer; let overlayContainerElement: HTMLElement; let testViewContainerRef: ViewContainerRef; let viewContainerFixture: ComponentFixture<ComponentWithChildViewContainer>; const simpleMessage = 'Burritos are here!'; const simpleActionLabel = 'pickup'; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [MdcSnackbarModule, SnackBarTestModule], }).compileComponents(); })); beforeEach(inject([MdcSnackbar, OverlayContainer], (sb: MdcSnackbar, oc: OverlayContainer) => { snackBar = sb; overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })); afterEach(() => { overlayContainer.ngOnDestroy(); }); beforeEach(() => { viewContainerFixture = TestBed.createComponent(ComponentWithChildViewContainer); viewContainerFixture.detectChanges(); testViewContainerRef = viewContainerFixture.componentInstance.childViewContainer; }); it('should open a simple message with a button', () => { const config: MdcSnackbarConfig = {viewContainerRef: testViewContainerRef}; const snackBarRef = snackBar.open(simpleMessage, simpleActionLabel, config); viewContainerFixture.detectChanges(); expect(snackBarRef.instance instanceof MdcSnackbarComponent) .toBe(true, 'Expected the snackbar content component to be MdcSnackbarComponent'); expect(snackBarRef.instance.snackbarRef) .toBe(snackBarRef, 'Expected the snackbar reference to be placed in the component instance'); }); it('should open a snackbar with non-array CSS classes to apply', () => { const config: MdcSnackbarConfig = { viewContainerRef: testViewContainerRef, dismiss: true, classes: 'snack-test', actionClasses: 'action-text', dismissClasses: 'dismiss-class' }; const snackBarRef = snackBar.open(simpleMessage, simpleActionLabel, config); viewContainerFixture.detectChanges(); expect(snackBarRef.instance instanceof MdcSnackbarComponent) .toBe(true, 'Expected the snackbar content component to be MdcSnackbarComponent'); expect(snackBarRef.instance.snackbarRef) .toBe(snackBarRef, 'Expected the snackbar reference to be placed in the component instance'); }); it('should open a snackbar with an array of CSS classes to apply', () => { const config: MdcSnackbarConfig = { viewContainerRef: testViewContainerRef, dismiss: true, classes: ['snack-test', 'snack-test2'], actionClasses: ['action-text'], dismissClasses: ['dismiss-class'] }; const snackBarRef = snackBar.open(simpleMessage, simpleActionLabel, config); viewContainerFixture.detectChanges(); expect(snackBarRef.instance instanceof MdcSnackbarComponent) .toBe(true, 'Expected the snackbar content component to be MdcSnackbarComponent'); expect(snackBarRef.instance.snackbarRef) .toBe(snackBarRef, 'Expected the snackbar reference to be placed in the component instance'); }); it('should open a snackbar with 10000 timeoutMs', () => { const config: MdcSnackbarConfig = { viewContainerRef: testViewContainerRef, timeoutMs: 10000 }; snackBar.open(simpleMessage, simpleActionLabel, config); viewContainerFixture.detectChanges(); }); it('should open a snackbar with dismiss icon and closeOnEscape set false', () => { const config: MdcSnackbarConfig = { viewContainerRef: testViewContainerRef, dismiss: true, closeOnEscape: false }; snackBar.open(simpleMessage, simpleActionLabel, config); viewContainerFixture.detectChanges(); }); it('should open a simple message with no button', () => { const config: MdcSnackbarConfig = {viewContainerRef: testViewContainerRef}; const snackBarRef = snackBar.open(simpleMessage, '', config); viewContainerFixture.detectChanges(); expect(snackBarRef.instance instanceof MdcSnackbarComponent) .toBe(true, 'Expected the snackbar content component to be MdcSnackbarComponent'); expect(snackBarRef.instance.snackbarRef) .toBe(snackBarRef, 'Expected the snackbar reference to be placed in the component instance'); }); it('should dismiss the snackbar and remove itself from the view', fakeAsync(() => { const config: MdcSnackbarConfig = {viewContainerRef: testViewContainerRef}; const dismissCompleteSpy = jasmine.createSpy('dismiss complete spy'); const snackBarRef = snackBar.open(simpleMessage, undefined, config); viewContainerFixture.detectChanges(); expect(overlayContainerElement.childElementCount) .toBeGreaterThan(0, 'Expected overlay container element to have at least one child'); snackBarRef.afterDismiss().subscribe(undefined, undefined, dismissCompleteSpy); snackBarRef.dismiss(); viewContainerFixture.detectChanges(); // Run through animations for dismissal flush(); expect(dismissCompleteSpy).toHaveBeenCalled(); expect(overlayContainerElement.childElementCount) .toBe(0, 'Expected the overlay container element to have no child elements'); })); it('should be able to get dismissed through the service', fakeAsync(() => { snackBar.open(simpleMessage); viewContainerFixture.detectChanges(); expect(overlayContainerElement.childElementCount).toBeGreaterThan(0); snackBar.dismiss(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.childElementCount).toBe(0); })); it('should remove past snackbars when opening new snackbars', fakeAsync(() => { snackBar.open('First snackbar'); viewContainerFixture.detectChanges(); tick(110); snackBar.open('Second snackbar'); viewContainerFixture.detectChanges(); tick(110); snackBar.open('Third snackbar'); viewContainerFixture.detectChanges(); tick(110); expect(overlayContainerElement.textContent!.trim()).toBe('Third snackbar'); flush(); })); it('should remove snackbar if another is shown while its still animating open', fakeAsync(() => { snackBar.open('First snackbar'); viewContainerFixture.detectChanges(); tick(110); snackBar.open('Second snackbar'); viewContainerFixture.detectChanges(); tick(110); expect(overlayContainerElement.textContent!.trim()).toBe('Second snackbar'); flush(); })); it('should allow manually dismissing with an action', fakeAsync(() => { const dismissCompleteSpy = jasmine.createSpy('dismiss complete spy'); const snackBarRef = snackBar.open('Some content'); viewContainerFixture.detectChanges(); snackBarRef.afterDismiss().subscribe(undefined, undefined, dismissCompleteSpy); snackBarRef.dismiss({action: true}); viewContainerFixture.detectChanges(); flush(); expect(dismissCompleteSpy).toHaveBeenCalled(); tick(500); })); it('should indicate in `afterClosed` whether it was dismissed by an action', fakeAsync(() => { const dismissSpy = jasmine.createSpy('dismiss spy'); const snackBarRef = snackBar.open('Some content'); viewContainerFixture.detectChanges(); snackBarRef.afterDismiss().subscribe(dismissSpy); snackBarRef.dismiss({action: true}); viewContainerFixture.detectChanges(); flush(); expect(dismissSpy).toHaveBeenCalledWith(jasmine.objectContaining({action: true})); tick(500); })); it('should clear the dismiss timeout when dismissed before timeout expiration', fakeAsync(() => { const config = new MdcSnackbarConfig(); config.timeoutMs = 1000; snackBar.open('content', 'test', config); setTimeout(() => snackBar.dismiss(), 500); tick(600); viewContainerFixture.detectChanges(); tick(); expect(viewContainerFixture.isStable()).toBe(true); })); it('should dismiss the open snackbar on destroy', fakeAsync(() => { snackBar.open(simpleMessage); viewContainerFixture.detectChanges(); expect(overlayContainerElement.childElementCount).toBeGreaterThan(0); snackBar.ngOnDestroy(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.childElementCount).toBe(0); })); }); describe('MdcSnackbar with parent MdcSnackbar', () => { let parentSnackBar: MdcSnackbar; let childSnackBar: MdcSnackbar; let overlayContainer: OverlayContainer; let overlayContainerElement: HTMLElement; let fixture: ComponentFixture<ComponentThatProvidesMdcSnackBar>; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [MdcSnackbarModule, SnackBarTestModule], declarations: [ComponentThatProvidesMdcSnackBar], }).compileComponents(); })); beforeEach(inject([MdcSnackbar, OverlayContainer], (sb: MdcSnackbar, oc: OverlayContainer) => { parentSnackBar = sb; overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); fixture = TestBed.createComponent(ComponentThatProvidesMdcSnackBar); childSnackBar = fixture.componentInstance.snackBar; fixture.detectChanges(); })); afterEach(() => { overlayContainer.ngOnDestroy(); }); it('should close snackBars opened by parent when opening from child', fakeAsync(() => { parentSnackBar.open('Pizza'); fixture.detectChanges(); tick(110); expect(overlayContainerElement.textContent) .toContain('Pizza', 'Expected a snackBar to be opened'); childSnackBar.open('Taco'); fixture.detectChanges(); tick(110); expect(overlayContainerElement.textContent) .toContain('Taco', 'Expected parent snackbar msg to be dismissed by opening from child'); flush(); })); it('should close snackBars opened by child when opening from parent', fakeAsync(() => { childSnackBar.open('Pizza'); fixture.detectChanges(); tick(110); expect(overlayContainerElement.textContent) .toContain('Pizza', 'Expected a snackBar to be opened'); parentSnackBar.open('Taco'); fixture.detectChanges(); tick(110); expect(overlayContainerElement.textContent) .toContain('Taco', 'Expected child snackbar msg to be dismissed by opening from parent'); flush(); })); it('should not dismiss parent snackbar if child is destroyed', fakeAsync(() => { parentSnackBar.open('Pizza'); fixture.detectChanges(); tick(110); expect(overlayContainerElement.childElementCount).toBeGreaterThan(0); childSnackBar.ngOnDestroy(); fixture.detectChanges(); tick(110); expect(overlayContainerElement.childElementCount).toBeGreaterThan(0); flush(); })); }); @Directive({selector: 'dir-with-view-container'}) class DirectiveWithViewContainer { constructor(public viewContainerRef: ViewContainerRef) {} } @Component({ selector: 'arbitrary-component', template: `<dir-with-view-container *ngIf="childComponentExists"></dir-with-view-container>`, }) class ComponentWithChildViewContainer { @ViewChild(DirectiveWithViewContainer, {static: false}) childWithViewContainer: DirectiveWithViewContainer; childComponentExists: boolean = true; get childViewContainer() { return this.childWithViewContainer.viewContainerRef; } } @Component({ selector: 'arbitrary-component-with-template-ref', template: ` <ng-template let-data> Fries {{localValue}} {{data?.value}} </ng-template> `, }) class ComponentWithTemplateRef { @ViewChild(TemplateRef, {static: false}) templateRef: TemplateRef<any>; localValue: string; } /** Simple component for testing ComponentPortal. */ @Component({template: '<p>Burritos are on the way.</p>'}) class BurritosNotification { constructor( public snackBarRef: MdcSnackbarRef<BurritosNotification>, @Inject(MDC_SNACKBAR_DATA) public data: any) {} } @Component({ template: '', providers: [MdcSnackbar] }) class ComponentThatProvidesMdcSnackBar { constructor(public snackBar: MdcSnackbar) {} } /** * Simple component to open snackbars from. * Create a real (non-test) NgModule as a workaround forRoot * https://github.com/angular/angular/issues/10760 */ const TEST_DIRECTIVES = [ComponentWithChildViewContainer, BurritosNotification, DirectiveWithViewContainer, ComponentWithTemplateRef]; @NgModule({ imports: [CommonModule, MdcSnackbarModule], exports: TEST_DIRECTIVES, declarations: TEST_DIRECTIVES, entryComponents: [ComponentWithChildViewContainer, BurritosNotification], }) class SnackBarTestModule {}
the_stack
import * as Tp from "../Collections/Immutable/Tuple" import { _A, _E, _R, _U } from "../Effect/commons" import * as E from "../Either" import { pipe } from "../Function" import type { Option } from "../Option" import { Stack } from "../Stack" import type * as U from "../Utils" /** * `Async[R, E, A]` is a purely functional description of an async computation * that requires an environment `R` and may either fail with an `E` or succeed * with an `A`. */ export interface Async<R, E, A> extends U.HasUnify {} export abstract class Async<R, E, A> { readonly [_U]!: "Async"; readonly [_E]!: () => E; readonly [_A]!: () => A; readonly [_R]!: (_: R) => void } export interface UIO<A> extends Async<unknown, never, A> {} export interface RIO<R, A> extends Async<R, never, A> {} export interface IO<E, A> extends Async<unknown, E, A> {} /** * @ets_optimize identity */ function concrete<R, E, A>(_: Async<R, E, A>): Concrete<R, E, A> { return _ as any } class ISucceed<A> extends Async<unknown, never, A> { readonly _asyncTag = "Succeed" constructor(readonly a: A) { super() } } class ISuspend<R, E, A> extends Async<R, E, A> { readonly _asyncTag = "Suspend" constructor(readonly f: () => Async<R, E, A>) { super() } } class IFail<E> extends Async<unknown, E, never> { readonly _asyncTag = "Fail" constructor(readonly e: E) { super() } } class IFlatMap<R, R1, E, E1, A, B> extends Async<R & R1, E1 | E, B> { readonly _asyncTag = "FlatMap" constructor( readonly value: Async<R, E, A>, readonly cont: (a: A) => Async<R1, E1, B> ) { super() } } class IFold<R, E1, E2, A, B> extends Async<R, E2, B> { readonly _asyncTag = "Fold" constructor( readonly value: Async<R, E1, A>, readonly failure: (e: E1) => Async<R, E2, B>, readonly success: (a: A) => Async<R, E2, B> ) { super() } } class IAccess<R, E, A> extends Async<R, E, A> { readonly _asyncTag = "Access" constructor(readonly access: (r: R) => Async<R, E, A>) { super() } } class IProvide<R, E, A> extends Async<unknown, E, A> { readonly _asyncTag = "Provide" constructor(readonly r: R, readonly cont: Async<R, E, A>) { super() } } class IPromise<E, A> extends Async<unknown, E, A> { readonly _asyncTag = "Promise" constructor( readonly promise: (onInterrupt: (f: () => void) => void) => Promise<A>, readonly onError: (u: unknown) => E ) { super() } } class IDone<E, A> extends Async<unknown, E, A> { readonly _asyncTag = "Done" constructor(readonly exit: Exit<E, A>) { super() } } type Concrete<R, E, A> = | ISucceed<A> | IFail<E> | IFlatMap<R, R, E, E, unknown, A> | IFold<R, unknown, E, unknown, A> | IAccess<R, E, A> | IProvide<R, E, A> | ISuspend<R, E, A> | IPromise<E, A> | IDone<E, A> class FoldFrame { readonly _asyncTag = "FoldFrame" constructor( readonly failure: (e: any) => Async<any, any, any>, readonly apply: (e: any) => Async<any, any, any> ) {} } class ApplyFrame { readonly _asyncTag = "ApplyFrame" constructor(readonly apply: (e: any) => Async<any, any, any>) {} } type Frame = FoldFrame | ApplyFrame /** * Models the state of interruption, allows for listening to interruption events & firing interruption events */ export class InterruptionState { private isInterrupted = false readonly listeners = new Set<() => void>() // listen to an interruption event listen(f: () => void) { this.listeners.add(f) return () => { // stop listening this.listeners.delete(f) } } get interrupted() { return this.isInterrupted } interrupt() { if (!this.isInterrupted) { // set to interrupted this.isInterrupted = true // notify this.listeners.forEach((i) => { i() }) } } } export interface Failure<E> { readonly _tag: "Failure" e: E } export interface Interrupt { readonly _tag: "Interrupt" } export interface Success<A> { readonly _tag: "Success" a: A } export type Rejection<E> = Failure<E> | Interrupt export type Exit<E, A> = Rejection<E> | Success<A> export const failExit = <E>(e: E): Rejection<E> => ({ _tag: "Failure", e }) export const interruptExit = <Exit<never, never>>{ _tag: "Interrupt" } export const successExit = <A>(a: A): Exit<never, A> => ({ _tag: "Success", a }) /** * Models a cancellable promise */ class CancelablePromise<E, A> { // holds the type information of E readonly _E!: () => E // gets called with a Rejection<E>, any here is to not break covariance imposed by _E private rejection: ((e: Rejection<any>) => void) | undefined = undefined // holds the current running promise private current: Promise<A> | undefined = undefined constructor( // creates the promise readonly promiseFactory: (onInterrupt: (f: () => void) => void) => Promise<A>, // listens for interruption events readonly is: InterruptionState ) {} // creates the computation linking it to the interruption state readonly promise: () => Promise<A> = () => { if (this.current) { throw new Error("Bug: promise() have been called twice") } else if (this.is.interrupted) { throw new Error("Bug: trying to create a promise already interrupted") } else { const onInterrupt = <(() => void)[]>[] // we record the current interrupt in the interruption registry const removeListener = this.is.listen(() => { onInterrupt.forEach((f) => { f() }) this.interrupt() }) const p = new Promise<A>((res, rej) => { // set the rejection handler this.rejection = rej // creates the underlying promise this.promiseFactory((f) => { onInterrupt.push(f) }) .then((a) => { // removes the call to interrupt from the interruption registry removeListener() // if not interrupted we continue if (!this.is.interrupted) { res(a) } }) .catch((e) => { // removes the call to interrupt from the interruption registry removeListener() // if not interrupted we continue if (!this.is.interrupted) { rej(e) } }) }) // track the current running promise to avoid re-creation this.current = p // return the promise return p } } readonly interrupt = () => { // triggeres a promise rejection on the current promise with an interrupt exit this.rejection?.(interruptExit as any) } } export class Tracer { private running = new Set<Promise<any>>() constructor() { this.traced = this.traced.bind(this) this.wait = this.wait.bind(this) this.clear = this.clear.bind(this) } // tracks a lazy promise lifetime traced<A>(promise: () => Promise<A>) { return async () => { const p = promise() this.running.add(p) try { const a = await p this.running.delete(p) return Promise.resolve(a) } catch (e) { this.running.delete(p) return Promise.reject(e) } } } // awaits for all the running promises to complete async wait(): Promise<Exit<any, any>[]> { const t = await Promise.all( Array.from(this.running).map((p) => p.then((a) => successExit(a)).catch((e) => Promise.resolve(e)) ) ) return await new Promise((r) => { setTimeout(() => { r(t) }, 0) }) } // clears itself clear() { this.running.clear() } } // create the root tracing context export const tracingContext = new Tracer() /** * Runs this computation with the specified initial state, returning either a * failure or the updated state and the result */ export function runPromiseExitEnv<R, E, A>( self: Async<R, E, A>, ri: R, is: InterruptionState = new InterruptionState() ): Promise<Exit<E, A>> { return tracingContext.traced(async () => { let stack: Stack<Frame> | undefined = undefined let a = null let r = ri let failed = false let curAsync = self as Async<any, any, any> | undefined let cnt = 0 let interruptedLocal = false function isInterruted() { return interruptedLocal || is.interrupted } function pop() { const nextInstr = stack if (nextInstr) { stack = stack?.previous } return nextInstr?.value } function push(cont: Frame) { stack = new Stack(cont, stack) } function findNextErrorHandler() { let unwinding = true while (unwinding) { const nextInstr = pop() if (nextInstr == null) { unwinding = false } else { if (nextInstr._asyncTag === "FoldFrame") { unwinding = false push(new ApplyFrame(nextInstr.failure)) } } } } while (curAsync != null && !isInterruted()) { if (cnt > 10_000) { await new Promise((r) => { setTimeout(() => { r(undefined) }, 0) }) cnt = 0 } cnt += 1 const xp = concrete(curAsync) switch (xp._asyncTag) { case "FlatMap": { const nested = concrete(xp.value) const continuation = xp.cont switch (nested._asyncTag) { case "Succeed": { curAsync = continuation(nested.a) break } default: { curAsync = nested push(new ApplyFrame(continuation)) } } break } case "Suspend": { curAsync = xp.f() break } case "Succeed": { a = xp.a const nextInstr = pop() if (nextInstr) { curAsync = nextInstr.apply(a) } else { curAsync = undefined } break } case "Fail": { findNextErrorHandler() const nextInst = pop() if (nextInst) { curAsync = nextInst.apply(xp.e) } else { failed = true a = xp.e curAsync = undefined } break } case "Fold": { curAsync = xp.value push(new FoldFrame(xp.failure, xp.success)) break } case "Done": { switch (xp.exit._tag) { case "Failure": { curAsync = new IFail(xp.exit.e) break } case "Interrupt": { interruptedLocal = true curAsync = undefined break } case "Success": { curAsync = new ISucceed(xp.exit.a) break } } break } case "Access": { curAsync = xp.access(r) break } case "Provide": { r = xp.r curAsync = xp.cont break } case "Promise": { try { curAsync = new ISucceed( await new CancelablePromise( (s) => xp.promise(s).catch((e) => Promise.reject(failExit(xp.onError(e)))), is ).promise() ) } catch (e) { const e_ = <Rejection<E>>e switch (e_._tag) { case "Failure": { curAsync = new IFail(e_.e) break } case "Interrupt": { interruptedLocal = true curAsync = undefined break } } } break } } } if (is.interrupted) { return interruptExit } if (failed) { return failExit(a) } return successExit(a) })() } export function runPromiseExit<E, A>( self: Async<unknown, E, A>, is: InterruptionState = new InterruptionState() ): Promise<Exit<E, A>> { return runPromiseExitEnv(self, {}, is) } // runs as a Promise of an Exit export async function runPromise<E, A>( task: Async<unknown, E, A>, is = new InterruptionState() ): Promise<A> { return runPromiseExit(task, is).then((e) => e._tag === "Failure" ? Promise.reject(e.e) : e._tag === "Interrupt" ? Promise.reject(e) : Promise.resolve(e.a) ) } // runs as a Cancellable export function runAsync<E, A>( task: Async<unknown, E, A>, cb?: (e: Exit<E, A>) => void ) { const is = new InterruptionState() runPromiseExit(task, is).then(cb) return () => { is.interrupt() } } // runs as a Cancellable export function runAsyncEnv<R, E, A>( task: Async<R, E, A>, r: R, cb?: (e: Exit<E, A>) => void ) { const is = new InterruptionState() runPromiseExitEnv(task, r, is).then(cb) return () => { is.interrupt() } } /** * Extends this computation with another computation that depends on the * result of this computation by running the first computation, using its * result to generate a second computation, and running that computation. * * @ets_data_first chain_ */ export function chain<A, R1, E1, B>(f: (a: A) => Async<R1, E1, B>) { return <R, E>(self: Async<R, E, A>): Async<R & R1, E | E1, B> => new IFlatMap(self, f) } /** * Extends this computation with another computation that depends on the * result of this computation by running the first computation, using its * result to generate a second computation, and running that computation. */ export function chain_<R, E, A, R1, E1, B>( self: Async<R, E, A>, f: (a: A) => Async<R1, E1, B> ): Async<R & R1, E | E1, B> { return new IFlatMap(self, f) } /** * Returns a computation that effectfully "peeks" at the success of this one. * * @ets_data_first tap_ */ export function tap<A, R1, E1, X>(f: (a: A) => Async<R1, E1, X>) { return <R, E>(self: Async<R, E, A>): Async<R & R1, E | E1, A> => tap_(self, f) } /** * Returns a computation that effectfully "peeks" at the success of this one. */ export function tap_<R, E, A, R1, E1, X>( self: Async<R, E, A>, f: (a: A) => Async<R1, E1, X> ): Async<R & R1, E | E1, A> { return chain_(self, (a) => map_(f(a), () => a)) } /** * Constructs a computation that always succeeds with the specified value. */ export function succeed<A>(a: A): Async<unknown, never, A> { return new ISucceed(a) } /** * Constructs a computation that always succeeds with the specified value, * passing the state through unchanged. */ export function fail<E>(a: E): Async<unknown, E, never> { return new IFail(a) } /** * Extends this computation with another computation that depends on the * result of this computation by running the first computation, using its * result to generate a second computation, and running that computation. */ export function map_<R, E, A, B>(self: Async<R, E, A>, f: (a: A) => B) { return chain_(self, (a) => succeed(f(a))) } /** * Extends this computation with another computation that depends on the * result of this computation by running the first computation, using its * result to generate a second computation, and running that computation. * * @ets_data_first map_ */ export function map<A, B>(f: (a: A) => B) { return <R, E>(self: Async<R, E, A>) => map_(self, f) } /** * Recovers from errors by accepting one computation to execute for the case * of an error, and one computation to execute for the case of success. */ export function foldM_<R, E, A, R1, E1, B, R2, E2, C>( self: Async<R, E, A>, failure: (e: E) => Async<R1, E1, B>, success: (a: A) => Async<R2, E2, C> ): Async<R & R1 & R2, E1 | E2, B | C> { return new IFold( self as Async<R & R1 & R2, E, A>, failure as (e: E) => Async<R1 & R2, E1 | E2, B | C>, success ) } /** * Recovers from errors by accepting one computation to execute for the case * of an error, and one computation to execute for the case of success. * * @ets_data_first foldM_ */ export function foldM<E, A, R1, E1, B, R2, E2, C>( failure: (e: E) => Async<R1, E1, B>, success: (a: A) => Async<R2, E2, C> ) { return <R>(self: Async<R, E, A>) => foldM_(self, failure, success) } /** * Folds over the failed or successful results of this computation to yield * a computation that does not fail, but succeeds with the value of the left * or right function passed to `fold`. * * @ets_data_first fold_ */ export function fold<E, A, B, C>(failure: (e: E) => B, success: (a: A) => C) { return <R>(self: Async<R, E, A>) => fold_(self, failure, success) } /** * Folds over the failed or successful results of this computation to yield * a computation that does not fail, but succeeds with the value of the left * or righr function passed to `fold`. */ export function fold_<R, E, A, B, C>( self: Async<R, E, A>, failure: (e: E) => B, success: (a: A) => C ): Async<R, never, B | C> { return foldM_( self, (e) => succeed(failure(e)), (a) => succeed(success(a)) ) } /** * Recovers from all errors. * * @ets_data_first catchAll_ */ export function catchAll<E, R1, E1, B>(failure: (e: E) => Async<R1, E1, B>) { return <R, A>(self: Async<R, E, A>) => catchAll_(self, failure) } /** * Recovers from all errors. */ export function catchAll_<R, E, A, R1, E1, B>( self: Async<R, E, A>, failure: (e: E) => Async<R1, E1, B> ) { return foldM_(self, failure, (a) => succeed(a)) } /** * Returns a computation whose error and success channels have been mapped * by the specified functions, `f` and `g`. * * @ets_data_first bimap_ */ export function bimap<E, A, E1, A1>(f: (e: E) => E1, g: (a: A) => A1) { return <R>(self: Async<R, E, A>) => bimap_(self, f, g) } /** * Returns a computation whose error and success channels have been mapped * by the specified functions, `f` and `g`. */ export function bimap_<R, E, A, E1, A1>( self: Async<R, E, A>, f: (e: E) => E1, g: (a: A) => A1 ) { return foldM_( self, (e) => fail(f(e)), (a) => succeed(() => g(a)) ) } /** * Transforms the error type of this computation with the specified * function. * * @ets_data_first mapError_ */ export function mapError<E, E1>(f: (e: E) => E1) { return <R, A>(self: Async<R, E, A>) => mapError_(self, f) } /** * Transforms the error type of this computation with the specified * function. */ export function mapError_<R, E, A, E1>(self: Async<R, E, A>, f: (e: E) => E1) { return catchAll_(self, (e) => fail(f(e))) } /** * Constructs a computation that always returns the `Unit` value, passing the * state through unchanged. */ export const unit = succeed<void>(undefined) /** * Transforms the initial state of this computation` with the specified * function. */ export function provideSome<R0, R1>(f: (s: R0) => R1) { return <E, A>(self: Async<R1, E, A>) => accessM((r: R0) => provideAll(f(r))(self)) } /** * Provides this computation with its required environment. * * @ets_data_first provideAll_ */ export function provideAll<R>(r: R) { return <E, A>(self: Async<R, E, A>): Async<unknown, E, A> => new IProvide(r, self) } /** * Provides this computation with its required environment. */ export function provideAll_<R, E, A>(self: Async<R, E, A>, r: R): Async<unknown, E, A> { return new IProvide(r, self) } /** * Provides some of the environment required to run this effect, * leaving the remainder `R0` and combining it automatically using spread. */ export function provide<R = unknown>(r: R) { return <E, A, R0 = unknown>(next: Async<R & R0, E, A>): Async<R0, E, A> => provideSome((r0: R0) => ({ ...r0, ...r }))(next) } /** * Access the environment monadically */ export function accessM<R, R1, E, A>( f: (_: R) => Async<R1, E, A> ): Async<R1 & R, E, A> { return new IAccess<R1 & R, E, A>(f) } /** * Access the environment with the function f */ export function access<R, A>(f: (_: R) => A): Async<R, never, A> { return accessM((r: R) => succeed(f(r))) } /** * Access the environment */ export function environment<R>(): Async<R, never, R> { return accessM((r: R) => succeed(r)) } /** * Returns a computation whose failure and success have been lifted into an * `Either`. The resulting computation cannot fail, because the failure case * has been exposed as part of the `Either` success case. */ export function either<R, E, A>(self: Async<R, E, A>): Async<R, never, E.Either<E, A>> { return fold_(self, E.left, E.right) } /** * Executes this computation and returns its value, if it succeeds, but * otherwise executes the specified computation. * * @ets_data_first orElseEither_ */ export function orElseEither<R2, E2, A2>(that: () => Async<R2, E2, A2>) { return <R, E, A>(self: Async<R, E, A>): Async<R & R2, E2, E.Either<A, A2>> => orElseEither_(self, that) } /** * Executes this computation and returns its value, if it succeeds, but * otherwise executes the specified computation. */ export function orElseEither_<R, E, A, R2, E2, A2>( self: Async<R, E, A>, that: () => Async<R2, E2, A2> ): Async<R & R2, E2, E.Either<A, A2>> { return foldM_( self, () => map_(that(), (a) => E.right(a)), (a) => succeed(E.left(a)) ) } /** * Combines this computation with the specified computation, passing the * updated state from this computation to that computation and combining the * results of both using the specified function. * * @ets_data_first zipWith_ */ export function zipWith<R1, E1, A, B, C>(that: Async<R1, E1, B>, f: (a: A, b: B) => C) { return <R, E>(self: Async<R, E, A>): Async<R & R1, E1 | E, C> => zipWith_(self, that, f) } /** * Combines this computation with the specified computation, passing the * updated state from this computation to that computation and combining the * results of both using the specified function. */ export function zipWith_<R, E, A, R1, E1, B, C>( self: Async<R, E, A>, that: Async<R1, E1, B>, f: (a: A, b: B) => C ) { return chain_(self, (a) => map_(that, (b) => f(a, b))) } /** * Combines this computation with the specified computation, passing the * updated state from this computation to that computation and combining the * results of both into a tuple. * * @ets_data_first zip_ */ export function zip<R1, E1, B>(that: Async<R1, E1, B>) { return <R, E, A>(self: Async<R, E, A>) => zip_(self, that) } /** * Combines this computation with the specified computation, passing the * updated state from this computation to that computation and combining the * results of both into a tuple. */ export function zip_<R, E, A, R1, E1, B>(self: Async<R, E, A>, that: Async<R1, E1, B>) { return zipWith_(self, that, Tp.tuple) } /** * Suspend a computation, useful in recursion */ export function suspend<R, E, A>(f: () => Async<R, E, A>): Async<R, E, A> { return new ISuspend(f) } /** * Lift a sync (non failable) computation */ export function succeedWith<A>(f: () => A) { return suspend(() => succeed<A>(f())) } /** * Lift a sync (non failable) computation */ export function tryCatch<E, A>(f: () => A, onThrow: (u: unknown) => E) { return suspend(() => { try { return succeed<A>(f()) } catch (u) { return fail(onThrow(u)) } }) } // construct from a promise export function promise<E, A>( promise: (onInterrupt: (f: () => void) => void) => Promise<A>, onError: (u: unknown) => E ): Async<unknown, E, A> { return new IPromise(promise, onError) } // construct from a non failable promise export function unfailable<A>( promise: (onInterrupt: (f: () => void) => void) => Promise<A> ): Async<unknown, never, A> { return new IPromise(promise, () => undefined as never) } // construct a Task from an exit value export function done<E, A>(exit: Exit<E, A>): Async<unknown, E, A> { return new IDone(exit) } // like .then in Promise when the result of f is a Promise but ignores the outout of f // useful for logging or doing things that should not change the result export function tapError<EA, B, EB, R>(f: (_: EA) => Async<R, EB, B>) { return <R1, A>(self: Async<R1, EA, A>) => pipe( self, catchAll((e) => pipe( f(e), chain((_) => fail(e)) ) ) ) } // sleeps for ms milliseconds export function sleep(ms: number) { return unfailable( (onInterrupt) => new Promise((res) => { const timer = setTimeout(() => { res(undefined) }, ms) onInterrupt(() => { clearTimeout(timer) }) }) ) } // delay the computation prepending a sleep of ms milliseconds export function delay(ms: number) { return <R, E, A>(self: Async<R, E, A>) => pipe( sleep(ms), chain(() => self) ) } // list an Either export function fromEither<E, A>(e: E.Either<E, A>) { return e._tag === "Right" ? succeed(e.right) : fail(e.left) } /** * Compact the union produced by the result of f * * @ets_optimize identity */ export function unionFn<ARGS extends any[], Ret extends Async<any, any, any>>( _: (...args: ARGS) => Ret ): (...args: ARGS) => Async<U._R<Ret>, U._E<Ret>, U._A<Ret>> { return _ as any } /** * Compact the union * * @ets_optimize identity */ export function union<Ret extends Async<any, any, any>>( _: Ret ): Async<U._R<Ret>, U._E<Ret>, U._A<Ret>> { return _ as any } /** * Get the A from an option */ export default function tryCatchOption_<A, E>(ma: Option<A>, onNone: () => E) { return pipe(E.fromOption_(ma, onNone), fromEither) } /** * Get the A from an option * * @ets_data_first tryCatchOption_ */ export function tryCatchOption<A, E>(onNone: () => E) { return (ma: Option<A>) => tryCatchOption_(ma, onNone) }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/rolesMappers"; import * as Parameters from "../models/parameters"; import { DataBoxEdgeManagementClientContext } from "../dataBoxEdgeManagementClientContext"; /** Class representing a Roles. */ export class Roles { private readonly client: DataBoxEdgeManagementClientContext; /** * Create a Roles. * @param {DataBoxEdgeManagementClientContext} client Reference to the service client. */ constructor(client: DataBoxEdgeManagementClientContext) { this.client = client; } /** * Lists all the roles configured in a Data Box Edge/Data Box Gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.RolesListByDataBoxEdgeDeviceResponse> */ listByDataBoxEdgeDevice(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.RolesListByDataBoxEdgeDeviceResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param callback The callback */ listByDataBoxEdgeDevice(deviceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.RoleList>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param options The optional parameters * @param callback The callback */ listByDataBoxEdgeDevice(deviceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.RoleList>): void; listByDataBoxEdgeDevice(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.RoleList>, callback?: msRest.ServiceCallback<Models.RoleList>): Promise<Models.RolesListByDataBoxEdgeDeviceResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, options }, listByDataBoxEdgeDeviceOperationSpec, callback) as Promise<Models.RolesListByDataBoxEdgeDeviceResponse>; } /** * Gets a specific role by name. * @param deviceName The device name. * @param name The role name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.RolesGetResponse> */ get(deviceName: string, name: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.RolesGetResponse>; /** * @param deviceName The device name. * @param name The role name. * @param resourceGroupName The resource group name. * @param callback The callback */ get(deviceName: string, name: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.RoleUnion>): void; /** * @param deviceName The device name. * @param name The role name. * @param resourceGroupName The resource group name. * @param options The optional parameters * @param callback The callback */ get(deviceName: string, name: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.RoleUnion>): void; get(deviceName: string, name: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.RoleUnion>, callback?: msRest.ServiceCallback<Models.RoleUnion>): Promise<Models.RolesGetResponse> { return this.client.sendOperationRequest( { deviceName, name, resourceGroupName, options }, getOperationSpec, callback) as Promise<Models.RolesGetResponse>; } /** * Create or update a role. * @param deviceName The device name. * @param name The role name. * @param role The role properties. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.RolesCreateOrUpdateResponse> */ createOrUpdate(deviceName: string, name: string, role: Models.RoleUnion, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.RolesCreateOrUpdateResponse> { return this.beginCreateOrUpdate(deviceName,name,role,resourceGroupName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.RolesCreateOrUpdateResponse>; } /** * Deletes the role on the device. * @param deviceName The device name. * @param name The role name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(deviceName: string, name: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(deviceName,name,resourceGroupName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Create or update a role. * @param deviceName The device name. * @param name The role name. * @param role The role properties. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(deviceName: string, name: string, role: Models.RoleUnion, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, name, role, resourceGroupName, options }, beginCreateOrUpdateOperationSpec, options); } /** * Deletes the role on the device. * @param deviceName The device name. * @param name The role name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(deviceName: string, name: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, name, resourceGroupName, options }, beginDeleteMethodOperationSpec, options); } /** * Lists all the roles configured in a Data Box Edge/Data Box Gateway device. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.RolesListByDataBoxEdgeDeviceNextResponse> */ listByDataBoxEdgeDeviceNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.RolesListByDataBoxEdgeDeviceNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByDataBoxEdgeDeviceNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.RoleList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByDataBoxEdgeDeviceNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.RoleList>): void; listByDataBoxEdgeDeviceNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.RoleList>, callback?: msRest.ServiceCallback<Models.RoleList>): Promise<Models.RolesListByDataBoxEdgeDeviceNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByDataBoxEdgeDeviceNextOperationSpec, callback) as Promise<Models.RolesListByDataBoxEdgeDeviceNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByDataBoxEdgeDeviceOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/roles", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.RoleList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/roles/{name}", urlParameters: [ Parameters.deviceName, Parameters.name, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Role }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/roles/{name}", urlParameters: [ Parameters.deviceName, Parameters.name, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "role", mapper: { ...Mappers.Role, required: true } }, responses: { 200: { bodyMapper: Mappers.Role }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/roles/{name}", urlParameters: [ Parameters.deviceName, Parameters.name, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByDataBoxEdgeDeviceNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.RoleList }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import { loadConfig, resolveBindings, resolveProfile } from './config_loader.ts'; import { gzip, isAbsolute, resolve, fromFileUrl, relative } from './deps_cli.ts'; import { putScript, Binding as ApiBinding, listDurableObjectsNamespaces, createDurableObjectsNamespace, updateDurableObjectsNamespace, Part, Migrations } from '../common/cloudflare_api.ts'; import { CLI_VERSION } from './cli_version.ts'; import { Bytes } from '../common/bytes.ts'; import { isValidScriptName } from '../common/config_validation.ts'; import { computeContentsForScriptReference } from './cli_common.ts'; import { Script, Binding, isTextBinding, isSecretBinding, isKVNamespaceBinding, isDONamespaceBinding, isWasmModuleBinding, isServiceBinding } from '../common/config.ts'; import { ModuleWatcher } from './module_watcher.ts'; import { checkMatchesReturnMatcher } from '../common/check.ts'; export async function push(args: (string | number)[], options: Record<string, unknown>) { const scriptSpec = args[0]; if (options.help || typeof scriptSpec !== 'string') { dumpHelp(); return; } const nameFromOptions = typeof options.name === 'string' && options.name.trim().length > 0 ? options.name.trim() : undefined; const config = await loadConfig(options); const { scriptName, rootSpecifier, script } = await computeContentsForScriptReference(scriptSpec, config, nameFromOptions); if (!isValidScriptName(scriptName)) throw new Error(`Bad scriptName: ${scriptName}`); const { accountId, apiToken } = await resolveProfile(config, options); const watch = !!options.watch; let pushNumber = 1; const buildAndPutScript = async () => { const isModule = !rootSpecifier.endsWith('.js'); let scriptContentsStr = ''; if (isModule) { console.log(`bundling ${scriptName} into bundle.js...`); const start = Date.now(); const result = await Deno.emit(rootSpecifier, { bundle: 'module', }); console.log(`bundle finished in ${Date.now() - start}ms`); const blockingDiagnostics = result.diagnostics.filter(v => !isModuleJsonImportWarning(v)) if (blockingDiagnostics.length > 0) { console.warn(Deno.formatDiagnostics(blockingDiagnostics)); throw new Error('bundle failed'); } scriptContentsStr = result.files['deno:///bundle.js']; if (typeof scriptContentsStr !== 'string') throw new Error(`bundle.js not found in bundle output files: ${Object.keys(result.files).join(', ')}`); } else { scriptContentsStr = await Deno.readTextFile(rootSpecifier); } let start = Date.now(); const doNamespaces = new DurableObjectNamespaces(accountId, apiToken); const pushId = watch ? `${pushNumber}` : undefined; const pushIdSuffix = pushId ? ` ${pushId}` : ''; const usageModel = script?.usageModel; const { bindings, parts } = script ? await computeBindings(script, scriptName, doNamespaces, pushId) : { bindings: [], parts: [] }; console.log(`computed bindings in ${Date.now() - start}ms`); // only perform migrations on first upload, not on subsequent --watch uploads const migrations = pushNumber === 1 ? computeMigrations(options) : undefined; if (isModule) { scriptContentsStr = await rewriteScriptContents(scriptContentsStr, rootSpecifier, parts); } const scriptContents = new TextEncoder().encode(scriptContentsStr); const compressedScriptContents = gzip(scriptContents); console.log(`putting ${isModule ? 'module' : 'script'}-based ${usageModel} worker ${scriptName}${pushIdSuffix}... ${computeSizeString(scriptContents, compressedScriptContents, parts)}`); if (migrations && migrations.deleted_classes.length > 0) { console.log(` migration will delete durable object class(es): ${migrations.deleted_classes.join(', ')}`); } start = Date.now(); await putScript(accountId, scriptName, apiToken, { scriptContents, bindings, migrations, parts, isModule, usageModel }); console.log(`put script ${scriptName}${pushIdSuffix} in ${Date.now() - start}ms`); pushNumber++; if (doNamespaces.hasPendingUpdates()) { start = Date.now(); await doNamespaces.flushPendingUpdates(); console.log(`updated durable object namespaces in ${Date.now() - start}ms`); } } await buildAndPutScript(); if (watch) { console.log('Watching for changes...'); const scriptUrl = rootSpecifier.startsWith('https://') ? new URL(rootSpecifier) : undefined; if (scriptUrl && !scriptUrl.pathname.endsWith('.ts')) throw new Error('Url-based module workers must end in .ts'); const scriptPathOrUrl = scriptUrl ? scriptUrl.toString() : script ? script.path : isAbsolute(rootSpecifier) ? rootSpecifier : resolve(Deno.cwd(), rootSpecifier); const _moduleWatcher = new ModuleWatcher(scriptPathOrUrl, async () => { try { await buildAndPutScript(); } catch (e) { console.error(e); } finally { console.log('Watching for changes...'); } }); return new Promise(() => {}); } } // function isModuleJsonImportWarning(diag: Deno.Diagnostic): boolean { /* these seem to be non-fatal { category: 1, code: 7042, start: { line: 3, character: 21 }, end: { line: 3, character: 38 }, messageText: "Module './whatever.json' was resolved to 'file:///file/to/whatever.json', but '--resolveJsonModule' is not used.", messageChain: null, source: null, sourceLine: "import whatever from './whatever.json' assert { type: 'json' };", fileName: "file:///path/to/whatever.ts", relatedInformation: null }, */ return diag.category === 1 && diag.code === 7042 } function computeMigrations(options: Record<string, unknown>): Migrations | undefined { const option = options['delete-class']; const deleted_classes = typeof option === 'string' ? [ option ] : Array.isArray(option) && option.every(v => typeof v === 'string') ? option as string[] : []; return deleted_classes.length > 0 ? { tag: `delete-${deleted_classes.join('-')}`, deleted_classes } : undefined; } function computeSizeString(scriptContents: Uint8Array, compressedScriptContents: Uint8Array, parts: Part[]): string { let uncompressedSize = scriptContents.length; let compressedSize = compressedScriptContents.length; for (const { name, valueBytes } of parts) { if (!valueBytes) throw new Error(`Unable to compute size for part: ${name}`); uncompressedSize += valueBytes.length; const compressedValueBytes = gzip(valueBytes); compressedSize += compressedValueBytes.length; } return `(${Bytes.formatSize(uncompressedSize)}) (${Bytes.formatSize(compressedSize)} compressed)`; } async function rewriteScriptContents(scriptContents: string, rootSpecifier: string, parts: Part[]): Promise<string> { const p = /const\s+([a-zA-Z0-9_]+)\s*=\s*await\s+import(Wasm|Text|Binary)\d*\(\s*(importMeta\d*)\.url\s*,\s*'((https:\/|\.)\/[\/.a-zA-Z0-9_-]+)'\s*\)\s*;?/g; let m: RegExpExecArray | null; let i = 0; const pieces = []; while((m = p.exec(scriptContents)) !== null) { const { index } = m; pieces.push(scriptContents.substring(i, index)); const line = m[0]; const variableName = m[1]; const importType = m[2]; const importMetaVariableName = m[3]; const unquotedModuleSpecifier = m[4]; const importMetaUrl = findImportMetaUrl(importMetaVariableName, scriptContents); const { relativePath, valueBytes, valueType } = await resolveImport({ importType, importMetaUrl, unquotedModuleSpecifier, rootSpecifier }); const value = new Blob([ valueBytes ], { type: valueType }); parts.push({ name: relativePath, fileName: relativePath, value, valueBytes }); pieces.push(`import ${variableName} from "${relativePath}";`); i = index + line.length; } if (pieces.length === 0) return scriptContents; pieces.push(scriptContents.substring(i)); return pieces.join(''); } function findImportMetaUrl(importMetaVariableName: string, scriptContents: string): string { const m = new RegExp(`.*const ${importMetaVariableName} = {\\s*url: "((file|https):.*?)".*`, 's').exec(scriptContents); if (!m) throw new Error(`findImportMetaUrl: Unable to find importMetaVariableName ${importMetaVariableName}`); return m[1]; } async function resolveImport(opts: { importType: string, importMetaUrl: string, unquotedModuleSpecifier: string, rootSpecifier: string }): Promise<{ relativePath: string, valueBytes: Uint8Array, valueType: string }> { const { importType, importMetaUrl, unquotedModuleSpecifier, rootSpecifier } = opts; const tag = `resolveImport${importType}`; const valueType = importType === 'Wasm' ? 'application/wasm' : importType === 'Text' ? 'text/plain' : 'application/octet-stream'; const isExpectedContentType: (contentType: string) => boolean = importType === 'Wasm' ? (v => ['application/wasm', 'application/octet-stream'].includes(v)) : importType === 'Text' ? (v => v.startsWith('text/')) : (_ => true); const fetchContents = async (url: string) => { console.log(`${tag}: Fetching ${url}`); const res = await fetch(url); if (res.status !== 200) throw new Error(`Bad status ${res.status}, expected 200 for ${url}`); const contentType = (res.headers.get('content-type') || '').toLowerCase(); if (!isExpectedContentType(contentType)) throw new Error(`${tag}: Unexpected content-type ${contentType} for ${url}`); const valueBytes = new Uint8Array(await res.arrayBuffer()); const relativePath = 'https/' + url.substring('https://'.length); return { relativePath, valueBytes, valueType }; } if (unquotedModuleSpecifier.startsWith('https://')) { return await fetchContents(unquotedModuleSpecifier); } if (importMetaUrl.startsWith('file://')) { const localPath = resolve(resolve(fromFileUrl(importMetaUrl), '..'), unquotedModuleSpecifier); const rootSpecifierDir = resolve(rootSpecifier, '..'); const relativePath = relative(rootSpecifierDir, localPath); const valueBytes = await Deno.readFile(localPath); return { relativePath, valueBytes, valueType }; } else if (importMetaUrl.startsWith('https://')) { const { pathname, origin } = new URL(importMetaUrl); const url = origin + resolve(resolve(pathname, '..'), unquotedModuleSpecifier); return await fetchContents(url); } else { throw new Error(`${tag}: Unsupported importMetaUrl: ${importMetaUrl}`); } } // class DurableObjectNamespaces { private readonly accountId: string; private readonly apiToken: string; private readonly pendingUpdates: { id: string, name?: string, script?: string, class?: string }[] = []; constructor(accountId: string, apiToken: string) { this.accountId = accountId; this.apiToken = apiToken; } async getOrCreateNamespaceId(namespaceSpec: string, scriptName: string): Promise<string> { const tokens = namespaceSpec.split(':'); if (tokens.length !== 2) throw new Error(`Bad durable object namespace spec: ${namespaceSpec}`); const name = tokens[0]; if (!/^[a-zA-Z0-9_-]+$/.test(name)) throw new Error(`Bad durable object namespace name: ${name}`); const className = tokens[1]; const namespaces = await listDurableObjectsNamespaces(this.accountId, this.apiToken); let namespace = namespaces.find(v => v.name === name); if (!namespace) { console.log(`Creating new durable object namespace: ${name}`); namespace = await createDurableObjectsNamespace(this.accountId, this.apiToken, { name }); } if (namespace.class !== className || namespace.script !== scriptName) { this.pendingUpdates.push({ id: namespace.id, name, script: scriptName, class: className }); } return namespace.id; } hasPendingUpdates() { return this.pendingUpdates.length > 0; } async flushPendingUpdates() { for (const payload of this.pendingUpdates) { console.log(`Updating durable object namespace ${payload.name}: script=${payload.script}, class=${payload.class}`); await updateDurableObjectsNamespace(this.accountId, this.apiToken, payload); } this.pendingUpdates.splice(0); } } // async function computeBindings(script: Script, scriptName: string, doNamespaces: DurableObjectNamespaces, pushId: string | undefined): Promise<{ bindings: ApiBinding[], parts: Part[] }> { const resolvedBindings = await resolveBindings(script.bindings || {}, undefined, pushId); const bindings: ApiBinding[] = []; const partsMap: Record<string, Part> = {}; for (const [name, binding] of Object.entries(resolvedBindings)) { bindings.push(await computeBinding(name, binding, doNamespaces, scriptName, partsMap)); } return { bindings, parts: Object.values(partsMap) }; } async function computeBinding(name: string, binding: Binding, doNamespaces: DurableObjectNamespaces, scriptName: string, parts: Record<string, Part>): Promise<ApiBinding> { if (isTextBinding(binding)) { return { type: 'plain_text', name, text: binding.value }; } else if (isSecretBinding(binding)) { return { type: 'secret_text', name, text: binding.secret }; } else if (isKVNamespaceBinding(binding)) { return { type: 'kv_namespace', name, namespace_id: binding.kvNamespace }; } else if (isDONamespaceBinding(binding)) { return { type: 'durable_object_namespace', name, namespace_id: await doNamespaces.getOrCreateNamespaceId(binding.doNamespace, scriptName) }; } else if (isWasmModuleBinding(binding)) { return { type: 'wasm_module', name, part: await computeWasmModulePart(binding.wasmModule, parts, name) }; } else if (isServiceBinding(binding)) { const [ _, service, environment ] = checkMatchesReturnMatcher('serviceEnvironment', binding.serviceEnvironment, /^(.*?):(.*?)$/); return { type: 'service', name, service, environment }; } else { throw new Error(`Unsupported binding ${name}: ${binding}`); } } async function computeWasmModulePart(wasmModule: string, parts: Record<string, Part>, name: string): Promise<string> { const valueBytes = await Deno.readFile(wasmModule); const part = name; parts[part] = { name, value: new Blob([ valueBytes ], { type: 'application/wasm' }), valueBytes }; return part; } function dumpHelp() { const lines = [ `denoflare-push ${CLI_VERSION}`, 'Upload a worker script to Cloudflare Workers', '', 'USAGE:', ' denoflare push [FLAGS] [OPTIONS] [--] [script-spec]', '', 'FLAGS:', ' -h, --help Prints help information', ' --verbose Toggle verbose output (when applicable)', ' --watch Re-upload the worker script when local changes are detected', '', 'OPTIONS:', ' -n, --name <name> Name to use for Cloudflare Worker script [default: Name of script defined in .denoflare config, or https url basename sans extension]', ' --profile <name> Name of profile to load from config (default: only profile or default profile in config)', ' --config <path> Path to config file (default: .denoflare in cwd or parents)', ' --delete-class <name> Delete an obsolete Durable Object (and all data!) by class name', '', 'ARGS:', ' <script-spec> Name of script defined in .denoflare config, file path to bundled js worker, or an https url to a module-based worker .ts, e.g. https://path/to/worker.ts', ]; for (const line of lines) { console.log(line); } }
the_stack
import { Inject, Injectable, OnDestroy } from "@angular/core"; import { _INVERTED_SHIFT_MAP, _KEYCODE_MAP, _MAP, _SHIFT_MAP, _SPECIAL_CASES, modifiers } from "./keys"; import { BehaviorSubject, fromEvent, Observable, Subject, Subscription, throwError, timer, of } from "rxjs"; import { ParsedShortcut, ShortcutEventOutput, ShortcutInput } from "./ng-keyboard-shortcuts.interfaces"; import { catchError, filter, first, map, repeat, scan, switchMap, takeUntil, tap, throttle } from "rxjs/operators"; import { allPass, any, difference, identity, isFunction, isNill, maxArrayProp } from "./utils"; import { DOCUMENT } from "@angular/common"; /** * @ignore * @type {number} */ let guid = 0; @Injectable({ providedIn: "root" }) export class KeyboardShortcutsService implements OnDestroy { /** * Parsed shortcuts * for each key create a predicate function */ private _shortcuts: ParsedShortcut[] = []; private _sequences: ParsedShortcut[] = []; /** * Throttle the keypress event. */ private throttleTime = 0; private _pressed = new Subject<ShortcutEventOutput>(); /** * Streams of pressed events, can be used instead or with a command. */ public pressed$ = this._pressed.asObservable(); /** * Disable all keyboard shortcuts */ private disabled = false; /** * @ignore * 2000 ms window to allow between key sequences otherwise * the sequence will reset. */ private static readonly TIMEOUT_SEQUENCE = 1000; private _shortcutsSub = new BehaviorSubject<ParsedShortcut[]>([]); public shortcuts$ = this._shortcutsSub .asObservable() .pipe(filter(shortcuts => !!shortcuts.length)); private _ignored = ["INPUT", "TEXTAREA", "SELECT"]; /** * @ignore * Subscription for on destroy. */ private readonly subscriptions: Subscription[] = []; /** * @ignore * @param shortcut */ private isAllowed = (shortcut: ParsedShortcut) => { const target = shortcut.event.target as HTMLElement; if (target === shortcut.target) { return true; } if (shortcut.allowIn.length) { return !difference(this._ignored, shortcut.allowIn).includes(target.nodeName); } return !this._ignored.includes(target.nodeName); }; /** * @ignore * @param event */ private mapEvent = event => { return this._shortcuts .filter(shortcut => !shortcut.isSequence) .map(shortcut => Object.assign({}, shortcut, { predicates: any( identity, shortcut.predicates.map((predicates: any) => allPass(predicates)(event)) ), event: event }) ) .filter(shortcut => shortcut.predicates) .reduce((acc, shortcut) => (acc.priority > shortcut.priority ? acc : shortcut), { priority: 0 } as ParsedShortcut); }; private keydown$ = fromEvent(this.document, "keydown"); /** * fixes for firefox prevent default * on click event on button focus: * see issue: * keeping this here for now, but it is commented out * Firefox reference bug: * https://bugzilla.mozilla.org/show_bug.cgi?id=1487102 * and my repo: * * https://github.com/omridevk/ng-keyboard-shortcuts/issues/35 */ private ignore$ = this.pressed$.pipe( filter(e => e.event.defaultPrevented), switchMap(() => this.clicks$.pipe(first())), tap((e: any) => { e.preventDefault(); e.stopPropagation(); }), repeat() ); /** * @ignore */ private clicks$ = fromEvent(this.document, "click", { capture: true }); private keyup$ = fromEvent(this.document, "keyup"); /** * @ignore */ private keydownCombo$ = this.keydown$.pipe( filter(_ => !this.disabled), map(this.mapEvent), filter( (shortcut: ParsedShortcut) => !shortcut.target || shortcut.event.target === shortcut.target ), filter((shortcut: ParsedShortcut) => isFunction(shortcut.command)), filter(this.isAllowed), tap(shortcut => { if (!shortcut.preventDefault) { return; } shortcut.event.preventDefault(); shortcut.event.stopPropagation(); }), throttle(shortcut => timer(shortcut.throttleTime)), tap(shortcut => shortcut.command({ event: shortcut.event, key: shortcut.key })), tap(shortcut => this._pressed.next({ event: shortcut.event, key: shortcut.key })), takeUntil(this.keyup$), repeat(), catchError(error => throwError(error)) ); /** * @ignore */ private timer$ = new Subject(); /** * @ignore */ private resetCounter$ = this.timer$ .asObservable() .pipe(switchMap(() => timer(KeyboardShortcutsService.TIMEOUT_SEQUENCE))); /** * @ignore */ private keydownSequence$ = this.shortcuts$.pipe( map(shortcuts => shortcuts.filter(shortcut => shortcut.isSequence)), switchMap(sequences => this.keydown$.pipe( map(event => { return { event, sequences }; }), tap(this.timer$) ) ), scan( (acc: { events: any[]; command?: any; sequences: any[] }, arg: any) => { let { event } = arg; const currentLength = acc.events.length; const sequences = currentLength ? acc.sequences : arg.sequences; let [characters] = this.characterFromEvent(event); characters = Array.isArray(characters) ? [...characters, event.key] : [characters, event.key]; const result = sequences .map(sequence => { const sequences = sequence.sequence.filter(seque => characters.some( key => (_SPECIAL_CASES[seque[currentLength]] || seque[currentLength]) === key ) ); const partialMatch = sequences.length > 0; if (sequence.fullMatch) { return sequence; } return { ...sequence, sequence: sequences, partialMatch, event: event, fullMatch: partialMatch && this.isFullMatch({ command: sequence, events: acc.events }) }; }) .filter(sequences => sequences.partialMatch || sequences.fullMatch); let [match] = result; if (!match || this.modifiersOn(event)) { return { events: [], sequences: this._sequences }; } /* * handle case of "?" sequence and "? a" sequence * need to determine which one to trigger. * if both match, we pick the longer one (? a) in this case. */ const guess = maxArrayProp("priority", result); if (result.length > 1 && guess.fullMatch) { return { events: [], command: guess, sequences: this._sequences }; } if (result.length > 1) { return { events: [...acc.events, event], command: result, sequences: result }; } if (match.fullMatch) { return { events: [], command: match, sequences: this._sequences }; } return { events: [...acc.events, event], command: result, sequences: result }; }, { events: [], sequences: [] } ), switchMap(({ command }) => { if (Array.isArray(command)) { /* * Add a timer to handle the case where for example: * a sequence "?" is registered and "? a" is registered as well * if the user does not hit any key for 500ms, the single sequence will trigger * if any keydown event occur, this timer will reset, given a chance to complete * the full sequence (? a) in this case. * This delay only occurs when single key sequence is the beginning of another sequence. */ return timer(500).pipe( map(() => ({ command: command.filter(command => command.fullMatch)[0] })) ); } return of({ command }); }), takeUntil(this.pressed$), filter(({ command }) => command && command.fullMatch), map(({ command }) => command), filter((shortcut: ParsedShortcut) => isFunction(shortcut.command)), filter( (shortcut: ParsedShortcut) => !shortcut.target || shortcut.event.target === shortcut.target ), filter(this.isAllowed), tap(shortcut => !shortcut.preventDefault || shortcut.event.preventDefault()), throttle(shortcut => timer(shortcut.throttleTime)), tap(shortcut => shortcut.command({ event: shortcut.event, key: shortcut.key })), tap(shortcut => this._pressed.next({ event: shortcut.event, key: shortcut.key })), takeUntil(this.resetCounter$), repeat() ); /** * @ignore * @param command * @param events */ private isFullMatch({ command, events }) { if (!command) { return false; } return command.sequence.some(sequence => { return sequence.length === events.length + 1; }); } /** * @ignore */ private get shortcuts() { return this._shortcuts; } /** * @ignore */ constructor(@Inject(DOCUMENT) private document: any) { this.subscriptions.push( this.keydownSequence$.subscribe(), this.keydownCombo$.subscribe() // this.ignore$.subscribe() ); } /** * @ignore * @param event */ private _characterFromEvent(event): [string, boolean] { if (typeof event.which !== "number") { event.which = event.keyCode; } if (_SPECIAL_CASES[event.which]) { return [_SPECIAL_CASES[event.which], event.shiftKey]; } if (_MAP[event.which]) { // for non keypress events the special maps are needed return [_MAP[event.which], event.shiftKey]; } if (_KEYCODE_MAP[event.which]) { return [_KEYCODE_MAP[event.which], event.shiftKey]; } // in case event key is lower case but registered key is upper case // return it in the lower case if (String.fromCharCode(event.which).toLowerCase() !== event.key) { return [String.fromCharCode(event.which).toLowerCase(), event.shiftKey]; } return [event.key, event.shiftKey]; } private characterFromEvent(event) { let [key, shiftKey] = this._characterFromEvent(event); if (shiftKey && _SHIFT_MAP[key]) { return [_SHIFT_MAP[key], shiftKey]; } return [key, shiftKey]; } /** * @ignore * Remove subscription. */ ngOnDestroy(): void { this.subscriptions.forEach(sub => sub.unsubscribe()); } /** * @ignore * @param shortcuts */ private isSequence(shortcuts: string[]): boolean { return !shortcuts.some(shortcut => shortcut.includes("+") || shortcut.length === 1); } /** * Add new shortcut/s */ public add(shortcuts: ShortcutInput[] | ShortcutInput): string[] { shortcuts = Array.isArray(shortcuts) ? shortcuts : [shortcuts]; const commands = this.parseCommand(shortcuts); commands.forEach(command => { if (command.isSequence) { this._sequences.push(command); return; } this._shortcuts.push(command); }); setTimeout(() => { this._shortcutsSub.next([...this._shortcuts, ...this._sequences]); }); return commands.map(command => command.id); } /** * Remove a command based on key or array of keys. * can be used for cleanup. * @returns * @param ids */ public remove(ids: string | string[]): KeyboardShortcutsService { ids = Array.isArray(ids) ? ids : [ids]; this._shortcuts = this._shortcuts.filter(shortcut => !ids.includes(shortcut.id)); this._sequences = this._sequences.filter(shortcut => !ids.includes(shortcut.id)); setTimeout(() => { this._shortcutsSub.next([...this._shortcuts, ...this._sequences]); }); return this; } /** * Returns an observable of keyboard shortcut filtered by a specific key. * @param key - the key to filter the observable by. */ public select(key: string): Observable<ShortcutEventOutput> { return this.pressed$.pipe( filter(({ event, key: eventKeys }) => { eventKeys = Array.isArray(eventKeys) ? eventKeys : [eventKeys]; return !!eventKeys.find(eventKey => eventKey === key); }) ); } /** * @ignore * transforms a shortcut to: * a predicate function */ private getKeys = (keys: string[]) => { return keys .map(key => key.trim()) .filter(key => key !== "+") .map(key => { // for modifiers like control key // look for event['ctrlKey'] // otherwise use the keyCode key = _SPECIAL_CASES[key] || key; if (modifiers.hasOwnProperty(key)) { return event => { return !!event[modifiers[key]]; }; } return event => { const isUpper = key === key.toUpperCase(); const isNonAlpha = (/[^a-zA-Z\d\s:]/).test(key); const inShiftMap = _INVERTED_SHIFT_MAP[key]; let [characters, shiftKey] = this.characterFromEvent(event); const allModifiers = Object.keys(modifiers).map((key) => { return modifiers[key]; }) const hasModifiers = allModifiers.some(modifier => event[modifier]); characters = Array.isArray(characters) ? [...characters, event.key] : [characters, event.key]; // if has modifiers: // we want to make sure it is not upper case letters // (because upper has modifiers so we want continue the check) // we also want to make sure it is not alphanumeric char like ? / ^ & and others (since those could require modifiers as well) // we also want to check this only if the length of // of the keys is one (i.e the command key is "?" or "c" // this while check is here to verify that: // if registered key like "e" // it won't be fired when clicking ctrl + e, or any modifiers + the key // we only want to trigger when the single key is clicked alone // thus all these edge cases. // hopefully this would cover all cases // TODO:: find a way simplify this if (hasModifiers && (!isUpper || isNonAlpha) && !inShiftMap && keys.length === 1) { return false; } return characters.some(char => { if (char === key && isUpper) { return true; } return key === char; }); }; }); }; /** * @ignore * @param event */ private modifiersOn(event) { return ["metaKey", "altKey", "ctrlKey"].some(mod => event[mod]); } /** * @ignore * Parse each command using getKeys function */ private parseCommand(command: ShortcutInput | ShortcutInput[]): ParsedShortcut[] { const commands = Array.isArray(command) ? command : [command]; return commands.map(command => { const keys = Array.isArray(command.key) ? command.key : [command.key]; const priority = Math.max(...keys.map(key => key.split(" ").filter(identity).length)); const predicates = keys.map(key => this.getKeys(key.split(" ").filter(identity))); const isSequence = this.isSequence(keys); const sequence = isSequence ? keys.map(key => key .split(" ") .filter(identity) .map(key => key.trim()) ) : []; return { ...command, isSequence, sequence: isSequence ? sequence : [], allowIn: command.allowIn || [], key: keys, id: `${guid++}`, throttle: isNill(command.throttleTime) ? this.throttleTime : command.throttleTime, priority: priority, predicates: predicates } as ParsedShortcut; }); } }
the_stack
import * as coreHttp from "@azure/core-http"; export interface DetectRequest { /** Time series data points. Points should be sorted by timestamp in ascending order to match the anomaly detection result. If the data is not sorted correctly or there is duplicated timestamp, the API will not work. In such case, an error message will be returned. */ series: TimeSeriesPoint[]; /** Optional argument, can be one of yearly, monthly, weekly, daily, hourly, minutely, secondly, microsecond or none. If granularity is not present, it will be none by default. If granularity is none, the timestamp property in time series point can be absent. */ granularity?: TimeGranularity; /** Custom Interval is used to set non-standard time interval, for example, if the series is 5 minutes, request can be set as {"granularity":"minutely", "customInterval":5}. */ customInterval?: number; /** Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically. */ period?: number; /** Optional argument, advanced model parameter, max anomaly ratio in a time series. */ maxAnomalyRatio?: number; /** Optional argument, advanced model parameter, between 0-99, the lower the value is, the larger the margin value will be which means less anomalies will be accepted. */ sensitivity?: number; } export interface TimeSeriesPoint { /** Optional argument, timestamp of a data point (ISO8601 format). */ timestamp?: Date; /** The measurement of that point, should be float. */ value: number; } export interface DetectEntireResponse { /** Frequency extracted from the series, zero means no recurrent pattern has been found. */ period: number; /** ExpectedValues contain expected value for each input point. The index of the array is consistent with the input series. */ expectedValues: number[]; /** UpperMargins contain upper margin of each input point. UpperMargin is used to calculate upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. Anomalies in response can be filtered by upperBoundary and lowerBoundary. By adjusting marginScale value, less significant anomalies can be filtered in client side. The index of the array is consistent with the input series. */ upperMargins: number[]; /** LowerMargins contain lower margin of each input point. LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. Points between the boundary can be marked as normal ones in client side. The index of the array is consistent with the input series. */ lowerMargins: number[]; /** IsAnomaly contains anomaly properties for each input point. True means an anomaly either negative or positive has been detected. The index of the array is consistent with the input series. */ isAnomaly: boolean[]; /** IsNegativeAnomaly contains anomaly status in negative direction for each input point. True means a negative anomaly has been detected. A negative anomaly means the point is detected as an anomaly and its real value is smaller than the expected one. The index of the array is consistent with the input series. */ isNegativeAnomaly: boolean[]; /** IsPositiveAnomaly contain anomaly status in positive direction for each input point. True means a positive anomaly has been detected. A positive anomaly means the point is detected as an anomaly and its real value is larger than the expected one. The index of the array is consistent with the input series. */ isPositiveAnomaly: boolean[]; } /** Error information returned by the API. */ export interface AnomalyDetectorError { /** The error code. */ code?: AnomalyDetectorErrorCodes; /** A message explaining the error reported by the service. */ message?: string; } export interface DetectLastPointResponse { /** Frequency extracted from the series, zero means no recurrent pattern has been found. */ period: number; /** Suggested input series points needed for detecting the latest point. */ suggestedWindow: number; /** Expected value of the latest point. */ expectedValue: number; /** Upper margin of the latest point. UpperMargin is used to calculate upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. If the value of latest point is between upperBoundary and lowerBoundary, it should be treated as normal value. By adjusting marginScale value, anomaly status of latest point can be changed. */ upperMargin: number; /** Lower margin of the latest point. LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. */ lowerMargin: number; /** Anomaly status of the latest point, true means the latest point is an anomaly either in negative direction or positive direction. */ isAnomaly: boolean; /** Anomaly status in negative direction of the latest point. True means the latest point is an anomaly and its real value is smaller than the expected one. */ isNegativeAnomaly: boolean; /** Anomaly status in positive direction of the latest point. True means the latest point is an anomaly and its real value is larger than the expected one. */ isPositiveAnomaly: boolean; } export interface DetectChangePointRequest { /** Time series data points. Points should be sorted by timestamp in ascending order to match the change point detection result. */ series: TimeSeriesPoint[]; /** Can only be one of yearly, monthly, weekly, daily, hourly, minutely or secondly. Granularity is used for verify whether input series is valid. */ granularity: TimeGranularity; /** Custom Interval is used to set non-standard time interval, for example, if the series is 5 minutes, request can be set as {"granularity":"minutely", "customInterval":5}. */ customInterval?: number; /** Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically. */ period?: number; /** Optional argument, advanced model parameter, a default stableTrendWindow will be used in detection. */ stableTrendWindow?: number; /** Optional argument, advanced model parameter, between 0.0-1.0, the lower the value is, the larger the trend error will be which means less change point will be accepted. */ threshold?: number; } export interface DetectChangePointResponse { /** * Frequency extracted from the series, zero means no recurrent pattern has been found. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly period?: number; /** isChangePoint contains change point properties for each input point. True means an anomaly either negative or positive has been detected. The index of the array is consistent with the input series. */ isChangePoint?: boolean[]; /** the change point confidence of each point */ confidenceScores?: number[]; } /** Train result of a model including status, errors and diagnose info for model and variables. */ export interface ModelInfo { /** An optional field, indicates how many history points will be used to determine the anomaly score of one subsequent point. */ slidingWindow?: number; /** An optional field, since those multivariate need to be aligned in the same timestamp before starting the detection. */ alignPolicy?: AlignPolicy; /** source file link of the input variables, each variable will be a csv with two columns, the first column will be timestamp, the second column will be value.Besides these variable csv files, an extra meta.json can be included in th zip file if you would like to rename a variable.Be default, the file name of the variable will be used as the variable name. */ source: string; /** require field, start time of data be used for generating multivariate anomaly detection model, should be data-time */ startTime: Date; /** require field, end time of data be used for generating multivariate anomaly detection model, should be data-time */ endTime: Date; /** optional field, name of the model */ displayName?: string; /** * Model training status. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly status?: ModelStatus; /** * Error message when fails to create a model. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly errors?: ErrorResponse[]; /** * Used for deep analysis model and variables * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly diagnosticsInfo?: DiagnosticsInfo; } export interface AlignPolicy { /** An optional field, indicates how we align different variables into the same time-range which is required by the model.{Inner, Outer} */ alignMode?: AlignMode; /** An optional field, indicates how missed values will be filled with. Can not be set to NotFill, when alignMode is Outer.{Previous, Subsequent, Linear, Zero, Fix, NotFill} */ fillNAMethod?: FillNAMethod; /** optional field, only be useful if FillNAMethod is set to Pad. */ paddingValue?: number; } export interface ErrorResponse { /** The error Code */ code: string; /** A message explaining the error reported by the service. */ message: string; } export interface DiagnosticsInfo { modelState?: ModelState; variableStates?: VariableState[]; } export interface ModelState { /** Epoch id */ epochIds?: number[]; trainLosses?: number[]; validationLosses?: number[]; latenciesInSeconds?: number[]; } export interface VariableState { /** Variable name. */ variable?: string; /** Merged NA ratio of a variable. */ filledNARatio?: number; /** Effective time-series points count. */ effectiveCount?: number; /** Start time of a variable */ startTime?: Date; /** End time of a variable */ endTime?: Date; /** Error message when parse variable */ errors?: ErrorResponse[]; } /** Response of get model. */ export interface Model { /** Model identifier. */ modelId: string; /** Date and time (UTC) when the model was created. */ createdTime: Date; /** Date and time (UTC) when the model was last updated. */ lastUpdatedTime: Date; /** Training Status of the model. */ modelInfo?: ModelInfo; } /** Request to submit a detection. */ export interface DetectionRequest { /** source file link of the input variables, each variable will be a csv with two columns, the first column will be timestamp, the second column will be value.Besides these variable csv files, a extra meta.json can be included in th zip file if you would like to rename a variable.Be default, the file name of the variable will be used as the variable name. The variables used in detection should be consistent with variables in the model used for detection. */ source: string; /** A require field, start time of data be used for detection, should be date-time. */ startTime: Date; /** A require field, end time of data be used for detection, should be date-time. */ endTime: Date; } /** Anomaly Response of one detection corresponds to a resultId. */ export interface DetectionResult { resultId: string; /** Multivariate anomaly detection status */ summary: DetectionResultSummary; /** anomaly status of each timestamp */ results: AnomalyState[]; } export interface DetectionResultSummary { /** Multivariate anomaly detection status */ status: DetectionStatus; /** Error message when creating or training model fails. */ errors?: ErrorResponse[]; variableStates?: VariableState[]; /** Request when creating the model. */ setupInfo: DetectionRequest; } export interface AnomalyState { /** timestamp */ timestamp: Date; value?: AnomalyValue; /** Error message when inference this timestamp */ errors?: ErrorResponse[]; } export interface AnomalyValue { /** If current timestamp is an anomaly, contributors will show potential root cause for thus anomaly. Contributors can help us understand why current timestamp has been detected as an anomaly. */ contributors?: AnomalyContributor[]; /** To indicate whether current timestamp is anomaly or not */ isAnomaly: boolean; /** anomaly score of the current timestamp, the more significant an anomaly is, the higher the score will be */ severity: number; /** anomaly score of the current timestamp, the more significant an anomaly is, the higher the score will be, score measures global significance */ score?: number; } export interface AnomalyContributor { /** The higher the contribution score is, the more likely the variable to be the root cause of a anomaly. */ contributionScore?: number; /** Variable name of a contributor */ variable?: string; } /** Response to the list models operation. */ export interface ModelList { /** List of models */ models: ModelSnapshot[]; /** Current count of trained multivariate models. */ currentCount: number; /** Max number of models that can be trained for this subscription. */ maxCount: number; /** next link to fetch more models */ nextLink?: string; } export interface ModelSnapshot { /** Model identifier. */ modelId: string; /** Date and time (UTC) when the model was created. */ createdTime: Date; /** Date and time (UTC) when the model was last updated. */ lastUpdatedTime: Date; /** * Model training status. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly status: ModelStatus; displayName?: string; /** Count of variables */ variablesCount: number; } /** Defines headers for AnomalyDetector_trainMultivariateModel operation. */ export interface AnomalyDetectorTrainMultivariateModelHeaders { /** Location and ID of the model being saved. */ location?: string; } /** Defines headers for AnomalyDetector_detectAnomaly operation. */ export interface AnomalyDetectorDetectAnomalyHeaders { /** Location and ID of the detection result being saved. */ location?: string; } /** Defines headers for AnomalyDetector_exportModel operation. */ export interface AnomalyDetectorExportModelHeaders { /** application/zip */ contentType?: string; } /** Known values of {@link AnomalyDetectorErrorCodes} that the service accepts. */ export const enum KnownAnomalyDetectorErrorCodes { InvalidCustomInterval = "InvalidCustomInterval", BadArgument = "BadArgument", InvalidGranularity = "InvalidGranularity", InvalidPeriod = "InvalidPeriod", InvalidModelArgument = "InvalidModelArgument", InvalidSeries = "InvalidSeries", InvalidJsonFormat = "InvalidJsonFormat", RequiredGranularity = "RequiredGranularity", RequiredSeries = "RequiredSeries" } /** * Defines values for AnomalyDetectorErrorCodes. \ * {@link KnownAnomalyDetectorErrorCodes} can be used interchangeably with AnomalyDetectorErrorCodes, * this enum contains the known values that the service supports. * ### Know values supported by the service * **InvalidCustomInterval** \ * **BadArgument** \ * **InvalidGranularity** \ * **InvalidPeriod** \ * **InvalidModelArgument** \ * **InvalidSeries** \ * **InvalidJsonFormat** \ * **RequiredGranularity** \ * **RequiredSeries** */ export type AnomalyDetectorErrorCodes = string; /** Defines values for TimeGranularity. */ export type TimeGranularity = | "yearly" | "monthly" | "weekly" | "daily" | "hourly" | "minutely" | "secondly" | "microsecond" | "none"; /** Defines values for AlignMode. */ export type AlignMode = "Inner" | "Outer"; /** Defines values for FillNAMethod. */ export type FillNAMethod = | "Previous" | "Subsequent" | "Linear" | "Zero" | "Pad" | "NotFill"; /** Defines values for ModelStatus. */ export type ModelStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; /** Defines values for DetectionStatus. */ export type DetectionStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; /** Contains response data for the detectEntireSeries operation. */ export type AnomalyDetectorDetectEntireSeriesResponse = DetectEntireResponse & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: DetectEntireResponse; }; }; /** Contains response data for the detectLastPoint operation. */ export type AnomalyDetectorDetectLastPointResponse = DetectLastPointResponse & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: DetectLastPointResponse; }; }; /** Contains response data for the detectChangePoint operation. */ export type AnomalyDetectorDetectChangePointResponse = DetectChangePointResponse & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: DetectChangePointResponse; }; }; /** Contains response data for the trainMultivariateModel operation. */ export type AnomalyDetectorTrainMultivariateModelResponse = AnomalyDetectorTrainMultivariateModelHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: AnomalyDetectorTrainMultivariateModelHeaders; }; }; /** Contains response data for the getMultivariateModel operation. */ export type AnomalyDetectorGetMultivariateModelResponse = Model & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: Model; }; }; /** Contains response data for the detectAnomaly operation. */ export type AnomalyDetectorDetectAnomalyResponse = AnomalyDetectorDetectAnomalyHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: AnomalyDetectorDetectAnomalyHeaders; }; }; /** Contains response data for the getDetectionResult operation. */ export type AnomalyDetectorGetDetectionResultResponse = DetectionResult & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: DetectionResult; }; }; /** Contains response data for the exportModel operation. */ export type AnomalyDetectorExportModelResponse = AnomalyDetectorExportModelHeaders & { /** * BROWSER ONLY * * The response body as a browser Blob. * Always `undefined` in node.js. */ blobBody?: Promise<Blob>; /** * NODEJS ONLY * * The response body as a node.js Readable stream. * Always `undefined` in the browser. */ readableStreamBody?: NodeJS.ReadableStream; /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: AnomalyDetectorExportModelHeaders; }; }; /** Optional parameters. */ export interface AnomalyDetectorListMultivariateModelOptionalParams extends coreHttp.OperationOptions { /** $skip indicates how many models will be skipped. */ skip?: number; /** $top indicates how many models will be fetched. */ top?: number; } /** Contains response data for the listMultivariateModel operation. */ export type AnomalyDetectorListMultivariateModelResponse = ModelList & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: ModelList; }; }; /** Optional parameters. */ export interface AnomalyDetectorListMultivariateModelNextOptionalParams extends coreHttp.OperationOptions { /** $skip indicates how many models will be skipped. */ skip?: number; /** $top indicates how many models will be fetched. */ top?: number; } /** Contains response data for the listMultivariateModelNext operation. */ export type AnomalyDetectorListMultivariateModelNextResponse = ModelList & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: ModelList; }; }; /** Optional parameters. */ export interface AnomalyDetectorOptionalParams extends coreHttp.ServiceClientOptions { /** Overrides client endpoint. */ endpoint?: string; }
the_stack
function VideoUtils (conversation: jCafe.Conversation, content: HTMLElement, listeners: any[], startStep: number, nSteps: number, reset: (boolean?) => void) { 'use strict'; var isActiveSpeakerMode = conversation.videoService.videoMode() == 'ActiveSpeaker'; const remoteVidContainerMap: { [displayName: string]: HTMLElement } = {}; function setupContainer(videoChannel: jCafe.VideoChannel, videoDiv: HTMLElement) { videoChannel.stream.source.sink.format('Stretch'); videoChannel.stream.source.sink.container(videoDiv); } function createVideoContainer(labelText: string) { var containersDiv = content.querySelector('.remoteVideoContainers'); var newContainer = document.createElement('div'); newContainer.className = 'remoteVideoContainer'; containersDiv.appendChild(newContainer); var labelElement = document.createElement('b'); labelElement.className = 'remoteVideoLabel'; labelElement.innerHTML = labelText; newContainer.appendChild(labelElement); return newContainer; } function showHideVideoContainer(show: boolean, container: HTMLElement) { if (container) container.style.display = show ? "block" : "none"; } function createAndSetUpContainer(participant: jCafe.Participant) { var container = remoteVidContainerMap[participant.person.displayName()] || createVideoContainer(participant.person.displayName()); remoteVidContainerMap[participant.person.displayName()] = container; setupContainer(participant.video.channels(0), container); } function disposeParticipantContainer(participant: jCafe.Participant) { const container = remoteVidContainerMap[participant.person.displayName()]; if (container) { var containerParentElt = content.querySelector('.remoteVideoContainers'); containerParentElt.removeChild(container); delete remoteVidContainerMap[participant.person.displayName()]; } } function handleIsVideoOnChangedMV(newState: boolean, oldState: boolean, participant: jCafe.Participant) { const nRemoteVids = conversation.participants().filter(p => p.video.channels(0).isVideoOn() == true).length; (<HTMLElement>content.querySelector('#remotevideo')).style.display = nRemoteVids > 0 ? 'block' : 'none'; const msg = newState ? ' started streaming their video' : ' stopped streaming their video'; window.framework.addNotification('info', participant.person.displayName() + msg); showHideVideoContainer(newState, remoteVidContainerMap[participant.person.displayName()]); if (conversation.isGroupConversation()) participant.video.channels(0).isStarted(newState); } function handleIsVideoOnChangedAS(newState: boolean, activeSpeaker: jCafe.ActiveSpeaker) { (<HTMLElement>content.querySelector('#remotevideo')).style.display = newState ? 'block': 'none'; window.framework.addNotification('info', 'ActiveSpeaker video channel isVideoOn == ' + newState); showHideVideoContainer(newState, <HTMLElement>content.querySelector('.remoteVideoContainer')); activeSpeaker.channel.isStarted(newState); } function handleParticipantVideoStateChanged(newState: string, oldState: string, participant: jCafe.Participant) { if (newState == "Connected") { window.framework.addNotification('info', participant.person.displayName() + ' is connected to video'); // In multiview, listen for added participants, set up a container for each, // set up listeners to call isStarted(true/false) when isVideoOn() becomes true/false if (!isActiveSpeakerMode) { createAndSetUpContainer(participant); listeners.push(participant.video.channels(0).isVideoOn.changed((newState, reason, oldState) => { handleIsVideoOnChangedMV(newState, oldState, participant); })); } } else if (newState == "Disconnected" && oldState == "Connected") { window.framework.addNotification('info', participant.person.displayName() + ' has disconnected their video'); if (!isActiveSpeakerMode) { disposeParticipantContainer(participant); } } } function handleConversationStateChanged(newState: string, reason: any, oldState: string) { if (newState === 'Disconnected' && (oldState === 'Connected' || oldState === 'Connecting')) { window.framework.addNotification('success', 'Conversation ended'); (<HTMLElement>content.querySelector('#selfvideo')).style.display = 'none'; (<HTMLElement>content.querySelector('#remotevideo')).style.display = 'none'; goToStep(startStep + 2); reset(true); } else if (newState == 'Connected') window.framework.addNotification('success', 'Conversation connected'); } function setUpParticipantListeners() { listeners.push(conversation.participants.added(participant => { window.framework.addNotification('success', participant.person.displayName() + ' has joined the conversation'); listeners.push(participant.video.state.changed((newState, reason, oldState) => { handleParticipantVideoStateChanged(newState, oldState, participant) })); })); listeners.push(conversation.participants.removed(participant => { window.framework.addNotification('success', participant.person.displayName() + ' has left the conversation'); if (!isActiveSpeakerMode) disposeParticipantContainer(participant); })); } function setUpListeners () { listeners.push(conversation.selfParticipant.video.state.when('Connected', () => { window.framework.addNotification('info', 'Showing self video...'); (<HTMLElement>content.querySelector('#selfvideo')).style.display = 'block'; setupContainer(conversation.selfParticipant.video.channels(0), <HTMLElement>content.querySelector('.selfVideoContainer')); window.framework.addNotification('success', 'Connected to video'); registerControlElements(conversation); setUpParticipantListeners(); // In activeSpeaker mode, set up one container for activeSpeaker channel, and call // isStarted(true/false) when channel.isVideoOn() becomes true/false if (isActiveSpeakerMode) { var activeSpeaker = conversation.videoService.activeSpeaker; setupContainer(activeSpeaker.channel, createVideoContainer("Active Speaker")); listeners.push(activeSpeaker.channel.isVideoOn.changed(newState => { handleIsVideoOnChangedAS(newState, activeSpeaker); })); listeners.push(activeSpeaker.participant.changed(p => { var displayName = p && p.person.displayName() || 'No Active Speaker'; window.framework.addNotification('info', "ActiveSpeaker has changed to: " + displayName); var videoLabelElement = content.querySelector('.remoteVideoLabel'); videoLabelElement.innerHTML = displayName; })); } })); listeners.push(conversation.state.changed((newState, reason, oldState) => { handleConversationStateChanged(newState, reason, oldState); })); } function startVideoService () { conversation.videoService.start().then(null, error => { window.framework.addNotification('error', JSON.stringify(error)); if (error.code && error.code == 'PluginNotInstalled') { window.framework.addNotification('info', 'You can install the plugin from:'); window.framework.addNotification('info', '(Windows) https://swx.cdn.skype.com/s4b-plugin/16.2.0.67/SkypeMeetingsApp.msi'); window.framework.addNotification('info', '(Mac) https://swx.cdn.skype.com/s4b-plugin/16.2.0.67/SkypeForBusinessPlugin.pkg'); } }); goToStep(startStep + 1); } function registerControlElements(conversation) { var audioControl = content.querySelector('.js-toggleSelfAudio'), videoControl = content.querySelector('.js-toggleSelfVideo'), holdControl = content.querySelector('.js-toggleSelfHold'); registerToggleAudio(audioControl); registerToggleVideo(videoControl); registerToggleHold(holdControl); function registerToggleAudio(control) { var muted = false, pastTense, action; control.onclick = function () { muted = !muted; if (!muted) { control.querySelector('.text').innerHTML = 'Turn Off'; pastTense = 'Unmuted'; action = 'Unmuting'; } else { control.querySelector('.text').innerHTML = 'Turn On'; pastTense = 'Muted'; action = 'Muting'; } conversation.selfParticipant.audio.isMuted.set(muted).then(function () { window.framework.addNotification('success', pastTense + ' self'); }, function (error) { window.framework.addNotification('error', action + ' failed. See console.'); console.error(action + ' self failed', error); }); } } function registerToggleVideo(control) { var isStarted = true, pastTense, action; control.onclick = function () { isStarted = !isStarted; if (!isStarted) { control.querySelector('.text').innerHTML = 'Turn On'; pastTense = 'Turned off'; action = 'Turning off'; } else { control.querySelector('.text').innerHTML = 'Turn Off'; pastTense = 'Turned on'; action = 'Turning on'; } conversation.selfParticipant.video.channels(0).isStarted.set(isStarted).then(function () { window.framework.addNotification('success', pastTense + ' self video'); }, function (error) { window.framework.addNotification('error', action + ' self video failed. See console.'); console.error(action + ' self video failed', error); }); } } function registerToggleHold(control) { var onHold = false, pastTense, action; control.onclick = function () { onHold = !onHold; if (onHold) { control.querySelector('.text').innerHTML = 'Resume'; pastTense = 'Put call on hold'; action = 'Putting call on hold'; } else { control.querySelector('.text').innerHTML = 'Hold'; pastTense = 'Resumed call'; action = 'Resuming call'; } conversation.selfParticipant.audio.isOnHold.set(onHold).then(function () { window.framework.addNotification('success', pastTense); }, function (error) { window.framework.addNotification('error', action + ' failed. See console.'); console.error(action + ' failed', error); }); } } } function goToStep(step) { for (var i = 1; i < nSteps; i++) { (<HTMLElement>content.querySelector('#step' + i)).style.display = 'none'; } (<HTMLElement>content.querySelector('#step' + step)).style.display = 'block'; } return { setUpListeners: setUpListeners, startVideoService: startVideoService } }
the_stack
import { createButtonGroup } from '../src/button-group/button-group'; import { createElement, enableRipple } from '@syncfusion/ej2-base'; import { profile , inMB, getMemoryProfile } from './common.spec'; /** * ButtonGroup Spec document */ describe('ButtonGroup', () => { beforeAll(() => { const isDef: any = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log('Unsupported environment, window.performance.memory is unavailable'); this.skip(); // skips test (in Chai) return; } }); const element: HTMLElement = createElement('div', { id: 'buttongroup' }) as HTMLElement; let buttonElement1: HTMLButtonElement; let buttonElement2: HTMLButtonElement; let buttonElement3: HTMLButtonElement; let inputElement1: HTMLInputElement; let inputElement2: HTMLInputElement; let inputElement3: HTMLInputElement; describe('Util function', () => { afterEach(() => { document.getElementById('buttongroup').innerHTML = ''; document.getElementById('buttongroup').removeAttribute('class'); }); it('for NormalButtonGroup', () => { buttonElement1 = createElement('button') as HTMLButtonElement; buttonElement2 = createElement('button') as HTMLButtonElement; buttonElement3 = createElement('button') as HTMLButtonElement; element.appendChild(buttonElement1); element.appendChild(buttonElement2); element.appendChild(buttonElement3); document.body.appendChild(element); createButtonGroup( '#buttongroup', { buttons: [{ content: 'HTML' }, { content: 'CSS' }, { content: 'Javascript' }] }); expect(element.classList.contains('e-btn-group')).toBeTruthy(); expect(element.children[0].classList.contains('e-btn')).toBeTruthy(); expect(element.children[1].classList.contains('e-btn')).toBeTruthy(); expect(element.children[2].classList.contains('e-btn')).toBeTruthy(); expect(element.children[0].textContent).toBe('HTML'); expect(element.children[1].textContent).toBe('CSS'); expect(element.children[2].textContent).toBe('Javascript'); }); it('for Checkbox type ButtonGroup ', () => { inputElement1 = createElement('input') as HTMLInputElement; inputElement2 = createElement('input') as HTMLInputElement; inputElement3 = createElement('input') as HTMLInputElement; element.appendChild(inputElement1); element.appendChild(inputElement2); element.appendChild(inputElement3); createButtonGroup( '#buttongroup', { buttons: [{ content: 'HTML' }, { content: 'CSS' }, { content: 'Javascript' }] }); expect(element.classList.contains('e-btn-group')).toBeTruthy(); expect(element.children[1].tagName).toBe('LABEL'); expect(element.children[3].tagName).toBe('LABEL'); expect(element.children[5].tagName).toBe('LABEL'); expect(element.children[1].classList.contains('e-btn')).toBeTruthy(); expect(element.children[3].classList.contains('e-btn')).toBeTruthy(); expect(element.children[5].classList.contains('e-btn')).toBeTruthy(); expect(element.children[1].textContent).toBe('HTML'); expect(element.children[3].textContent).toBe('CSS'); expect(element.children[5].textContent).toBe('Javascript'); }); it('for Nesting', () => { buttonElement1 = createElement('button') as HTMLButtonElement; buttonElement2 = createElement('button') as HTMLButtonElement; buttonElement3 = createElement('button') as HTMLButtonElement; element.appendChild(buttonElement1); element.appendChild(buttonElement2); element.appendChild(buttonElement3); createButtonGroup( '#buttongroup', { buttons: [{ content: 'HTML' }, null, { content: 'Javascript' }] }); expect(element.classList.contains('e-btn-group')).toBeTruthy(); expect(element.children[0].classList.contains('e-btn')).toBeTruthy(); expect(element.children[1].classList.contains('e-btn')).toBeFalsy(); expect(element.children[2].classList.contains('e-btn')).toBeTruthy(); expect(element.children[0].textContent).toBe('HTML'); expect(element.children[1].textContent).toBe(''); expect(element.children[2].textContent).toBe('Javascript'); }); it('for cssClass with NormalButtonGroup', () => { buttonElement1 = createElement('button') as HTMLButtonElement; buttonElement2 = createElement('button') as HTMLButtonElement; buttonElement3 = createElement('button') as HTMLButtonElement; element.appendChild(buttonElement1); element.appendChild(buttonElement2); element.appendChild(buttonElement3); createButtonGroup( '#buttongroup', { cssClass: 'e-primary', buttons: [{ content: 'HTML' }, { content: 'CSS', cssClass: 'e-success' }, { content: 'Javascript' }] }); expect(element.classList.contains('e-btn-group')).toBeTruthy(); expect(element.children[0].classList.contains('e-primary')).toBeTruthy(); expect(element.children[1].classList.contains('e-success')).toBeTruthy(); expect(element.children[2].classList.contains('e-primary')).toBeTruthy(); }); it('for cssClass with Checkbox type ButtonGroup ', () => { inputElement1 = createElement('input') as HTMLInputElement; inputElement2 = createElement('input') as HTMLInputElement; inputElement3 = createElement('input') as HTMLInputElement; element.appendChild(inputElement1); element.appendChild(inputElement2); element.appendChild(inputElement3); createButtonGroup( '#buttongroup', { cssClass: 'e-primary', buttons: [{ content: 'HTML' }, { content: 'CSS', cssClass: 'e-success' }, { content: 'Javascript' }] }); expect(element.children[1].classList.contains('e-primary')).toBeTruthy(); expect(element.children[3].classList.contains('e-success')).toBeTruthy(); expect(element.children[5].classList.contains('e-primary')).toBeTruthy(); }); it('for NormalButtonGroup with Ripple effect', () => { enableRipple(true); buttonElement1 = createElement('button') as HTMLButtonElement; buttonElement2 = createElement('button') as HTMLButtonElement; buttonElement3 = createElement('button') as HTMLButtonElement; element.appendChild(buttonElement1); element.appendChild(buttonElement2); element.appendChild(buttonElement3); document.body.appendChild(element); createButtonGroup( '#buttongroup', { buttons: [{ content: 'HTML' }, { content: 'CSS' }, { content: 'Javascript' }] }); expect(element.children[0].getAttribute('data-ripple')).toBe('true'); expect(element.children[1].getAttribute('data-ripple')).toBe('true'); expect(element.children[2].getAttribute('data-ripple')).toBe('true'); enableRipple(false); }); it('Input type ID checking', () => { inputElement1 = createElement('input', { id: 'checkbox1' }) as HTMLInputElement; inputElement2 = createElement('input', { id: 'checkbox2' }) as HTMLInputElement; inputElement3 = createElement('input', { id: 'checkbox3' }) as HTMLInputElement; element.appendChild(inputElement1); element.appendChild(inputElement2); element.appendChild(inputElement3); createButtonGroup( '#buttongroup', { buttons: [{ content: 'HTML' }, { content: 'CSS' }, { content: 'Javascript' }] }); expect(element.children[1].getAttribute('for')).toBe('checkbox1'); expect(element.children[3].getAttribute('for')).toBe('checkbox2'); expect(element.children[5].getAttribute('for')).toBe('checkbox3'); }); it('ARIA Checking', () => { buttonElement1 = createElement('button') as HTMLButtonElement; buttonElement2 = createElement('button') as HTMLButtonElement; buttonElement3 = createElement('button') as HTMLButtonElement; element.appendChild(buttonElement1); element.appendChild(buttonElement2); element.appendChild(buttonElement3); document.body.appendChild(element); createButtonGroup('#buttongroup', { buttons: [{ content: 'HTML' }, { content: 'CSS' }, { content: 'Javascript' }] }); expect(element.getAttribute('role')).toBe('group'); }); // For else part coverage it('Without button options', () => { buttonElement1 = createElement('button') as HTMLButtonElement; buttonElement2 = createElement('button') as HTMLButtonElement; buttonElement3 = createElement('button') as HTMLButtonElement; element.appendChild(buttonElement1); element.appendChild(buttonElement2); element.appendChild(buttonElement3); document.body.appendChild(element); createButtonGroup('#buttongroup', { cssClass: 'e-primary' }); }); it('Options as null', () => { buttonElement1 = createElement('button') as HTMLButtonElement; buttonElement2 = createElement('button') as HTMLButtonElement; buttonElement3 = createElement('button') as HTMLButtonElement; element.appendChild(buttonElement1); element.appendChild(buttonElement2); element.appendChild(buttonElement3); document.body.appendChild(element); createButtonGroup('#buttongroup'); }); it('Without Button and Input element', () => { const divElement1: HTMLElement = createElement('div') as HTMLElement; const divElement2: HTMLElement = createElement('div') as HTMLElement; element.appendChild(divElement1); element.appendChild(divElement2); document.body.appendChild(element); createButtonGroup('#buttongroup', { cssClass: 'e-primary' }); }); }); it('memory leak', () => { profile.sample(); const average: any = inMB(profile.averageChange); // check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); const memory: any = inMB(getMemoryProfile()); // check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
import { i18nMark, withI18n } from "@lingui/react"; import { Trans, t } from "@lingui/macro"; import classNames from "classnames"; import { Form, Modal, Tooltip } from "reactjs-components"; import mixin from "reactjs-mixin"; import PropTypes from "prop-types"; import * as React from "react"; import { Icon, InfoBoxInline } from "@dcos/ui-kit"; import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum"; import { iconSizeXs } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens"; import FilterBar from "#SRC/js/components/FilterBar"; import InfoTooltipIcon from "#SRC/js/components/form/InfoTooltipIcon"; import MetadataStore from "#SRC/js/stores/MetadataStore"; import ModalHeading from "#SRC/js/components/modals/ModalHeading"; import StoreMixin from "#SRC/js/mixins/StoreMixin"; import StringUtil from "#SRC/js/utils/StringUtil"; import ToggleButton from "#SRC/js/components/ToggleButton"; import ACLStore from "../submodules/acl/stores/ACLStore"; class PermissionBuilderModal extends mixin(StoreMixin) { static defaultProps = { activeView: "builder", disabled: false, dupesFound: [], errors: [], handleBulkAddToggle() {}, open: false, onClose() {}, onSubmit() {}, permissionsAddedCount: 0, }; static propTypes = { activeView: PropTypes.oneOf(["builder", "bulk"]), disabled: PropTypes.bool, dupesFound: PropTypes.array, errors: PropTypes.array, handleBulkAddToggle: PropTypes.func, open: PropTypes.bool, onClose: PropTypes.func, onSubmit: PropTypes.func, permissionsAddedCount: PropTypes.number, subject: PropTypes.object, }; state = { actions: "", chosenRIDs: [], errorMsg: null, model: {}, resource: "", }; store_listeners = [ { name: "acl", events: ["fetchSchemaSuccess", "fetchSchemaError"] }, ]; UNSAFE_componentWillMount() { ACLStore.fetchACLSchema(); } onAclStoreFetchSchemaSuccess() { const chosenRIDs = this.preSelectPermissions( [], ACLStore.getPermissionSchema() ); this.setState({ chosenRIDs, errorMsg: null }); } onAclStoreFetchSchemaError() { const { i18n } = this.props; this.setState({ errorMsg: i18n._(t`Unable to fetch permission schema.`) }); } handleSubmit = () => { this.props.onSubmit(this.getSubmittedACLs()); }; handleError = () => { // Make sure to update modal, as error fields might have made modal bigger this.forceUpdate(); }; handleClose = () => { this.props.onClose(); }; handleFormChange = (model, selection, item) => { const { index, permission } = item || {}; let { chosenRIDs } = this.state; const newState = { model }; if (permission && index != null) { chosenRIDs = chosenRIDs.slice(0, index); chosenRIDs.push(permission.rid); newState.chosenRIDs = this.preSelectPermissions(chosenRIDs, permission); } this.setState(newState); }; handleBulkFormChange = (changeModel) => { this.setState(changeModel); }; handleAllowAllActions(actions) { const { model } = this.state; model.actions = actions.map((name) => ({ checked: true, label: StringUtil.capitalize(name), name, })); this.setState({ model }); } isBulkAdd() { return this.props.activeView === "bulk"; } preSelectPermissions(chosenRIDs, permission) { let nextChild = permission; while (nextChild.getItems() && nextChild.getItems().length === 1) { nextChild = nextChild.getItems()[0]; chosenRIDs.push(nextChild.rid); } return chosenRIDs; } getDropdownItems(permission, index) { const { name, groupName } = permission; const defaultItem = [ { className: "hidden", html: name, id: "default-item", permission, index, selectedHtml: "Select " + groupName, }, ]; return defaultItem.concat( permission.getItems().map((item) => { const itemName = item.name; return { className: "clickable", html: itemName, id: item.rid, permission: item, index, selectedHtml: itemName, }; }) ); } getSelectedActions(actions = []) { return actions.reduce((actionNames, action) => { if (action.checked) { actionNames.push(action.name); } return actionNames; }, []); } getSubmittedACLs() { const { bulkacls = "", chosenRIDs, model } = this.state; if (this.isBulkAdd() && bulkacls !== null) { return bulkacls .split("\n") .filter((aclLine) => aclLine.length) .map((aclLine) => { const splitLine = aclLine.trim().split(" "); const resource = splitLine.shift().trim(); const actions = splitLine .join(" ") .split(",") .map((action) => action.trim().toLowerCase()); return { actions, resource, }; }); } return [ { actions: this.getSelectedActions(model.actions), resource: this.getResourceString(model, chosenRIDs), }, ]; } getResourceString(model, chosenRIDs) { const resource = ACLStore.getPermissionSchema().collectPermissionString( chosenRIDs ); // Create input value array sorted after index in the resource const values = Object.keys(model) // Filter out items that do not have a number as key .filter((item) => !isNaN(parseInt(item, 10))) // Remove 'input' from key, and parse integer to sort correctly .sort((a, b) => parseInt(a, 10) - parseInt(b, 10)) .map((valueKey) => model[valueKey]); // Replace occurances of '*' with model values const segments = resource.split("*"); return segments.reduce((memo, segment, index) => { // Do not add value to last segment if (segments.length - 1 === index) { return memo + segment; } // Add segment and model value return memo + segment + (values.shift() || "*"); }, ""); } getActionCheckboxDefinitions() { const { disabled, i18n } = this.props; const { chosenRIDs, model } = this.state; const actions = ACLStore.getPermissionSchema().collectActions(chosenRIDs); if (!actions.length) { return null; } const modelActions = model.actions || []; const actionValues = modelActions.reduce((memo, action) => { memo[action.name] = action.checked; return memo; }, {}); const showLabel = ( <Trans render="h4" className="flush-top"> Actions ( <a className="clickable" onClick={this.handleAllowAllActions.bind(this, actions)} > Allow All </a> ) </Trans> ); return { disabled, fieldType: "checkbox", formElementClass: { "column-12": false }, formGroupClass: "form-group media-object-spacing-wrapper media-object-spacing-narrow media-object-offset", labelClass: "media-object-item", itemWrapperClass: "media-object media-object-wrap", name: "actions", validation(value) { return value.some((checkbox) => checkbox.checked); }, showLabel, validationErrorText: i18n._(t`Please select at least one option.`), value: actions.map((name) => ({ checked: actionValues[name], label: StringUtil.capitalize(name), name, })), writeType: "input", }; } getFormElementDefinition = (permission, index) => { const { model } = this.state; const { disabled } = this.props; const { name, groupName, rid } = permission; const tooltipContent = ( <Trans render="span"> <a href={MetadataStore.buildDocsURI("/security/ent/perms-management/")} target="_blank" > See documentation </a> . </Trans> ); if (rid === "*") { const indexString = index.toString(); return { columnWidth: 4, // Set to 4 so we can disable column class disabled, fieldType: "text", formElementClass: { "column-4": false, // Disable column class "media-object-item": true, }, name: indexString, placeholder: name, required: true, showError: false, showLabel: ( <label> {`${groupName} `} <Tooltip content={tooltipContent} wrapperClassName="tooltip-wrapper" wrapText={true} maxWidth={300} interactive={true} > <InfoTooltipIcon /> </Tooltip> </label> ), validation() { return true; }, value: model[indexString], writeType: "input", }; } const items = permission.getItems(); // Leave out dropdown selection, if there is no or // only one choice (will be pre selected) if (!items || items.length < 2) { return null; } return { columnWidth: 4, // Set to 4 so we can disable column class fieldType: "select", formElementClass: { "column-4": false, // Disable column class "media-object-item": true, }, label: groupName, showLabel: true, options: this.getDropdownItems(permission, index), name: rid, required: false, validation() { return true; }, value: model[rid], writeType: "input", }; }; getFormDefinition() { const { chosenRIDs } = this.state; const permissionSelections = []; ACLStore.getPermissionSchema() .collectChildren(chosenRIDs) .forEach((permission, index) => { const formElement = this.getFormElementDefinition(permission, index); if (formElement) { permissionSelections.push(formElement); } }); const definition = [permissionSelections]; const actionsFormElement = this.getActionCheckboxDefinitions(); if (actionsFormElement) { definition.push(actionsFormElement); } return definition; } toggleBulkAdd = () => { this.props.handleBulkAddToggle(); }; setTriggerSubmit = (triggerSubmit) => { this.triggerSubmit = triggerSubmit; }; getManualForm() { const { chosenRIDs, model } = this.state; const { disabled, errors } = this.props; let value = this.getResourceString(model, chosenRIDs); const actions = this.getSelectedActions(model.actions).join(","); // There's no sense in just showing `dcos` if the user // didn't actually pick anything from the wizard. if (value === "dcos") { value = ""; } else { value += ` ${actions}`; } const definition = [ [ { disabled, fieldType: "textarea", focused: true, name: "bulkacls", required: true, showLabel: false, writeType: "input", validation() { return true; }, value, }, ], ]; if (errors.length) { definition[0].validationError = { bulkacls: true }; } const tooltipContent = ( <Trans render="span"> Define the permission in a string format. If the permission also includes an action, specify the action that should be allowed. Refer to{" "} <a href={MetadataStore.buildDocsURI("/security/ent/perms-management/")} target="_blank" > the documentation </a>{" "} for more details. </Trans> ); return ( <div> {this.getErrorMessage()} <h4> <Trans render="span">Permissions Strings</Trans> <Tooltip content={tooltipContent} wrapperClassName="tooltip-wrapper" wrapText={true} maxWidth={350} interactive={true} > <InfoTooltipIcon /> </Tooltip> </h4> <Form formGroupClass="form-group flush-bottom" definition={definition} onError={this.handleError} onChange={this.handleBulkFormChange} onSubmit={this.handleSubmit} triggerSubmit={this.setTriggerSubmit} /> </div> ); } getForm() { if (this.isBulkAdd()) { return this.getManualForm(); } return ( <div> <Trans render="h4">Resource</Trans> {this.getErrorMessage()} <Form className="form flush-bottom media-object-spacing-wrapper media-object-spacing-narrow media-object-offset" formRowClass={{ "media-object media-object-wrap": true, row: false, }} definition={this.getFormDefinition()} onError={this.handleError} onChange={this.handleFormChange} onSubmit={this.handleSubmit} triggerSubmit={this.setTriggerSubmit} /> </div> ); } getErrorMessage() { const { errorMsg } = this.state; if (!errorMsg || this.isBulkAdd()) { return null; } return ( <Trans render="p" className="text-danger flush-top"> {errorMsg} Go to{" "} <a className="clickable" onClick={this.toggleBulkAdd}> insert permission string </a>{" "} to enter a permission manually. </Trans> ); } getPermissionText() { if (this.isBulkAdd()) { return "Permissions"; } return "Permission"; } getFooter() { const { disabled } = this.props; const actions = ACLStore.getPermissionSchema().collectActions( this.state.chosenRIDs ); const permisssionText = this.isBulkAdd() ? i18nMark("Add Permissions") : i18nMark("Add Permission"); const affirmText = disabled ? i18nMark("Adding...") : permisssionText; return ( <div className="flush-bottom flex flex-direction-top-to-bottom flex-align-items-stretch-screen-small flex-direction-left-to-right-screen-small flex-justify-items-space-between-screen-medium"> <Trans render={ <button className="button button-primary-link flush-left" onClick={this.handleClose} /> } > Close </Trans> <Trans render={ <button className="button button-primary" disabled={!this.isBulkAdd() && (disabled || !actions.length)} onClick={this.triggerSubmit} /> } id={affirmText} /> </div> ); } getHeader() { return ( <FilterBar className="filter-bar filter-bar-offset" rightAlignLastNChildren={1} > <ModalHeading> <Trans render="span"> Add a Permission for {this.props.subjectID} </Trans> </ModalHeading> <ToggleButton checked={this.isBulkAdd()} onChange={this.toggleBulkAdd}> <Trans render="span">Insert Permission String</Trans> </ToggleButton> </FilterBar> ); } getIntroduction() { if (this.isBulkAdd()) { return ( <Trans render="p"> Use the form below to manually enter or paste permissions.{" "} <a className="clickable" onClick={this.toggleBulkAdd}> Switch to permission builder </a>{" "} to add a single permission. </Trans> ); } return ( <Trans render="p"> Use the form below to build your permission. For more information see the{" "} <a href={MetadataStore.buildDocsURI("/security/ent/perms-reference/")} target="_blank" key="docs" > documentation </a> . To bulk add permissions,{" "} <a className="clickable" onClick={this.toggleBulkAdd}> switch to advanced mode </a> . </Trans> ); } getMessage() { const { disabled, dupesFound, errors, permissionsAddedCount } = this.props; let dupeMessages = null; let errorMessages = null; let errorMessage = null; let successMessage = null; if (permissionsAddedCount && !disabled) { // L10NTODO: Pluralize successMessage = ( <div className="form-row-pad-bottom"> <InfoBoxInline key="successMessage" appearance="success" message={ <React.Fragment> <div className="flex"> <div> <Icon shape={SystemIcons.CircleCheck} size={iconSizeXs} color="currentColor" /> </div> <div className="errorsAlert-message"> <strong> {permissionsAddedCount}{" "} {StringUtil.pluralize( "Permission", permissionsAddedCount )}{" "} added. </strong> </div> </div> </React.Fragment> } /> </div> ); } if (dupesFound.length) { // L10NTODO: Pluralize dupeMessages = dupesFound .slice(0, 5) // Show first five errors. .map((duplicate) => ( <Trans render="li" key={duplicate} className="errorsAlert-listItem"> Duplicate Resource ID: {duplicate} </Trans> )); } if (errors.length) { errorMessages = errors .slice(0, 5 - dupesFound.length) // Show first five errors. .map((errorObject, key) => { let preText = ""; const { action, error, resourceID } = errorObject; if (error.indexOf(resourceID) === -1) { preText += `For ${resourceID}`; if (action && error.indexOf(action) === -1) { preText += ` ${action}`; } preText += ": "; } else if (action) { preText += `For action ${action}: `; } return ( <li key={key} className="errorsAlert-listItem"> {preText} {error} </li> ); }); } if (dupesFound.length + errors.length > 5) { errorMessages.push( <li className="errorsAlert-listItem" key="more"> <Trans>and {dupesFound.length + errors.length - 5} more.</Trans> </li> ); } if (errorMessages || dupeMessages) { // L10NTODO: Pluralize errorMessage = ( <div className="form-row-pad-bottom"> <InfoBoxInline appearance="danger" message={ <React.Fragment> <div className="flex"> <div> <Icon shape={SystemIcons.Yield} size={iconSizeXs} color="currentColor" /> </div> <div className="errorsAlert-message"> <div key="errorHeading"> <strong> Unable to add {errors.length + dupesFound.length}{" "} {StringUtil.pluralize( "permission", errors.length + dupesFound.length )} : </strong> </div> <ul className="errorsAlert-list"> {dupeMessages} {errorMessages} </ul> </div> </div> </React.Fragment> } /> </div> ); } return ( <div> {successMessage} {errorMessage} </div> ); } render() { const modalClass = classNames("modal modal-large", { "permission-form-modal": !this.isBulkAdd(), }); return ( <Modal bodyClass="permission-form" closeByBackdropClick={true} footer={this.getFooter()} header={this.getHeader()} modalClass={modalClass} onClose={this.handleClose} open={this.props.open} scrollContainerClass="" showHeader={true} showFooter={true} showHeader={true} useGemini={false} > <div className="modal-body allow-overflow"> <div className="text-overflow-break-word"> {this.getMessage()} {this.getIntroduction()} {this.getForm()} </div> </div> </Modal> ); } } export default withI18n()(PermissionBuilderModal);
the_stack
import { AssetDatabase, EditorGUI, EditorGUILayout, EditorGUIUtility, EditorStyles, GenericMenu, Handles } from "UnityEditor"; import { Color, Event, EventType, FocusType, GUI, GUIContent, GUILayout, GUIUtility, KeyCode, Rect, Texture, Vector2, Vector3 } from "UnityEngine"; import { EventDispatcher } from "../../../plover/events/dispatcher"; import { ITreeNodeEventHandler, UTreeNode } from "./treenode"; export class UTreeView { static readonly CONTEXT_MENU = "CONTEXT_MENU"; readonly SKIP_RETURN = 0; private _handler: ITreeNodeEventHandler; private _events: EventDispatcher; private _eventUsed = false; private _skipReturn = 0; private _root: UTreeNode; private _height: number; private _drawY: number; private _rowIndex: number; private _indentSize: number = 16; private _controlRect: Rect; private _controlID: number; private _controlEventType: EventType; private _controlMousePos: Vector2; private _rowRect = Rect.zero; private _indentRect = Rect.zero; private _tempRect = Rect.zero; // private _point = Vector3.zero; // private _drawLine = false; private _selected: UTreeNode; private _editing = false; private _deferredMenuPopup: boolean = false; private _searchString: string; private _selectionColor = new Color(44 / 255, 93 / 255, 135 / 255); private _rowColor = new Color(0.5, 0.5, 0.5, 0.1); private _focusColor = new Color(58 / 255, 121 / 255, 187 / 255); private _debug_touchChild = 0; private _debug_drawChild = 0; get selected() { return this._selected; } set selected(value: UTreeNode) { if (this._selected != value) { this._selected?.endEdit(); this._editing = false; this._skipReturn = 0; this._selected = value; } } get searchString() { return this._searchString; } set searchString(value: string) { this.search(value); } get root() { return this._root; } get handler() { return this._handler; } set handler(value: ITreeNodeEventHandler) { this._handler = value; } constructor(handler: ITreeNodeEventHandler) { this._searchString = ""; this._handler = handler; this._root = new UTreeNode(this, null, true, "/"); this._root.isEditable = false; this._root.isSearchable = false; this._root.expanded = true; } on(evt: string, caller: any, fn?: Function) { if (!this._events) { this._events = new EventDispatcher(); } this._events.on(evt, caller, fn); } off(evt: string, caller: any, fn?: Function) { if (this._events) { this._events.off(evt, caller, fn); } } dispatch(name: string, arg0?: any, arg1?: any, arg2?: any) { if (!this._events) { this._events = new EventDispatcher(); } this._events.dispatch(name, arg0, arg1, arg2); } allocFolderHierarchy(path: string, data: any): UTreeNode { return this._getFolderHierarchy(path, data); } getFolderHierarchy(path: string): UTreeNode { return this._getFolderHierarchy(path, null); } private _getFolderHierarchy(path: string, data: any): UTreeNode { if (path.startsWith("/")) { path = path.substring(1); } let node: UTreeNode = this._root; if (path.length > 0) { let hierarchy = path.split("/"); for (let i = 0; i < hierarchy.length; i++) { node = node.getFolderByName(hierarchy[i], true, data); } } return node; } removeAll() { this._root.removeAll(); this.selected = null; } deleteNode(node: UTreeNode) { if (node && this._selected == node && node.parent) { this._selected = this.findNextNode(node) || this.findPreviousNode(node); return node.parent.removeChild(node); } return false; } search(p: string) { if (p == null) { p = ""; } if (this._searchString != p) { this._searchString = p; this._search(this._root); } } private _search(node: UTreeNode) { node.match(this._searchString); for (let i = 0, count = node.childCount; i < count; i++) { this._search(node.getChildByIndex(i)); } } expandAll() { this._root.expandAll(); } collapseAll() { this._root.collapseAll(); } draw(offsetX: number, offsetY: number, width: number, height: number) { let repaint = false; let cEvent = Event.current; if (this._deferredMenuPopup) { this._deferredMenuPopup = false; if (this._selected) { this._selected.drawMenu(this, cEvent.mousePosition, this._handler); repaint = true; } } this._debug_touchChild = 0; this._debug_drawChild = 0; this._eventUsed = false; this._height = 0; this._drawY = 0; this._rowIndex = 0; if (this._searchString == null || this._searchString.length == 0) { this.calcRowHeight(this._root); this.setControlRect(cEvent); this.drawRow(this._root, 0, offsetY, height); } else { this.calcSearchResultsHeight(this._root); this.setControlRect(cEvent); this.drawSearchResults(this._root, 0, offsetY, height); } if (this._controlID == GUIUtility.keyboardControl) { this._tempRect.Set(0, 0, 1, height); EditorGUI.DrawRect(this._tempRect, this._focusColor); } if (cEvent.isKey) { let eventType = cEvent.type; if (this._editing) { switch (eventType) { case EventType.KeyUp: { let keyCode = cEvent.keyCode; if (keyCode == KeyCode.Return) { if (this._skipReturn > 0) { this._skipReturn--; this.useEvent(); } else { GUI.FocusControl(null); GUIUtility.keyboardControl = this._controlID; this._selected?.endEdit(); this._editing = false; this._skipReturn = 0; this.useEvent(); } } } break; } } else { if (this._selected && this._controlEventType == EventType.KeyUp && this._controlID == GUIUtility.keyboardControl) { // console.log(GUIUtility.keyboardControl, this._controlID); let keyCode = cEvent.keyCode; if (keyCode == KeyCode.Return) { if (this._selected.isEditable) { this._editing = true; this._skipReturn = this.SKIP_RETURN; this.useEvent(); } } else { if (keyCode == KeyCode.UpArrow) { if (this._selected.parent) { let sibling = this.findPreviousNode(this._selected); if (sibling) { this._selected = sibling; this._selected.expandUp(); this.useEvent(); } } } else if (keyCode == KeyCode.DownArrow) { let sibling = this.findNextNode(this._selected); if (sibling) { this._selected = sibling; this._selected.expandUp(); this.useEvent(); } } else if (keyCode == KeyCode.LeftArrow) { if (this._selected.expanded && this._selected.isFolder) { this._selected.expanded = false; this._selected.expandUp(); } else if (this._selected.parent) { this._selected = this._selected.parent; this._selected.expandUp(); } this.useEvent(); } else if (keyCode == KeyCode.RightArrow) { this._selected.expanded = true; this._selected.expandUp(); this.useEvent(); } } } } } else { if (!this._editing && this._controlEventType == EventType.MouseUp) { this._tempRect.Set(0, 0, width, height); if (this._tempRect.Contains(this._controlMousePos)) { GUIUtility.keyboardControl = this._controlID; repaint = true; } } } return this._deferredMenuPopup || repaint; } private calcRowHeight(node: UTreeNode) { this._height += node.calcRowHeight(); if (node.expanded) { for (let i = 0, count = node.childCount; i < count; i++) { this.calcRowHeight(node.getChildByIndex(i)); } } } private calcSearchResultsHeight(node: UTreeNode) { if (node.isMatch) { this._height += node.calcRowHeight(); } for (let i = 0, count = node.childCount; i < count; i++) { this.calcRowHeight(node.getChildByIndex(i)); } } private setControlRect(cEvent: Event) { this._controlRect = EditorGUILayout.GetControlRect(false, this._height, GUILayout.MinWidth(160)); this._controlID = GUIUtility.GetControlID(FocusType.Keyboard, this._controlRect); this._controlEventType = cEvent.GetTypeForControl(this._controlID); if (this._controlEventType == EventType.MouseUp) { this._controlMousePos = cEvent.mousePosition; } } private useEvent() { this._eventUsed = true; GUI.changed = true; Event.current.Use(); } private drawSearchResults(node: UTreeNode, depth: number, offsetY: number, height: number) { let drawY = this._drawY; if (node.isMatch) { this._drawY += node.height; ++this._rowIndex; ++this._debug_touchChild; if ((this._drawY - offsetY) > 0 && (drawY - offsetY) < height) { let rowIndent = 0; let baseX = 14; let bSelected = this._selected == node; ++this._debug_drawChild; this._rowRect.Set(this._controlRect.x, this._controlRect.y + drawY, this._controlRect.width, node.height); this._indentRect.Set(this._controlRect.x + baseX + rowIndent, this._rowRect.y, this._controlRect.width - rowIndent, node.height); if (bSelected) { EditorGUI.DrawRect(this._rowRect, this._selectionColor); } else if (this._rowIndex % 2) { EditorGUI.DrawRect(this._rowRect, this._rowColor); } node.draw(this._indentRect, bSelected, bSelected && this._editing, this._indentSize); if (this._controlEventType == EventType.MouseUp) { if (this._rowRect.Contains(this._controlMousePos)) { if (Event.current.button == 1) { if (this._selected == node) { node.drawMenu(this, this._controlMousePos, this._handler); this.useEvent(); } else { this.selected = node; if (!this._editing) { this._deferredMenuPopup = true; } this.useEvent(); } } else if (Event.current.button == 0) { if (node.isFolder && node._foldoutRect.Contains(this._controlMousePos)) { node.expanded = !node.expanded; } else { this.selected = node; } this.useEvent(); } } } } } for (let i = 0, count = node.childCount; i < count; i++) { this.drawSearchResults(node.getChildByIndex(i), depth + 1, offsetY, height); } } private drawRow(node: UTreeNode, depth: number, offsetY: number, height: number) { let drawY = this._drawY; this._drawY += node.height; ++this._rowIndex; ++this._debug_touchChild; if ((this._drawY - offsetY) > 0 && (drawY - offsetY) < height) { let rowIndent = this._indentSize * depth; let baseX = 14; let bSelected = this._selected == node; ++this._debug_drawChild; this._rowRect.Set(this._controlRect.x, this._controlRect.y + drawY, this._controlRect.width, node.height); this._indentRect.Set(this._controlRect.x + baseX + rowIndent, this._rowRect.y, this._controlRect.width - rowIndent, node.height); if (bSelected) { EditorGUI.DrawRect(this._rowRect, this._selectionColor); } else if (this._rowIndex % 2) { EditorGUI.DrawRect(this._rowRect, this._rowColor); } node.draw(this._indentRect, bSelected, bSelected && this._editing, this._indentSize); if (this._controlEventType == EventType.MouseUp) { if (this._rowRect.Contains(this._controlMousePos)) { if (Event.current.button == 1) { if (this._selected == node) { node.drawMenu(this, this._controlMousePos, this._handler); this.useEvent(); } else { this.selected = node; if (!this._editing) { this._deferredMenuPopup = true; } this.useEvent(); } } else if (Event.current.button == 0) { if (node.isFolder && node._foldoutRect.Contains(this._controlMousePos)) { node.expanded = !node.expanded; } else { this.selected = node; } this.useEvent(); } } } } else { node.visible = false; } if (node.expanded) { for (let i = 0, count = node.childCount; i < count; i++) { this.drawRow(node.getChildByIndex(i), depth + 1, offsetY, height); // if (this._drawLine && i == count - 1) { // this._point.Set(child._lineStart.x, node._lineStart.y, 0); // // Handles.DrawDottedLine(this._point, child._lineStartIn, 1); // Handles.color = Color.gray; // Handles.DrawLine(this._point, child._lineStartIn); // } } } } findPreviousNode(node: UTreeNode) { let sibling = node.parent.findLastSibling(node); while (sibling && sibling.expanded && sibling.childCount > 0) { sibling = sibling.getLastChild(); } return sibling || node.parent; } findNextNode(node: UTreeNode) { if (node.expanded && node.childCount > 0) { return node.getFirstChild(); } while (node.parent) { let sibling = node.parent.findNextSibling(node); if (sibling) { return sibling; } node = node.parent; } return null; } }
the_stack
import 'reflect-metadata' import { test } from '@japa/runner' import { Ioc } from '@adonisjs/fold' import { Kernel } from '@adonisjs/ace' import { testingRenderer } from '@poppinss/cliui' import { Application } from '@adonisjs/application' import { Router } from '@adonisjs/http-server/build/src/Router' import { PreCompiler } from '@adonisjs/http-server/build/src/Server/PreCompiler/index' import ListRoutes from '../../commands/ListRoutes' const ioc = new Ioc() const precompiler = new PreCompiler(ioc, { get() {}, getNamed(name: string) { return { name } }, } as any) test.group('Command | List Routes Json', (group) => { group.each.teardown(() => { testingRenderer.logs = [] }) test('list routes in the order they are registered', async ({ assert }) => { const app = new Application(__dirname, 'test', {}) const router = new Router({} as any, precompiler.compileRoute.bind(precompiler)) router.get('about', async () => {}) router.get('contact', async () => {}) router.commit() app.container.bind('Adonis/Core/Route', () => router) const listRoutes = new ListRoutes(app, new Kernel(app)) listRoutes.logger.useRenderer(testingRenderer) listRoutes.json = true await listRoutes.run() assert.deepEqual( testingRenderer.logs.map(({ message }) => JSON.parse(message)), [ { root: [ { domain: 'root', name: '', pattern: '/about', methods: ['GET', 'HEAD'], handler: 'Closure', middleware: [], }, { domain: 'root', name: '', pattern: '/contact', methods: ['GET', 'HEAD'], handler: 'Closure', middleware: [], }, ], }, ] ) }) test('list routes with middleware', async ({ assert }) => { const app = new Application(__dirname, 'test', {}) const router = new Router({} as any, precompiler.compileRoute.bind(precompiler)) router.get('about', async () => {}) router.get('contact', async () => {}).middleware(['auth', 'acl:admin']) router.commit() app.container.bind('Adonis/Core/Route', () => router) const listRoutes = new ListRoutes(app, new Kernel(app)) listRoutes.logger.useRenderer(testingRenderer) listRoutes.json = true await listRoutes.run() assert.deepEqual( testingRenderer.logs.map(({ message }) => JSON.parse(message)), [ { root: [ { domain: 'root', name: '', pattern: '/about', methods: ['GET', 'HEAD'], handler: 'Closure', middleware: [], }, { domain: 'root', name: '', pattern: '/contact', methods: ['GET', 'HEAD'], handler: 'Closure', middleware: ['auth', 'acl:admin'], }, ], }, ] ) }) test('list routes with controller handlers', async ({ assert }) => { const app = new Application(__dirname, 'test', {}) ioc.bind('App/Controllers/Http/HomeController', () => {}) ioc.bind('App/Controllers/Http/ContactController', () => {}) const router = new Router({} as any, precompiler.compileRoute.bind(precompiler)) router.get('about', 'HomeController.index') router.get('contact', 'ContactController') router.commit() app.container.bind('Adonis/Core/Route', () => router) const listRoutes = new ListRoutes(app, new Kernel(app)) listRoutes.json = true listRoutes.logger.useRenderer(testingRenderer) await listRoutes.run() assert.deepEqual( testingRenderer.logs.map(({ message }) => JSON.parse(message)), [ { root: [ { domain: 'root', name: '', pattern: '/about', methods: ['GET', 'HEAD'], handler: 'HomeController.index', middleware: [], }, { domain: 'root', name: '', pattern: '/contact', methods: ['GET', 'HEAD'], handler: 'ContactController.handle', middleware: [], }, ], }, ] ) }) test('output complete controller namespace when using a custom namespace', async ({ assert }) => { const app = new Application(__dirname, 'test', {}) const router = new Router({} as any, precompiler.compileRoute.bind(precompiler)) ioc.bind('App/Controllers/Http/HomeController', () => {}) ioc.bind('App/Admin/ContactController', () => {}) router.get('about', 'HomeController.index') router.get('contact', 'ContactController').namespace('App/Admin') router.commit() app.container.bind('Adonis/Core/Route', () => router) const listRoutes = new ListRoutes(app, new Kernel(app)) listRoutes.json = true listRoutes.logger.useRenderer(testingRenderer) await listRoutes.run() assert.deepEqual( testingRenderer.logs.map(({ message }) => JSON.parse(message)), [ { root: [ { domain: 'root', name: '', pattern: '/about', methods: ['GET', 'HEAD'], handler: 'HomeController.index', middleware: [], }, { domain: 'root', name: '', pattern: '/contact', methods: ['GET', 'HEAD'], handler: 'App/Admin/ContactController.handle', middleware: [], }, ], }, ] ) }) test('ignore custom namespace when its same as the default namespace', async ({ assert }) => { const app = new Application(__dirname, 'test', {}) const router = new Router({} as any, precompiler.compileRoute.bind(precompiler)) ioc.bind('App/Controllers/Http/HomeController', () => {}) ioc.bind('App/Controllers/Http/ContactController', () => {}) router.get('about', 'HomeController.index') router.get('contact', 'ContactController').namespace('App/Controllers/Http') router.commit() app.container.bind('Adonis/Core/Route', () => router) const listRoutes = new ListRoutes(app, new Kernel(app)) listRoutes.json = true listRoutes.logger.useRenderer(testingRenderer) await listRoutes.run() assert.deepEqual( testingRenderer.logs.map(({ message }) => JSON.parse(message)), [ { root: [ { domain: 'root', name: '', pattern: '/about', methods: ['GET', 'HEAD'], handler: 'HomeController.index', middleware: [], }, { domain: 'root', name: '', pattern: '/contact', methods: ['GET', 'HEAD'], handler: 'ContactController.handle', middleware: [], }, ], }, ] ) }) test('output route custom domain', async ({ assert }) => { const app = new Application(__dirname, 'test', {}) const router = new Router({} as any, precompiler.compileRoute.bind(precompiler)) router.get('about', async () => {}).domain('blogger.com') router.commit() app.container.bind('Adonis/Core/Route', () => router) const listRoutes = new ListRoutes(app, new Kernel(app)) listRoutes.json = true listRoutes.logger.useRenderer(testingRenderer) await listRoutes.run() assert.deepEqual( testingRenderer.logs.map(({ message }) => JSON.parse(message)), [ { 'blogger.com': [ { domain: 'blogger.com', name: '', pattern: '/about', methods: ['GET', 'HEAD'], handler: 'Closure', middleware: [], }, ], }, ] ) }) test('prefix route group pattern', async ({ assert }) => { const app = new Application(__dirname, 'test', {}) const router = new Router({} as any, precompiler.compileRoute.bind(precompiler)) router .group(() => { router.get('about', async () => {}).domain('blogger.com') }) .prefix('v1') router.commit() app.container.bind('Adonis/Core/Route', () => router) const listRoutes = new ListRoutes(app, new Kernel(app)) listRoutes.json = true listRoutes.logger.useRenderer(testingRenderer) await listRoutes.run() assert.deepEqual( testingRenderer.logs.map(({ message }) => JSON.parse(message)), [ { 'blogger.com': [ { domain: 'blogger.com', name: '', pattern: '/v1/about', methods: ['GET', 'HEAD'], handler: 'Closure', middleware: [], }, ], }, ] ) }) test('filter routes by method', async ({ assert }) => { const app = new Application(__dirname, 'test', {}) const router = new Router({} as any, precompiler.compileRoute.bind(precompiler)) router.get('about', async () => {}) router.post('contact', async () => {}) router.commit() app.container.bind('Adonis/Core/Route', () => router) const listRoutes = new ListRoutes(app, new Kernel(app)) listRoutes.logger.useRenderer(testingRenderer) listRoutes.json = true listRoutes.methodsFilter = ['GET'] await listRoutes.run() assert.deepEqual( testingRenderer.logs.map(({ message }) => JSON.parse(message)), [ { root: [ { domain: 'root', name: '', pattern: '/about', methods: ['GET', 'HEAD'], handler: 'Closure', middleware: [], }, ], }, ] ) }) test('filter routes by name', async ({ assert }) => { const app = new Application(__dirname, 'test', {}) const router = new Router({} as any, precompiler.compileRoute.bind(precompiler)) router.get('about', async () => {}) router.post('contact', async () => {}).as('contactUs') router.commit() app.container.bind('Adonis/Core/Route', () => router) const listRoutes = new ListRoutes(app, new Kernel(app)) listRoutes.logger.useRenderer(testingRenderer) listRoutes.json = true listRoutes.namesFilter = ['contactUs'] await listRoutes.run() assert.deepEqual( testingRenderer.logs.map(({ message }) => JSON.parse(message)), [ { root: [ { domain: 'root', name: 'contactUs', pattern: '/contact', methods: ['POST'], handler: 'Closure', middleware: [], }, ], }, ] ) }) test('filter routes by route pattern', async ({ assert }) => { const app = new Application(__dirname, 'test', {}) const router = new Router({} as any, precompiler.compileRoute.bind(precompiler)) router.get('about', async () => {}) router.post('contact', async () => {}) router.commit() app.container.bind('Adonis/Core/Route', () => router) const listRoutes = new ListRoutes(app, new Kernel(app)) listRoutes.logger.useRenderer(testingRenderer) listRoutes.json = true listRoutes.patternsFilter = ['/ab'] await listRoutes.run() assert.deepEqual( testingRenderer.logs.map(({ message }) => JSON.parse(message)), [ { root: [ { domain: 'root', name: '', pattern: '/about', methods: ['GET', 'HEAD'], handler: 'Closure', middleware: [], }, ], }, ] ) }) test('apply a combination of filters', async ({ assert }) => { const app = new Application(__dirname, 'test', {}) const router = new Router({} as any, precompiler.compileRoute.bind(precompiler)) router.get('about', async () => {}) router.post('about', async () => {}) router.put('about', async () => {}).as('editDetails') router.get('contact', async () => {}) router.commit() app.container.bind('Adonis/Core/Route', () => router) const listRoutes = new ListRoutes(app, new Kernel(app)) listRoutes.logger.useRenderer(testingRenderer) listRoutes.json = true listRoutes.patternsFilter = ['/ab'] listRoutes.methodsFilter = ['GET'] listRoutes.namesFilter = ['editDetails'] await listRoutes.run() assert.deepEqual( testingRenderer.logs.map(({ message }) => JSON.parse(message)), [ { root: [], }, ] ) }) })
the_stack
import { IconCommonAdd, IconCommonStoryBlock } from '@app/assets/icons' import { mergeTokens, splitToken, tokenPosition2SplitedTokenPosition } from '@app/components/editor/helpers/tokenManipulation' import { useBindHovering } from '@app/hooks' import { useBlockSuspense, useSearchBlocks } from '@app/hooks/api' import { useBlockTranscations } from '@app/hooks/useBlockTranscation' import { ThemingVariables } from '@app/styles' import { Editor } from '@app/types' import { blockIdGenerator, DEFAULT_TITLE, TelleryGlyph } from '@app/utils' import { css } from '@emotion/css' import { motion } from 'framer-motion' import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' import scrollIntoView from 'scroll-into-view-if-needed' import invariant from 'tiny-invariant' import { BlockTitle } from '..' import { EditorPopover } from '../EditorPopover' import { TellerySelection, tellerySelection2Native, TellerySelectionType } from '../helpers/tellerySelection' import { useEditor, useGetBlockTitleTextSnapshot } from '../hooks' import { useEditableContextMenu } from '../hooks/useEditableContextMenu' interface BlockReferenceDropDownInterface { open: boolean id: string keyword: string blockRef: React.MutableRefObject<HTMLDivElement | null> setOpen: (show: boolean) => void selection: TellerySelection | null } export const _BlockReferenceDropdown: React.FC<BlockReferenceDropDownInterface> = (props) => { const { id, keyword, open, setOpen, selection } = props const [referenceRange, setReferenceRange] = useState<null | Range | HTMLElement>(null) useEffect(() => { if (open) { invariant(selection, 'selection is null') setReferenceRange((_referenceRange) => { const range = tellerySelection2Native(selection) invariant(range, 'range is null') // const _range = docSelection.rangeCount > 0 && docSelection.getRangeAt(0).cloneRange() // invariant(_range, 'selection not exist') if (range.getClientRects().length === 0) { return range.startContainer as HTMLElement } else { return range } }) } else { setOpen(false) setReferenceRange(null) } // eslint-disable-next-line react-hooks/exhaustive-deps }, [open, setOpen]) useEffect(() => { if (selection && selection.type === TellerySelectionType.Inline && open) { if (selection.focus.nodeIndex <= selection.anchor.nodeIndex && selection.focus.offset < selection.anchor.offset) { setOpen(false) } } }, [open, selection, setOpen]) return ( <EditorPopover open={open} setOpen={setOpen} referenceElement={referenceRange ?? null} placement="bottom-start" lockBodyScroll > {referenceRange && open && ( <_BlockReferenceDropdownInner {...props} open={!!(referenceRange && open)} referenceRange={referenceRange} /> )} </EditorPopover> ) // return <_BlockReferenceDropdownInner {...props} open={!!(referenceRange && open)} referenceRange={referenceRange} /> } export const _BlockReferenceDropdownInner: React.FC< BlockReferenceDropDownInterface & { referenceRange: null | Range | HTMLElement } > = (props) => { const { id, keyword, open, setOpen, blockRef, selection, referenceRange } = props const editor = useEditor<Editor.BaseBlock>() const currentBlock = useBlockSuspense(id) // const [referenceRange, setReferenceRange] = useState<null | Range>(null) const { data, isLoading } = useSearchBlocks(keyword, 10, Editor.BlockType.Story, { enabled: !!keyword, keepPreviousData: true }) const stories = useMemo( () => (data && keyword ? data.searchResults.map((id) => data.blocks[id]) : []), [data, keyword] ) const blockTranscations = useBlockTranscations() const searchResultClickHandler = useCallback( async (index) => { if (currentBlock?.content?.title) { const exec = async (currentBlock: Editor.BaseBlock) => { if (selection?.type === TellerySelectionType.Block) return const tokens = currentBlock?.content?.title ?? [] const splitedTokens = splitToken(tokens) const textStart = tokenPosition2SplitedTokenPosition( tokens, selection!.anchor.nodeIndex, selection!.anchor.offset ) const end = tokenPosition2SplitedTokenPosition(tokens, selection!.focus.nodeIndex, selection!.focus.offset) if (typeof textStart !== 'number' || typeof end !== 'number') { return } const start = textStart - 2 const getNewToken = async (index: number): Promise<Editor.Token> => { if (index <= 0 || !stories) { const newStoryId = blockIdGenerator() const title = keyword ?? DEFAULT_TITLE await blockTranscations.createNewStory({ id: newStoryId, title }) return [TelleryGlyph.BI_LINK, [[Editor.InlineType.Reference, 's', `${newStoryId}`]]] } else { const referenceIndex = index - 1 const story = stories[referenceIndex] return [TelleryGlyph.BI_LINK, [[Editor.InlineType.Reference, 's', `${story.id}`]]] } } const newToken: Editor.Token = await getNewToken(index) splitedTokens.splice(start, end - start, newToken) const mergedTokens = mergeTokens(splitedTokens) editor?.updateBlockTitle?.(currentBlock.id, mergedTokens) setOpen(false) } await exec({ ...currentBlock }) } }, [blockTranscations, currentBlock, editor, keyword, selection, setOpen, stories] ) const getBlockTitle = useGetBlockTitleTextSnapshot() const hasExactSame = useMemo(() => { if (stories?.length === 0) return false return stories?.some((story) => getBlockTitle(story) === keyword) }, [keyword, stories, getBlockTitle]) useEffect(() => { if (selection && selection.type === TellerySelectionType.Inline && open) { if (selection.focus.nodeIndex <= selection.anchor.nodeIndex && selection.focus.offset < selection.anchor.offset) { setOpen(false) } } }, [open, selection, setOpen]) const items = useMemo(() => { const storyItems = stories?.map((story, index) => { const action = () => searchResultClickHandler(index + 1) return { id: story.id, view: ( <> <div className={css` width: 36px; height: 36px; border-radius: 4px; margin-right: 10px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; `} > <IconCommonStoryBlock /> </div> {story && ( <div className={css` white-space: nowrap; text-overflow: ellipsis; overflow: hidden; flex-shrink: 1; `} > <BlockTitle block={story} /> </div> )} </> ), action: action } }) ?? [] if (hasExactSame === false) { const action = () => searchResultClickHandler(0) storyItems.unshift({ id: 'create', view: ( <> <div className={css` width: 36px; height: 36px; background: ${ThemingVariables.colors.primary[4]}; border-radius: 4px; margin-right: 10px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; `} > <IconCommonAdd color={ThemingVariables.colors.primary[1]} /> </div> Create {keyword} </> ), action: action }) } return storyItems }, [hasExactSame, keyword, searchResultClickHandler, stories]) const [currentIndex, setIndex] = useEditableContextMenu( open, useMemo(() => items.map((item) => item.action), [items]), blockRef ) return ( <motion.div aria-label="Block Reference" className={css` outline: none; background: ${ThemingVariables.colors.gray[5]}; box-shadow: ${ThemingVariables.boxShadows[0]}; border-radius: 8px; display: flex; flex-direction: column; align-items: stretch; max-height: 200px; width: 280px; overflow-x: hidden; overflow-y: auto; user-select: none; padding: 8px; font-weight: normal; & * + * { margin-top: 2px; } `} onMouseDown={(e) => { e.preventDefault() e.stopPropagation() }} > {keyword ? ( <> <div className={css` font-size: 12px; color: #888; `} > Reference story <span>{isLoading && 'loading'}</span> </div> {items.map((item, index) => ( <DropDownMenuItem key={item.id} onClick={item.action} active={currentIndex === index} index={index} setIndex={setIndex as (index: number) => void} > {item.view} </DropDownMenuItem> ))} </> ) : ( <div className={css` font-size: 14px; line-height: 16px; color: ${ThemingVariables.colors.text[2]}; padding: 14px 12px; `} > Search a story </div> )} </motion.div> ) } const DropDownMenuItem: React.FC<{ onClick: React.MouseEventHandler<HTMLDivElement> active: boolean setIndex: (index: number) => void index: number }> = ({ children, onClick, active, setIndex, index }) => { const ref = useRef<HTMLDivElement | null>(null) const [hoveringHandlers, hovering] = useBindHovering() useEffect(() => { if (hovering) { setIndex(index) } // eslint-disable-next-line react-hooks/exhaustive-deps }, [hovering, setIndex]) useEffect(() => { if (active && ref.current) { scrollIntoView(ref.current, { scrollMode: 'always', block: 'nearest', inline: 'nearest' }) } }, [active, ref]) return ( <div ref={ref} {...hoveringHandlers()} onClick={onClick} data-active={active} className={css` background: transparent; border: none; cursor: pointer; border-radius: 8px; padding: 4px; display: flex; justify-content: flex-start; align-items: center; font-size: 14px; line-height: 17px; cursor: pointer; padding: 4px; display: flex; justify-content: flex-start; align-items: center; font-size: 14px; line-height: 17px; color: ${ThemingVariables.colors.text[0]}; &:hover { background-color: ${ThemingVariables.colors.primary[4]} !important; } &:active, &[data-active='true'] { background-color: ${ThemingVariables.colors.primary[4]} !important; } `} > {children} </div> ) } _BlockReferenceDropdown.whyDidYouRender = { logOnDifferentValues: true, customName: '_BlockReferenceDropdown' } export const BlockReferenceDropdown = memo(_BlockReferenceDropdown)
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [ssm](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awssystemsmanager.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Ssm extends PolicyStatement { public servicePrefix = 'ssm'; /** * Statement provider for service [ssm](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awssystemsmanager.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to add or overwrite one or more tags for a specified AWS resource * * Access Level: Tagging * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_AddTagsToResource.html */ public toAddTagsToResource() { return this.to('AddTagsToResource'); } /** * Grants permission to associate RelatedItem to an OpsItem * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_AssociateOpsItemRelatedItem.html */ public toAssociateOpsItemRelatedItem() { return this.to('AssociateOpsItemRelatedItem'); } /** * Grants permission to cancel a specified Run Command command * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CancelCommand.html */ public toCancelCommand() { return this.to('CancelCommand'); } /** * Grants permission to cancel an in-progress maintenance window execution * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CancelMaintenanceWindowExecution.html */ public toCancelMaintenanceWindowExecution() { return this.to('CancelMaintenanceWindowExecution'); } /** * Grants permission to create an activation that is used to register on-premises servers and virtual machines (VMs) with Systems Manager * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateActivation.html */ public toCreateActivation() { return this.to('CreateActivation'); } /** * Grants permission to associate a specified Systems Manager document with specified instances or other targets * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateAssociation.html */ public toCreateAssociation() { return this.to('CreateAssociation'); } /** * Grants permission to combine entries for multiple CreateAssociation operations in a single command * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateAssociationBatch.html */ public toCreateAssociationBatch() { return this.to('CreateAssociationBatch'); } /** * Grants permission to create a Systems Manager SSM document * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - iam:PassRole * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateDocument.html */ public toCreateDocument() { return this.to('CreateDocument'); } /** * Grants permission to create a maintenance window * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateMaintenanceWindow.html */ public toCreateMaintenanceWindow() { return this.to('CreateMaintenanceWindow'); } /** * Grants permission to create an OpsItem in OpsCenter * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateOpsItem.html */ public toCreateOpsItem() { return this.to('CreateOpsItem'); } /** * Grants permission to create an OpsMetadata object for an AWS resource * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateOpsMetadata.html */ public toCreateOpsMetadata() { return this.to('CreateOpsMetadata'); } /** * Grants permission to create a patch baseline * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreatePatchBaseline.html */ public toCreatePatchBaseline() { return this.to('CreatePatchBaseline'); } /** * Grants permission to create a resource data sync configuration, which regularly collects inventory data from managed instances and updates the data in an Amazon S3 bucket * * Access Level: Write * * Possible conditions: * - .ifSyncType() * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateResourceDataSync.html */ public toCreateResourceDataSync() { return this.to('CreateResourceDataSync'); } /** * Grants permission to delete a specified activation for managed instances * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeleteActivation.html */ public toDeleteActivation() { return this.to('DeleteActivation'); } /** * Grants permission to disassociate a specified SSM document from a specified instance * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeleteAssociation.html */ public toDeleteAssociation() { return this.to('DeleteAssociation'); } /** * Grants permission to delete a specified SSM document and its instance associations * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeleteDocument.html */ public toDeleteDocument() { return this.to('DeleteDocument'); } /** * Grants permission to delete a specified custom inventory type, or the data associated with a custom inventory type * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeleteInventory.html */ public toDeleteInventory() { return this.to('DeleteInventory'); } /** * Grants permission to delete a specified maintenance window * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeleteMaintenanceWindow.html */ public toDeleteMaintenanceWindow() { return this.to('DeleteMaintenanceWindow'); } /** * Grants permission to delete an OpsMetadata object * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeleteOpsMetadata.html */ public toDeleteOpsMetadata() { return this.to('DeleteOpsMetadata'); } /** * Grants permission to delete a specified SSM parameter * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeleteParameter.html */ public toDeleteParameter() { return this.to('DeleteParameter'); } /** * Grants permission to delete multiple specified SSM parameters * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeleteParameters.html */ public toDeleteParameters() { return this.to('DeleteParameters'); } /** * Grants permission to delete a specified patch baseline * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeletePatchBaseline.html */ public toDeletePatchBaseline() { return this.to('DeletePatchBaseline'); } /** * Grants permission to delete a specified resource data sync * * Access Level: Write * * Possible conditions: * - .ifSyncType() * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeleteResourceDataSync.html */ public toDeleteResourceDataSync() { return this.to('DeleteResourceDataSync'); } /** * Grants permission to deregister a specified on-premises server or virtual machine (VM) from Systems Manager * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeregisterManagedInstance.html */ public toDeregisterManagedInstance() { return this.to('DeregisterManagedInstance'); } /** * Grants permission to deregister a specified patch baseline from being the default patch baseline for a specified patch group * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeregisterPatchBaselineForPatchGroup.html */ public toDeregisterPatchBaselineForPatchGroup() { return this.to('DeregisterPatchBaselineForPatchGroup'); } /** * Grants permission to deregister a specified target from a maintenance window * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeregisterTargetFromMaintenanceWindow.html */ public toDeregisterTargetFromMaintenanceWindow() { return this.to('DeregisterTargetFromMaintenanceWindow'); } /** * Grants permission to deregister a specified task from a maintenance window * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeregisterTaskFromMaintenanceWindow.html */ public toDeregisterTaskFromMaintenanceWindow() { return this.to('DeregisterTaskFromMaintenanceWindow'); } /** * Grants permission to view details about a specified managed instance activation, such as when it was created and the number of instances registered using the activation * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeActivations.html */ public toDescribeActivations() { return this.to('DescribeActivations'); } /** * Grants permission to view details about the specified association for a specified instance or target * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeAssociation.html */ public toDescribeAssociation() { return this.to('DescribeAssociation'); } /** * Grants permission to view information about a specified association execution * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeAssociationExecutionTargets.html */ public toDescribeAssociationExecutionTargets() { return this.to('DescribeAssociationExecutionTargets'); } /** * Grants permission to view all executions for a specified association * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeAssociationExecutions.html */ public toDescribeAssociationExecutions() { return this.to('DescribeAssociationExecutions'); } /** * Grants permission to view details about all active and terminated Automation executions * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeAutomationExecutions.html */ public toDescribeAutomationExecutions() { return this.to('DescribeAutomationExecutions'); } /** * Grants permission to view information about all active and terminated step executions in an Automation workflow * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeAutomationStepExecutions.html */ public toDescribeAutomationStepExecutions() { return this.to('DescribeAutomationStepExecutions'); } /** * Grants permission to view all patches eligible to include in a patch baseline * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeAvailablePatches.html */ public toDescribeAvailablePatches() { return this.to('DescribeAvailablePatches'); } /** * Grants permission to view details about a specified SSM document * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeDocument.html */ public toDescribeDocument() { return this.to('DescribeDocument'); } /** * Grants permission to display information about SSM document parameters in the Systems Manager console (internal Systems Manager action) * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up-messageAPIs.html */ public toDescribeDocumentParameters() { return this.to('DescribeDocumentParameters'); } /** * Grants permission to view the permissions for a specified SSM document * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeDocumentPermission.html */ public toDescribeDocumentPermission() { return this.to('DescribeDocumentPermission'); } /** * Grants permission to view all current associations for a specified instance * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeEffectiveInstanceAssociations.html */ public toDescribeEffectiveInstanceAssociations() { return this.to('DescribeEffectiveInstanceAssociations'); } /** * Grants permission to view details about the patches currently associated with the specified patch baseline (Windows only) * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeEffectivePatchesForPatchBaseline.html */ public toDescribeEffectivePatchesForPatchBaseline() { return this.to('DescribeEffectivePatchesForPatchBaseline'); } /** * Grants permission to view the status of the associations for a specified instance * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInstanceAssociationsStatus.html */ public toDescribeInstanceAssociationsStatus() { return this.to('DescribeInstanceAssociationsStatus'); } /** * Grants permission to view details about a specified instance * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInstanceInformation.html */ public toDescribeInstanceInformation() { return this.to('DescribeInstanceInformation'); } /** * Grants permission to view status details about patches on a specified instance * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInstancePatchStates.html */ public toDescribeInstancePatchStates() { return this.to('DescribeInstancePatchStates'); } /** * Grants permission to describe the high-level patch state for the instances in the specified patch group * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInstancePatchStatesForPatchGroup.html */ public toDescribeInstancePatchStatesForPatchGroup() { return this.to('DescribeInstancePatchStatesForPatchGroup'); } /** * Grants permission to view general details about the patches on a specified instance * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInstancePatches.html */ public toDescribeInstancePatches() { return this.to('DescribeInstancePatches'); } /** * Grants permission to user's Amazon EC2 console to render managed instances' nodes * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up-messageAPIs.html */ public toDescribeInstanceProperties() { return this.to('DescribeInstanceProperties'); } /** * Grants permission to view details about a specified inventory deletion * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInventoryDeletions.html */ public toDescribeInventoryDeletions() { return this.to('DescribeInventoryDeletions'); } /** * Grants permission to view details of a specified task execution for a maintenance window * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeMaintenanceWindowExecutionTaskInvocations.html */ public toDescribeMaintenanceWindowExecutionTaskInvocations() { return this.to('DescribeMaintenanceWindowExecutionTaskInvocations'); } /** * Grants permission to view details about the tasks that ran during a specified maintenance window execution * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeMaintenanceWindowExecutionTasks.html */ public toDescribeMaintenanceWindowExecutionTasks() { return this.to('DescribeMaintenanceWindowExecutionTasks'); } /** * Grants permission to view the executions of a specified maintenance window * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeMaintenanceWindowExecutions.html */ public toDescribeMaintenanceWindowExecutions() { return this.to('DescribeMaintenanceWindowExecutions'); } /** * Grants permission to view details about upcoming executions of a specified maintenance window * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeMaintenanceWindowSchedule.html */ public toDescribeMaintenanceWindowSchedule() { return this.to('DescribeMaintenanceWindowSchedule'); } /** * Grants permission to view a list of the targets associated with a specified maintenance window * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeMaintenanceWindowTargets.html */ public toDescribeMaintenanceWindowTargets() { return this.to('DescribeMaintenanceWindowTargets'); } /** * Grants permission to view a list of the tasks associated with a specified maintenance window * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeMaintenanceWindowTasks.html */ public toDescribeMaintenanceWindowTasks() { return this.to('DescribeMaintenanceWindowTasks'); } /** * Grants permission to view information about all or specified maintenance windows * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeMaintenanceWindows.html */ public toDescribeMaintenanceWindows() { return this.to('DescribeMaintenanceWindows'); } /** * Grants permission to view information about the maintenance window targets and tasks associated with a specified instance * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeMaintenanceWindowsForTarget.html */ public toDescribeMaintenanceWindowsForTarget() { return this.to('DescribeMaintenanceWindowsForTarget'); } /** * Grants permission to view details about specified OpsItems * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeOpsItems.html */ public toDescribeOpsItems() { return this.to('DescribeOpsItems'); } /** * Grants permission to view details about a specified SSM parameter * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeParameters.html */ public toDescribeParameters() { return this.to('DescribeParameters'); } /** * Grants permission to view information about patch baselines that meet the specified criteria * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribePatchBaselines.html */ public toDescribePatchBaselines() { return this.to('DescribePatchBaselines'); } /** * Grants permission to view aggregated status details for patches for a specified patch group * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribePatchGroupState.html */ public toDescribePatchGroupState() { return this.to('DescribePatchGroupState'); } /** * Grants permission to view information about the patch baseline for a specified patch group * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribePatchGroups.html */ public toDescribePatchGroups() { return this.to('DescribePatchGroups'); } /** * Grants permission to view details of available patches for a specified operating system and patch property * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribePatchProperties.html */ public toDescribePatchProperties() { return this.to('DescribePatchProperties'); } /** * Grants permission to view a list of recent Session Manager sessions that meet the specified search criteria * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeSessions.html */ public toDescribeSessions() { return this.to('DescribeSessions'); } /** * Grants permission to disassociate RelatedItem from an OpsItem * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DisassociateOpsItemRelatedItem.html */ public toDisassociateOpsItemRelatedItem() { return this.to('DisassociateOpsItemRelatedItem'); } /** * Grants permission to view details of a specified Automation execution * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_AutomationExecution.html */ public toGetAutomationExecution() { return this.to('GetAutomationExecution'); } /** * Grants permission to view the calendar state for a change calendar or a list of change calendars * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetCalendarState.html */ public toGetCalendarState() { return this.to('GetCalendarState'); } /** * Grants permission to view details about the command execution of a specified invocation or plugin * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetCommandInvocation.html */ public toGetCommandInvocation() { return this.to('GetCommandInvocation'); } /** * Grants permission to view the Session Manager connection status for a specified managed instance * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetConnectionStatus.html */ public toGetConnectionStatus() { return this.to('GetConnectionStatus'); } /** * Grants permission to view the current default patch baseline for a specified operating system type * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetDefaultPatchBaseline.html */ public toGetDefaultPatchBaseline() { return this.to('GetDefaultPatchBaseline'); } /** * Grants permission to retrieve the current patch baseline snapshot for a specified instance * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetDeployablePatchSnapshotForInstance.html */ public toGetDeployablePatchSnapshotForInstance() { return this.to('GetDeployablePatchSnapshotForInstance'); } /** * Grants permission to view the contents of a specified SSM document * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetDocument.html */ public toGetDocument() { return this.to('GetDocument'); } /** * Grants permission to view instance inventory details per the specified criteria * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetInventory.html */ public toGetInventory() { return this.to('GetInventory'); } /** * Grants permission to view a list of inventory types or attribute names for a specified inventory item type * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetInventorySchema.html */ public toGetInventorySchema() { return this.to('GetInventorySchema'); } /** * Grants permission to view details about a specified maintenance window * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetMaintenanceWindow.html */ public toGetMaintenanceWindow() { return this.to('GetMaintenanceWindow'); } /** * Grants permission to view details about a specified maintenance window execution * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetMaintenanceWindowExecution.html */ public toGetMaintenanceWindowExecution() { return this.to('GetMaintenanceWindowExecution'); } /** * Grants permission to view details about a specified maintenance window execution task * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetMaintenanceWindowExecutionTask.html */ public toGetMaintenanceWindowExecutionTask() { return this.to('GetMaintenanceWindowExecutionTask'); } /** * Grants permission to view details about a specific maintenance window task running on a specific target * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetMaintenanceWindowExecutionTaskInvocation.html */ public toGetMaintenanceWindowExecutionTaskInvocation() { return this.to('GetMaintenanceWindowExecutionTaskInvocation'); } /** * Grants permission to view details about tasks registered with a specified maintenance window * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetMaintenanceWindowTask.html */ public toGetMaintenanceWindowTask() { return this.to('GetMaintenanceWindowTask'); } /** * Used by Systems Manager and SSM Agent to determine package installation requirements for an instance (internal Systems Manager call) * * Access Level: Read */ public toGetManifest() { return this.to('GetManifest'); } /** * Grants permission to view information about a specified OpsItem * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetOpsItem.html */ public toGetOpsItem() { return this.to('GetOpsItem'); } /** * Grants permission to retrieve an OpsMetadata object * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetOpsMetadata.html */ public toGetOpsMetadata() { return this.to('GetOpsMetadata'); } /** * Grants permission to view summary information about OpsItems based on specified filters and aggregators * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetOpsSummary.html */ public toGetOpsSummary() { return this.to('GetOpsSummary'); } /** * Grants permission to view information about a specified parameter * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetParameter.html */ public toGetParameter() { return this.to('GetParameter'); } /** * Grants permission to view details and changes for a specified parameter * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetParameterHistory.html */ public toGetParameterHistory() { return this.to('GetParameterHistory'); } /** * Grants permission to view information about multiple specified parameters * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetParameters.html */ public toGetParameters() { return this.to('GetParameters'); } /** * Grants permission to view information about parameters in a specified hierarchy * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetParametersByPath.html */ public toGetParametersByPath() { return this.to('GetParametersByPath'); } /** * Grants permission to view information about a specified patch baseline * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetPatchBaseline.html */ public toGetPatchBaseline() { return this.to('GetPatchBaseline'); } /** * Grants permission to view the ID of the current patch baseline for a specified patch group * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetPatchBaselineForPatchGroup.html */ public toGetPatchBaselineForPatchGroup() { return this.to('GetPatchBaselineForPatchGroup'); } /** * Grants permission to view the account-level setting for an AWS service * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetServiceSetting.html */ public toGetServiceSetting() { return this.to('GetServiceSetting'); } /** * Grants permission to apply an identifying label to a specified version of a parameter * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_LabelParameterVersion.html */ public toLabelParameterVersion() { return this.to('LabelParameterVersion'); } /** * Grants permission to list versions of the specified association * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListAssociationVersions.html */ public toListAssociationVersions() { return this.to('ListAssociationVersions'); } /** * Grants permission to list the associations for a specified SSM document or managed instance * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListAssociations.html */ public toListAssociations() { return this.to('ListAssociations'); } /** * Grants permission to list information about command invocations sent to a specified instance * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListCommandInvocations.html */ public toListCommandInvocations() { return this.to('ListCommandInvocations'); } /** * Grants permission to list the commands sent to a specified instance * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListCommands.html */ public toListCommands() { return this.to('ListCommands'); } /** * Grants permission to list compliance status for specified resource types on a specified resource * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListComplianceItems.html */ public toListComplianceItems() { return this.to('ListComplianceItems'); } /** * Grants permission to list a summary count of compliant and noncompliant resources for a specified compliance type * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListComplianceSummaries.html */ public toListComplianceSummaries() { return this.to('ListComplianceSummaries'); } /** * Grants permission to view metadata history about a specified SSM document * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListDocumentMetadataHistory.html */ public toListDocumentMetadataHistory() { return this.to('ListDocumentMetadataHistory'); } /** * Grants permission to list all versions of a specified document * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListDocumentVersions.html */ public toListDocumentVersions() { return this.to('ListDocumentVersions'); } /** * Grants permission to view information about a specified SSM document * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListDocuments.html */ public toListDocuments() { return this.to('ListDocuments'); } /** * Used by SSM Agent to check for new State Manager associations (internal Systems Manager call) * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up-messageAPIs.html */ public toListInstanceAssociations() { return this.to('ListInstanceAssociations'); } /** * Grants permission to view a list of specified inventory types for a specified instance * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListInventoryEntries.html */ public toListInventoryEntries() { return this.to('ListInventoryEntries'); } /** * Grants permission to view details about OpsItemEvents * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListOpsItemEvents.html */ public toListOpsItemEvents() { return this.to('ListOpsItemEvents'); } /** * Grants permission to view details about OpsItem RelatedItems * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListOpsItemRelatedItems.html */ public toListOpsItemRelatedItems() { return this.to('ListOpsItemRelatedItems'); } /** * Grants permission to view a list of OpsMetadata objects * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListOpsMetadata.html */ public toListOpsMetadata() { return this.to('ListOpsMetadata'); } /** * Grants permission to list resource-level summary count * * Access Level: List * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListResourceComplianceSummaries.html */ public toListResourceComplianceSummaries() { return this.to('ListResourceComplianceSummaries'); } /** * Grants permission to list information about resource data sync configurations in an account * * Access Level: List * * Possible conditions: * - .ifSyncType() * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListResourceDataSync.html */ public toListResourceDataSync() { return this.to('ListResourceDataSync'); } /** * Grants permission to view a list of resource tags for a specified resource * * Access Level: Read * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to share a custom SSM document publicly or privately with specified AWS accounts * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ModifyDocumentPermission.html */ public toModifyDocumentPermission() { return this.to('ModifyDocumentPermission'); } /** * Grants permission to register a compliance type and other compliance details on a specified resource * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_PutComplianceItems.html */ public toPutComplianceItems() { return this.to('PutComplianceItems'); } /** * Used by SSM Agent to generate a report of the results of specific agent requests (internal Systems Manager call) * * Access Level: Read */ public toPutConfigurePackageResult() { return this.to('PutConfigurePackageResult'); } /** * Grants permission to add or update inventory items on multiple specified managed instances * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_PutInventory.html */ public toPutInventory() { return this.to('PutInventory'); } /** * Grants permission to create an SSM parameter * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_PutParameter.html */ public toPutParameter() { return this.to('PutParameter'); } /** * Grants permission to specify the default patch baseline for an operating system type * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_RegisterDefaultPatchBaseline.html */ public toRegisterDefaultPatchBaseline() { return this.to('RegisterDefaultPatchBaseline'); } /** * Grants permission to specify the default patch baseline for a specified patch group * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_RegisterPatchBaselineForPatchGroup.html */ public toRegisterPatchBaselineForPatchGroup() { return this.to('RegisterPatchBaselineForPatchGroup'); } /** * Grants permission to register a target with a specified maintenance window * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_RegisterTargetWithMaintenanceWindow.html */ public toRegisterTargetWithMaintenanceWindow() { return this.to('RegisterTargetWithMaintenanceWindow'); } /** * Grants permission to register a task with a specified maintenance window * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_RegisterTaskWithMaintenanceWindow.html */ public toRegisterTaskWithMaintenanceWindow() { return this.to('RegisterTaskWithMaintenanceWindow'); } /** * Grants permission to remove a specified tag key from a specified resource * * Access Level: Tagging * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_RemoveTagsFromResource.html */ public toRemoveTagsFromResource() { return this.to('RemoveTagsFromResource'); } /** * Grants permission to reset the service setting for an AWS account to the default value * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ResetServiceSetting.html */ public toResetServiceSetting() { return this.to('ResetServiceSetting'); } /** * Grants permission to reconnect a Session Manager session to a managed instance * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ResumeSession.html */ public toResumeSession() { return this.to('ResumeSession'); } /** * Grants permission to send a signal to change the current behavior or status of a specified Automation execution * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_SendAutomationSignal.html */ public toSendAutomationSignal() { return this.to('SendAutomationSignal'); } /** * Grants permission to run commands on one or more specified managed instances * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * - .ifResourceTag() * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_SendCommand.html */ public toSendCommand() { return this.to('SendCommand'); } /** * Grants permission to run a specified association manually * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartAssociationsOnce.html */ public toStartAssociationsOnce() { return this.to('StartAssociationsOnce'); } /** * Grants permission to initiate the execution of an Automation document * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartAutomationExecution.html */ public toStartAutomationExecution() { return this.to('StartAutomationExecution'); } /** * Grants permission to initiate the execution of an Automation Change Template document * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartChangeRequestExecution.html */ public toStartChangeRequestExecution() { return this.to('StartChangeRequestExecution'); } /** * Grants permission to initiate a connection to a specified target for a Session Manager session * * Access Level: Write * * Possible conditions: * - .ifSessionDocumentAccessCheck() * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartSession.html */ public toStartSession() { return this.to('StartSession'); } /** * Grants permission to stop a specified Automation execution that is already in progress * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StopAutomationExecution.html */ public toStopAutomationExecution() { return this.to('StopAutomationExecution'); } /** * Grants permission to permanently end a Session Manager connection to an instance * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_TerminateSession.html */ public toTerminateSession() { return this.to('TerminateSession'); } /** * Grants permission to update an association and immediately run the association on the specified targets * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateAssociation.html */ public toUpdateAssociation() { return this.to('UpdateAssociation'); } /** * Grants permission to update the status of the SSM document associated with a specified instance * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateAssociationStatus.html */ public toUpdateAssociationStatus() { return this.to('UpdateAssociationStatus'); } /** * Grants permission to update one or more values for an SSM document * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateDocument.html */ public toUpdateDocument() { return this.to('UpdateDocument'); } /** * Grants permission to change the default version of an SSM document * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateDocumentDefaultVersion.html */ public toUpdateDocumentDefaultVersion() { return this.to('UpdateDocumentDefaultVersion'); } /** * Grants permission to update the metadata of an SSM document * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateDocumentMetadata.html */ public toUpdateDocumentMetadata() { return this.to('UpdateDocumentMetadata'); } /** * Used by SSM Agent to update the status of the association that it is currently running (internal Systems Manager call) * * Access Level: Write */ public toUpdateInstanceAssociationStatus() { return this.to('UpdateInstanceAssociationStatus'); } /** * Used by SSM Agent to send a heartbeat signal to the Systems Manager service in the cloud * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up-messageAPIs.html */ public toUpdateInstanceInformation() { return this.to('UpdateInstanceInformation'); } /** * Grants permission to update a specified maintenance window * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateMaintenanceWindow.html */ public toUpdateMaintenanceWindow() { return this.to('UpdateMaintenanceWindow'); } /** * Grants permission to update a specified maintenance window target * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateMaintenanceWindowTarget.html */ public toUpdateMaintenanceWindowTarget() { return this.to('UpdateMaintenanceWindowTarget'); } /** * Grants permission to update a specified maintenance window task * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateMaintenanceWindowTask.html */ public toUpdateMaintenanceWindowTask() { return this.to('UpdateMaintenanceWindowTask'); } /** * Grants permission to assign or change the IAM role assigned to a specified managed instance * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateManagedInstanceRole.html */ public toUpdateManagedInstanceRole() { return this.to('UpdateManagedInstanceRole'); } /** * Grants permission to edit or change an OpsItem * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateOpsItem.html */ public toUpdateOpsItem() { return this.to('UpdateOpsItem'); } /** * Grants permission to update an OpsMetadata object * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateOpsMetadata.html */ public toUpdateOpsMetadata() { return this.to('UpdateOpsMetadata'); } /** * Grants permission to update a specified patch baseline * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdatePatchBaseline.html */ public toUpdatePatchBaseline() { return this.to('UpdatePatchBaseline'); } /** * Grants permission to update a resource data sync * * Access Level: Write * * Possible conditions: * - .ifSyncType() * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateResourceDataSync.html */ public toUpdateResourceDataSync() { return this.to('UpdateResourceDataSync'); } /** * Grants permission to update the service setting for an AWS account * * Access Level: Write * * https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateServiceSetting.html */ public toUpdateServiceSetting() { return this.to('UpdateServiceSetting'); } protected accessLevelList: AccessLevelList = { "Tagging": [ "AddTagsToResource", "RemoveTagsFromResource" ], "Write": [ "AssociateOpsItemRelatedItem", "CancelCommand", "CancelMaintenanceWindowExecution", "CreateActivation", "CreateAssociation", "CreateAssociationBatch", "CreateDocument", "CreateMaintenanceWindow", "CreateOpsItem", "CreateOpsMetadata", "CreatePatchBaseline", "CreateResourceDataSync", "DeleteActivation", "DeleteAssociation", "DeleteDocument", "DeleteInventory", "DeleteMaintenanceWindow", "DeleteOpsMetadata", "DeleteParameter", "DeleteParameters", "DeletePatchBaseline", "DeleteResourceDataSync", "DeregisterManagedInstance", "DeregisterPatchBaselineForPatchGroup", "DeregisterTargetFromMaintenanceWindow", "DeregisterTaskFromMaintenanceWindow", "DisassociateOpsItemRelatedItem", "LabelParameterVersion", "ModifyDocumentPermission", "PutComplianceItems", "PutInventory", "PutParameter", "RegisterDefaultPatchBaseline", "RegisterPatchBaselineForPatchGroup", "RegisterTargetWithMaintenanceWindow", "RegisterTaskWithMaintenanceWindow", "ResetServiceSetting", "ResumeSession", "SendAutomationSignal", "SendCommand", "StartAssociationsOnce", "StartAutomationExecution", "StartChangeRequestExecution", "StartSession", "StopAutomationExecution", "TerminateSession", "UpdateAssociation", "UpdateAssociationStatus", "UpdateDocument", "UpdateDocumentDefaultVersion", "UpdateDocumentMetadata", "UpdateInstanceAssociationStatus", "UpdateInstanceInformation", "UpdateMaintenanceWindow", "UpdateMaintenanceWindowTarget", "UpdateMaintenanceWindowTask", "UpdateManagedInstanceRole", "UpdateOpsItem", "UpdateOpsMetadata", "UpdatePatchBaseline", "UpdateResourceDataSync", "UpdateServiceSetting" ], "Read": [ "DescribeActivations", "DescribeAssociation", "DescribeAssociationExecutionTargets", "DescribeAssociationExecutions", "DescribeAutomationExecutions", "DescribeAutomationStepExecutions", "DescribeAvailablePatches", "DescribeDocument", "DescribeDocumentParameters", "DescribeDocumentPermission", "DescribeEffectiveInstanceAssociations", "DescribeEffectivePatchesForPatchBaseline", "DescribeInstanceAssociationsStatus", "DescribeInstanceInformation", "DescribeInstancePatchStates", "DescribeInstancePatchStatesForPatchGroup", "DescribeInstancePatches", "DescribeInstanceProperties", "DescribeInventoryDeletions", "DescribeOpsItems", "DescribePatchGroupState", "GetAutomationExecution", "GetCalendarState", "GetCommandInvocation", "GetConnectionStatus", "GetDefaultPatchBaseline", "GetDeployablePatchSnapshotForInstance", "GetDocument", "GetInventory", "GetInventorySchema", "GetMaintenanceWindow", "GetMaintenanceWindowExecution", "GetMaintenanceWindowExecutionTask", "GetMaintenanceWindowExecutionTaskInvocation", "GetMaintenanceWindowTask", "GetManifest", "GetOpsItem", "GetOpsMetadata", "GetOpsSummary", "GetParameter", "GetParameterHistory", "GetParameters", "GetParametersByPath", "GetPatchBaseline", "GetPatchBaselineForPatchGroup", "GetServiceSetting", "ListCommandInvocations", "ListCommands", "ListDocumentMetadataHistory", "ListOpsItemEvents", "ListOpsItemRelatedItems", "ListTagsForResource", "PutConfigurePackageResult" ], "List": [ "DescribeMaintenanceWindowExecutionTaskInvocations", "DescribeMaintenanceWindowExecutionTasks", "DescribeMaintenanceWindowExecutions", "DescribeMaintenanceWindowSchedule", "DescribeMaintenanceWindowTargets", "DescribeMaintenanceWindowTasks", "DescribeMaintenanceWindows", "DescribeMaintenanceWindowsForTarget", "DescribeParameters", "DescribePatchBaselines", "DescribePatchGroups", "DescribePatchProperties", "DescribeSessions", "ListAssociationVersions", "ListAssociations", "ListComplianceItems", "ListComplianceSummaries", "ListDocumentVersions", "ListDocuments", "ListInstanceAssociations", "ListInventoryEntries", "ListOpsMetadata", "ListResourceComplianceSummaries", "ListResourceDataSync" ] }; /** * Adds a resource of type association to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html * * @param associationId - Identifier for the associationId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onAssociation(associationId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:association/${AssociationId}'; arn = arn.replace('${AssociationId}', associationId); 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 automation-execution to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-working.html * * @param automationExecutionId - Identifier for the automationExecutionId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onAutomationExecution(automationExecutionId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:automation-execution/${AutomationExecutionId}'; arn = arn.replace('${AutomationExecutionId}', automationExecutionId); 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 automation-definition to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-documents.html * * @param automationDefinitionName - Identifier for the automationDefinitionName. * @param versionId - Identifier for the versionId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onAutomationDefinition(automationDefinitionName: string, versionId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:automation-definition/${AutomationDefinitionName}:${VersionId}'; arn = arn.replace('${AutomationDefinitionName}', automationDefinitionName); arn = arn.replace('${VersionId}', versionId); 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 bucket to the statement * * @param bucketName - Identifier for the bucketName. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onBucket(bucketName: string, partition?: string) { var arn = 'arn:${Partition}:s3:::${BucketName}'; arn = arn.replace('${BucketName}', bucketName); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type document to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-ssm-docs.html * * @param documentName - Identifier for the documentName. * @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() * - .ifResourceTag() */ public onDocument(documentName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:document/${DocumentName}'; arn = arn.replace('${DocumentName}', documentName); 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 instance to the statement * * @param instanceId - Identifier for the instanceId. * @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() * - .ifResourceTag() */ public onInstance(instanceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ec2:${Region}:${Account}:instance/${InstanceId}'; arn = arn.replace('${InstanceId}', instanceId); 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 maintenancewindow to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-maintenance.html * * @param resourceId - Identifier for the resourceId. * @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() * - .ifResourceTag() */ public onMaintenancewindow(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:maintenancewindow/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); 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 managed-instance to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html * * @param instanceId - Identifier for the instanceId. * @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() * - .ifResourceTag() */ public onManagedInstance(instanceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:managed-instance/${InstanceId}'; arn = arn.replace('${InstanceId}', instanceId); 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 managed-instance-inventory to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-configuring.html * * @param instanceId - Identifier for the instanceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onManagedInstanceInventory(instanceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:managed-instance-inventory/${InstanceId}'; arn = arn.replace('${InstanceId}', instanceId); 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 opsitem to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems.html * * @param resourceId - Identifier for the resourceId. * @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 onOpsitem(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:opsitem/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); 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 opsmetadata to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/API_OpsMetadata.html * * @param resourceId - Identifier for the resourceId. * @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() * - .ifResourceTag() */ public onOpsmetadata(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:opsmetadata/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); 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 parameter to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html * * @param parameterNameWithoutLeadingSlash - Identifier for the parameterNameWithoutLeadingSlash. * @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() * - .ifResourceTag() */ public onParameter(parameterNameWithoutLeadingSlash: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:parameter/${ParameterNameWithoutLeadingSlash}'; arn = arn.replace('${ParameterNameWithoutLeadingSlash}', parameterNameWithoutLeadingSlash); 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 patchbaseline to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-patch.html * * @param patchBaselineIdResourceId - Identifier for the patchBaselineIdResourceId. * @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() * - .ifResourceTag() */ public onPatchbaseline(patchBaselineIdResourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:patchbaseline/${PatchBaselineIdResourceId}'; arn = arn.replace('${PatchBaselineIdResourceId}', patchBaselineIdResourceId); 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 session to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html * * @param sessionId - Identifier for the sessionId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onSession(sessionId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:session/${SessionId}'; arn = arn.replace('${SessionId}', sessionId); 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 resourcedatasync to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-datasync.html * * @param syncName - Identifier for the syncName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onResourcedatasync(syncName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:resource-data-sync/${SyncName}'; arn = arn.replace('${SyncName}', syncName); 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 servicesetting to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/API_ServiceSetting.html * * @param resourceId - Identifier for the resourceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onServicesetting(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:servicesetting/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); 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 windowtarget to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-maintenance-assign-targets.html * * @param windowTargetId - Identifier for the windowTargetId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onWindowtarget(windowTargetId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:windowtarget/${WindowTargetId}'; arn = arn.replace('${WindowTargetId}', windowTargetId); 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 windowtask to the statement * * https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-maintenance-assign-tasks.html * * @param windowTaskId - Identifier for the windowTaskId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onWindowtask(windowTaskId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ssm:${Region}:${Account}:windowtask/${WindowTaskId}'; arn = arn.replace('${WindowTaskId}', windowTaskId); 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 task to the statement * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/scheduling_tasks.html * * @param taskId - Identifier for the taskId. * @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 onTask(taskId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ecs:${Region}:${Account}:task/${TaskId}'; arn = arn.replace('${TaskId}', taskId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters access by controlling whether the values for specified resources can be overwritten * * https://docs.aws.amazon.com/systems-manager/latest/userguide/auth-and-access-control-iam-access-control-identity-based.html#policy-conditions * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifOverwrite(value: string | string[], operator?: Operator | string) { return this.if(`Overwrite`, value, operator || 'StringLike'); } /** * Filters access for resources created in a hierarchical structure * * https://docs.aws.amazon.com/systems-manager/latest/userguide/auth-and-access-control-iam-access-control-identity-based.html#policy-conditions * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifRecursive(value: string | string[], operator?: Operator | string) { return this.if(`Recursive`, value, operator || 'StringLike'); } /** * Filters access by verifying that a user has permission to access either the default Session Manager configuration document or the custom configuration document specified in a request * * https://docs.aws.amazon.com/systems-manager/latest/userguide/getting-started-sessiondocumentaccesscheck.html * * Applies to actions: * - .toStartSession() * * @param value `true` or `false`. **Default:** `true` */ public ifSessionDocumentAccessCheck(value?: boolean) { return this.if(`SessionDocumentAccessCheck`, (typeof value !== 'undefined' ? value : true), 'Bool'); } /** * Filters access by verifying that a user also has access to the ResourceDataSync SyncType specified in the request * * https://docs.aws.amazon.com/systems-manager/latest/userguide/auth-and-access-control-iam-access-control-identity-based.html#policy-conditions * * Applies to actions: * - .toCreateResourceDataSync() * - .toDeleteResourceDataSync() * - .toListResourceDataSync() * - .toUpdateResourceDataSync() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifSyncType(value: string | string[], operator?: Operator | string) { return this.if(`SyncType`, value, operator || 'StringLike'); } /** * Filters access based on a tag key-value pair assigned to the Systems Manager resource * * https://docs.aws.amazon.com/systems-manager/latest/userguide/auth-and-access-control-iam-access-control-identity-based.html#policy-conditions * * Applies to actions: * - .toSendCommand() * * Applies to resource types: * - document * - instance * - maintenancewindow * - managed-instance * - opsmetadata * - parameter * - patchbaseline * * @param tagKey The tag key to check * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifResourceTag(tagKey: string, value: string | string[], operator?: Operator | string) { return this.if(`ResourceTag/${ tagKey }`, value, operator || 'StringLike'); } }
the_stack
import { Ticker, UPDATE_PRIORITY } from '@pixi/ticker'; import sinon from 'sinon'; import { expect } from 'chai'; const { shared, system } = Ticker; describe('Ticker', function () { before(function () { this.length = (ticker) => { ticker = ticker || shared; if (!ticker._head || !ticker._head.next) { return 0; } let listener = ticker._head.next; let i = 0; while (listener) { listener = listener.next; i++; } return i; }; }); it('should be available', function () { expect(Ticker).to.be.a('function'); expect(shared).to.be.an.instanceof(Ticker); expect(system).to.be.an.instanceof(Ticker); }); it('should create a new ticker and destroy it', function () { const ticker = new Ticker(); ticker.start(); const listener = sinon.spy(); expect(this.length(ticker)).to.equal(0); ticker.add(listener); expect(this.length(ticker)).to.equal(1); ticker.destroy(); expect(ticker._head).to.be.null; expect(ticker.started).to.be.false; expect(this.length(ticker)).to.equal(0); }); it('should protect destroying shared ticker', function () { const listener = sinon.spy(); shared.add(listener); // needed to autoStart shared.destroy(); expect(shared._head).to.not.be.null; expect(shared.started).to.be.true; }); it('should protect destroying system ticker', function () { const listener = sinon.spy(); system.add(listener); // needed to autoStart system.destroy(); expect(system._head).to.not.be.null; expect(system.started).to.be.true; }); it('should add and remove listener', function () { const listener = sinon.spy(); const length = this.length(); shared.add(listener); expect(this.length()).to.equal(length + 1); shared.remove(listener); expect(this.length()).to.equal(length); }); it('should update a listener', function () { const listener = sinon.spy(); shared.add(listener); shared.update(); expect(listener.calledOnce).to.be.true; shared.remove(listener); shared.update(); expect(listener.calledOnce).to.be.true; }); it('should update a listener twice and remove once', function () { const listener = sinon.spy(); const length = this.length(); shared.add(listener).add(listener); shared.update(); expect(listener.calledTwice).to.be.true; expect(this.length()).to.equal(length + 2); shared.remove(listener); shared.update(); expect(listener.calledTwice).to.be.true; expect(this.length()).to.equal(length); }); it('should count listeners correctly', function () { const ticker = new Ticker(); expect(ticker.count).to.equal(0); const listener = sinon.spy(); ticker.add(listener); expect(ticker.count).to.equal(1); ticker.add(listener); expect(ticker.count).to.equal(2); ticker.remove(listener); expect(ticker.count).to.equal(0); ticker.destroy(); expect(ticker._head).to.be.null; expect(ticker.started).to.be.false; expect(this.length(ticker)).to.equal(0); }); it('should respect priority order', function () { const length = this.length(); const listener1 = sinon.spy(); const listener2 = sinon.spy(); const listener3 = sinon.spy(); const listener4 = sinon.spy(); shared.add(listener1, null, UPDATE_PRIORITY.LOW) .add(listener4, null, UPDATE_PRIORITY.INTERACTION) .add(listener3, null, UPDATE_PRIORITY.HIGH) .add(listener2, null, UPDATE_PRIORITY.NORMAL); shared.update(); expect(this.length()).to.equal(length + 4); sinon.assert.callOrder(listener4, listener3, listener2, listener1); shared.remove(listener1) .remove(listener2) .remove(listener3) .remove(listener4); expect(this.length()).to.equal(length); }); it('should auto-remove once listeners', function () { const length = this.length(); const listener = sinon.spy(); shared.addOnce(listener); shared.update(); expect(listener.calledOnce).to.be.true; expect(this.length()).to.equal(length); }); it('should call when adding same priority', function () { const length = this.length(); const listener1 = sinon.spy(); const listener2 = sinon.spy(); const listener3 = sinon.spy(); shared.add(listener1) .add(listener2) .add(listener3); shared.update(); expect(this.length()).to.equal(length + 3); sinon.assert.callOrder(listener1, listener2, listener3); shared.remove(listener1) .remove(listener2) .remove(listener3); expect(this.length()).to.equal(length); }); it.skip('should remove once listener in a stack', function () { const length = this.length(); const listener1 = sinon.spy(); const listener2 = sinon.spy(); const listener3 = sinon.spy(); shared.add(listener1, null, UPDATE_PRIORITY.HIGH); shared.addOnce(listener2, null, UPDATE_PRIORITY.NORMAL); shared.add(listener3, null, UPDATE_PRIORITY.LOW); shared.update(); expect(this.length()).to.equal(length + 2); shared.update(); expect(listener1.calledTwice).to.be.true; expect(listener2.calledOnce).to.be.true; expect(listener3.calledTwice).to.be.true; shared.remove(listener1).remove(listener3); expect(this.length()).to.equal(length); }); it('should call inserted item with a lower priority', function () { const length = this.length(); const lowListener = sinon.spy(); const highListener = sinon.spy(); const mainListener = sinon.spy(() => { shared.add(highListener, null, UPDATE_PRIORITY.HIGH); shared.add(lowListener, null, UPDATE_PRIORITY.LOW); }); shared.add(mainListener, null, UPDATE_PRIORITY.NORMAL); shared.update(); expect(this.length()).to.equal(length + 3); expect(mainListener.calledOnce).to.be.true; expect(lowListener.calledOnce).to.be.true; expect(highListener.calledOnce).to.be.false; shared.remove(mainListener) .remove(highListener) .remove(lowListener); expect(this.length()).to.equal(length); }); it('should remove emit low-priority item during emit', function () { const length = this.length(); const listener2 = sinon.spy(); const listener1 = sinon.spy(() => { shared.add(listener2, null, UPDATE_PRIORITY.LOW); }); shared.add(listener1, null, UPDATE_PRIORITY.NORMAL); shared.update(); expect(this.length()).to.equal(length + 2); expect(listener2.calledOnce).to.be.true; expect(listener1.calledOnce).to.be.true; shared.remove(listener1) .remove(listener2); expect(this.length()).to.equal(length); }); it('should remove itself on emit after adding new item', function () { const length = this.length(); const listener2 = sinon.spy(); const listener1 = sinon.spy(() => { shared.add(listener2, null, UPDATE_PRIORITY.LOW); shared.remove(listener1); // listener is removed right away expect(this.length()).to.equal(length + 1); }); shared.add(listener1, null, UPDATE_PRIORITY.NORMAL); shared.update(); expect(this.length()).to.equal(length + 1); expect(listener2.calledOnce).to.be.true; expect(listener1.calledOnce).to.be.true; shared.remove(listener2); expect(this.length()).to.equal(length); }); it.skip('should remove itself before, still calling new item', function () { const length = this.length(); const listener2 = sinon.spy(); const listener1 = sinon.spy(() => { shared.remove(listener1); shared.add(listener2, null, UPDATE_PRIORITY.LOW); // listener is removed right away expect(this.length()).to.equal(length + 1); }); shared.add(listener1, null, UPDATE_PRIORITY.NORMAL); shared.update(); expect(this.length()).to.equal(length + 1); expect(listener2.called).to.be.false; expect(listener1.calledOnce).to.be.true; shared.update(); expect(listener2.calledOnce).to.be.true; expect(listener1.calledOnce).to.be.true; shared.remove(listener2); expect(this.length()).to.equal(length); }); it.skip('should remove items before and after current priority', function () { const length = this.length(); const listener2 = sinon.spy(); const listener3 = sinon.spy(); const listener4 = sinon.spy(); shared.add(listener2, null, UPDATE_PRIORITY.HIGH); shared.add(listener3, null, UPDATE_PRIORITY.LOW); shared.add(listener4, null, UPDATE_PRIORITY.LOW); const listener1 = sinon.spy(() => { shared.remove(listener2) .remove(listener3); // listener is removed right away expect(this.length()).to.equal(length + 2); }); shared.add(listener1, null, UPDATE_PRIORITY.NORMAL); shared.update(); expect(this.length()).to.equal(length + 2); expect(listener2.calledOnce).to.be.true; expect(listener3.calledOnce).to.be.false; expect(listener4.calledOnce).to.be.true; expect(listener1.calledOnce).to.be.true; shared.update(); expect(listener2.calledOnce).to.be.true; expect(listener3.calledOnce).to.be.false; expect(listener4.calledTwice).to.be.true; expect(listener1.calledTwice).to.be.true; shared.remove(listener1) .remove(listener4); expect(this.length()).to.equal(length); }); it('should destroy on listener', function (done) { const ticker = new Ticker(); const listener2 = sinon.spy(); const listener = sinon.spy(() => { ticker.destroy(); setTimeout(() => { expect(listener2.called).to.be.false; expect(listener.calledOnce).to.be.true; done(); }, 0); }); ticker.add(listener); ticker.add(listener2, null, UPDATE_PRIORITY.LOW); ticker.start(); }); it('should Ticker call destroyed listener "next" pointer after destroy', function (done) { const ticker = new Ticker(); const listener1 = sinon.spy(); const listener2 = sinon.spy(() => { ticker.remove(listener2); }); const listener3 = sinon.spy(() => { ticker.stop(); expect(listener1.calledOnce).to.be.true; expect(listener2.calledOnce).to.be.true; expect(listener3.calledOnce).to.be.true; done(); }); ticker.add(listener1, null, UPDATE_PRIORITY.HIGH); ticker.add(listener2, null, UPDATE_PRIORITY.HIGH); ticker.add(listener3, null, UPDATE_PRIORITY.HIGH); ticker.start(); }); });
the_stack
import { ReactiveElement, PropertyValues, ReactiveControllerHost, } from '@lit/reactive-element'; import { IntersectionController, IntersectionControllerConfig, } from '../intersection_controller.js'; import {generateElementName, nextFrame} from './test-helpers.js'; import {assert} from '@esm-bundle/chai'; // Note, since tests are not built with production support, detect DEV_MODE // by checking if warning API is available. const DEV_MODE = !!ReactiveElement.enableWarning; if (DEV_MODE) { ReactiveElement.disableWarning?.('change-in-update'); } // TODO: disable these tests until can figure out issues with Sauce Safari // version. They do pass on latest Safari locally. //(window.IntersectionObserver ? suite : suite.skip) suite.skip('IntersectionController', () => { let container: HTMLElement; interface TestElement extends ReactiveElement { observer: IntersectionController; observerValue: unknown; resetObserverValue: () => void; changeDuringUpdate?: () => void; } const defineTestElement = ( getControllerConfig: ( host: ReactiveControllerHost ) => IntersectionControllerConfig ) => { class A extends ReactiveElement { observer: IntersectionController; observerValue: unknown; changeDuringUpdate?: () => void; constructor() { super(); const config = getControllerConfig(this); this.observer = new IntersectionController(this, config); } override update(props: PropertyValues) { super.update(props); if (this.changeDuringUpdate) { this.changeDuringUpdate(); } } override updated() { this.observerValue = this.observer.value; } resetObserverValue() { this.observer.value = this.observerValue = undefined; } } customElements.define(generateElementName(), A); return A; }; const renderTestElement = async (Ctor: typeof HTMLElement) => { const el = new Ctor() as TestElement; container.appendChild(el); await intersectionComplete(); return el; }; const getTestElement = async ( getControllerConfig: ( host: ReactiveControllerHost ) => IntersectionControllerConfig = () => ({}) ) => { const ctor = defineTestElement(getControllerConfig); const el = await renderTestElement(ctor); return el; }; const intersectionComplete = async () => { await nextFrame(); await nextFrame(); }; const intersectOut = (el: HTMLElement) => { el.style.position = 'absolute'; el.style.left = el.style.top = '-10000px'; }; const intersectIn = (el: HTMLElement) => { el.style.position = 'absolute'; el.style.left = el.style.top = '0px'; }; setup(() => { container = document.createElement('div'); document.body.appendChild(container); }); teardown(() => { if (container && container.parentNode) { container.parentNode.removeChild(container); } }); // Note, only the first test fails on chrome when using playwright. // Work around this by inserting 1 dummy test. test('dummy test: workaround for first test fails on chrome when using playwright', async () => { const el = await getTestElement(); assert.ok(el); }); test('can observe changes', async () => { const el = await getTestElement(); // Reports initial change by default assert.isTrue(el.observerValue); // Reports change when not intersecting el.resetObserverValue(); intersectOut(el); await intersectionComplete(); assert.isTrue(el.observerValue); // Reports change when intersecting el.resetObserverValue(); intersectIn(el); await intersectionComplete(); assert.isTrue(el.observerValue); }); test('can observe changes during update', async () => { const el = await getTestElement(); el.resetObserverValue(); el.changeDuringUpdate = () => intersectOut(el); el.requestUpdate(); await intersectionComplete(); assert.isTrue(el.observerValue); }); test('skips initial changes when `skipInitial` is `true`', async () => { const el = await getTestElement(() => ({ skipInitial: true, })); // Does not reports initial change when `skipInitial` is set assert.isUndefined(el.observerValue); // Reports subsequent attribute change when `skipInitial` is set el.resetObserverValue(); intersectOut(el); await intersectionComplete(); assert.isTrue(el.observerValue); // Reports another attribute change el.resetObserverValue(); el.requestUpdate(); await intersectionComplete(); assert.isUndefined(el.observerValue); intersectIn(el); await intersectionComplete(); assert.isTrue(el.observerValue); }); test('observation managed via connection', async () => { const el = await getTestElement(() => ({ skipInitial: true, })); assert.isUndefined(el.observerValue); intersectOut(el); // Does not report change after element removed. el.remove(); await intersectionComplete(); assert.isUndefined(el.observerValue); // Does not report change after element re-connected container.appendChild(el); await intersectionComplete(); assert.isUndefined(el.observerValue); // Reports change on mutation when element is connected el.resetObserverValue(); intersectIn(el); await intersectionComplete(); assert.isTrue(el.observerValue); }); test('can observe external element', async () => { const d = document.createElement('div'); container.appendChild(d); const el = await getTestElement(() => ({ target: d, skipInitial: true, })); assert.equal(el.observerValue, undefined); // Observe intersect out intersectOut(d); await intersectionComplete(); assert.isTrue(el.observerValue); el.resetObserverValue(); // Observe intersect in intersectIn(d); await intersectionComplete(); assert.isTrue(el.observerValue); }); test('can manage value via `callback`', async () => { const el = await getTestElement(() => ({ callback: (entries: IntersectionObserverEntry[]) => entries[0]?.isIntersecting, })); assert.isTrue(el.observerValue); el.resetObserverValue(); // Intersect out intersectOut(el); await intersectionComplete(); assert.isFalse(el.observerValue); // Intersect in el.resetObserverValue(); await intersectionComplete(); intersectIn(el); await intersectionComplete(); assert.isTrue(el.observerValue); }); test('can call `observe` to observe element', async () => { const el = await getTestElement(); el.resetObserverValue(); const d1 = document.createElement('div'); // Reports initial changes when observe called. el.observer.observe(d1); el.renderRoot.appendChild(d1); await intersectionComplete(); assert.isTrue(el.observerValue); // Reports change to observed target. el.resetObserverValue(); intersectOut(d1); await intersectionComplete(); assert.isTrue(el.observerValue); // Reports change to configured target. el.resetObserverValue(); intersectOut(el); await intersectionComplete(); assert.isTrue(el.observerValue); // Reset host intersectIn(el); await intersectionComplete(); // Can observe another target el.resetObserverValue(); const d2 = document.createElement('div'); el.observer.observe(d2); el.renderRoot.appendChild(d2); await intersectionComplete(); assert.isTrue(el.observerValue); // Reports change to new observed target. el.resetObserverValue(); intersectOut(d2); await intersectionComplete(); assert.isTrue(el.observerValue); // Reports change to configured target. el.resetObserverValue(); intersectOut(el); await intersectionComplete(); assert.isTrue(el.observerValue); // Reset host intersectIn(el); await intersectionComplete(); // Reports change to first observed target. el.resetObserverValue(); intersectIn(d1); await intersectionComplete(); assert.isTrue(el.observerValue); }); test('can specifying target as `null` and call `observe` to observe element', async () => { const el = await getTestElement(() => ({ target: null, })); el.resetObserverValue(); const d1 = document.createElement('div'); // Reports initial changes when observe called. el.observer.observe(d1); el.renderRoot.appendChild(d1); await intersectionComplete(); assert.isTrue(el.observerValue); // Reports change to observed target. el.resetObserverValue(); intersectOut(d1); await intersectionComplete(); assert.isTrue(el.observerValue); // Can observe another target el.resetObserverValue(); const d2 = document.createElement('div'); el.observer.observe(d2); el.renderRoot.appendChild(d2); await intersectionComplete(); assert.isTrue(el.observerValue); // Reports change to new observed target. el.resetObserverValue(); intersectOut(d2); await intersectionComplete(); assert.isTrue(el.observerValue); // Reports change to first observed target. el.resetObserverValue(); intersectIn(d1); await intersectionComplete(); assert.isTrue(el.observerValue); }); test('observed target respects `skipInitial`', async () => { const el = await getTestElement(() => ({ target: null, skipInitial: true, })); const d1 = document.createElement('div'); el.renderRoot.appendChild(d1); await intersectionComplete(); // Does not reports initial changes when observe called. el.observer.observe(d1); el.requestUpdate(); await intersectionComplete(); assert.isUndefined(el.observerValue); // Reports change to observed target. intersectOut(d1); await intersectionComplete(); assert.isTrue(el.observerValue); }); test('observed target not re-observed on connection', async () => { const el = await getTestElement(() => ({ target: null, skipInitial: true, })); const d1 = document.createElement('div'); el.renderRoot.appendChild(d1); el.observer.observe(d1); await intersectionComplete(); assert.isUndefined(el.observerValue); // Does not report change when disconnected. el.requestUpdate(); el.remove(); await intersectionComplete(); assert.isUndefined(el.observerValue); // Does not report change when re-connected container.appendChild(el); await intersectionComplete(); assert.isUndefined(el.observerValue); intersectOut(d1); await intersectionComplete(); assert.isUndefined(el.observerValue); // Can re-observe after connection, respecting `skipInitial` el.observer.observe(d1); await intersectionComplete(); assert.isUndefined(el.observerValue); intersectIn(d1); await intersectionComplete(); assert.isTrue(el.observerValue); }); });
the_stack
import {PlatformTest, ProviderScope} from "@tsed/common"; import {Injectable} from "@tsed/di"; import {ParamTypes, PathParams, QueryParams} from "@tsed/platform-params"; import {expect} from "chai"; import Sinon from "sinon"; import {buildPlatformParams, invokePlatformParams} from "../../../../../test/helper/buildPlatformParams"; const sandbox = Sinon.createSandbox(); describe("PlatformParams", () => { beforeEach(() => PlatformTest.create()); afterEach(() => PlatformTest.reset()); describe("getArg()", () => { it("should return REQUEST (node)", async () => { // GIVEN const {param, $ctx, h, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.NODE_REQUEST, dataPath: "$ctx.request.req" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.getReq()); }); it("should return REQUEST (framework)", async () => { // GIVEN const {param, $ctx, h, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.REQUEST, dataPath: "$ctx.request.request" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.getRequest()); }); it("should return REQUEST (platform)", async () => { // GIVEN const {param, h, $ctx, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.PLATFORM_REQUEST, dataPath: "$ctx.request" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.request); }); it("should return RESPONSE (node)", async () => { // GIVEN const {param, $ctx, h, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.NODE_RESPONSE, dataPath: "$ctx.response.res" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.getRes()); }); it("should return RESPONSE (framework)", async () => { // GIVEN const {param, $ctx, h, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.RESPONSE, dataPath: "$ctx.response.response" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.getResponse()); }); it("should return RESPONSE (platform)", async () => { // GIVEN const {param, $ctx, h, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.PLATFORM_RESPONSE, dataPath: "$ctx.response" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.response); }); it("should return NEXT", async () => { // GIVEN const {param, h, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.NEXT_FN, dataPath: "next" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.be.a("function"); }); it("should return ERR", async () => { // GIVEN const {param, h, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.ERR, dataPath: "err" }); h.err = new Error(); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq(h.err); }); it("should return $CTX", async () => { // GIVEN const {param, h, $ctx, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.$CTX, dataPath: "$ctx" }); // WHEN // @ts-ignore const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx); }); it("should return RESPONSE_DATA", async () => { // GIVEN const {param, h, $ctx, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.RESPONSE_DATA, dataPath: "$ctx.data" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.data); }); it("should return ENDPOINT_INFO", async () => { // GIVEN const {param, h, $ctx, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.ENDPOINT_INFO, dataPath: "$ctx.endpoint" }); // @ts-ignore $ctx.endpoint = "endpoint"; // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.endpoint); }); it("should return BODY", async () => { // GIVEN const {param, h, $ctx, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.BODY, dataPath: "$ctx.request.body" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.getRequest().body); }); it("should return PATH", async () => { // GIVEN const {param, h, $ctx, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.PATH, dataPath: "$ctx.request.params" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.getRequest().params); }); it("should return QUERY", async () => { // GIVEN const {param, h, $ctx, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.QUERY, dataPath: "$ctx.request.query" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.getRequest().query); }); it("should return HEADER", async () => { // GIVEN const {param, h, platformParams, ctx} = await buildPlatformParams({ sandbox, paramType: ParamTypes.HEADER, dataPath: "$ctx.request.headers" }); ctx.request.raw.headers["accept"] = "application/json"; ctx.request.raw.headers["content-type"] = "application/json"; // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq({ accept: "application/json", "content-type": "application/json" }); }); it("should return COOKIES", async () => { // GIVEN const {param, h, $ctx, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.COOKIES, dataPath: "$ctx.request.cookies" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.getRequest().cookies); }); it("should return SESSION", async () => { // GIVEN const {param, h, $ctx, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.SESSION, dataPath: "$ctx.request.session" }); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.request.session); }); it("should return LOCALS", async () => { // GIVEN const {param, h, $ctx, platformParams} = await buildPlatformParams({ sandbox, paramType: ParamTypes.LOCALS, dataPath: "$ctx.response.locals" }); h.err = new Error(); // WHEN const pipes = await platformParams.getPipes(param); const value = await platformParams.getArg(h, pipes, param); // THEN expect(value).to.deep.eq($ctx.getResponse().locals); }); }); describe("compileHandler()", () => { it("should build all params and return value (SINGLETON)", async () => { const platformParams = await invokePlatformParams(); @Injectable() class MyCtrTest { get(@PathParams() params: any, @QueryParams() query: any) { return {params, query}; } } const handler = await platformParams.compileHandler({ token: MyCtrTest, propertyKey: "get" }); const $ctx = PlatformTest.createRequestContext({ event: { request: { query: { test: "test" }, params: { s: "s" } } } }); const result = await handler({ $ctx }); expect(result).to.deep.eq({ query: { test: "test" }, params: { s: "s" } }); }); it("should build all params and return value (REQUEST)", async () => { const platformParams = await invokePlatformParams(); @Injectable({ scope: ProviderScope.REQUEST }) class MyCtrTest { get(@PathParams() params: any, @QueryParams() query: any) { return {params, query}; } } const $ctx = PlatformTest.createRequestContext({ event: { request: { query: { test: "test" }, params: { s: "s" } } } }); const handler = await platformParams.compileHandler({ token: MyCtrTest, propertyKey: "get" }); const result = await handler({ $ctx }); expect(result).to.deep.eq({ query: { test: "test" }, params: { s: "s" } }); }); it("should call without args", async () => { const platformParams = await invokePlatformParams(); @Injectable() class MyCtrTest { get() { return "test"; } } const $ctx = PlatformTest.createRequestContext({ event: { request: { query: { test: "test" }, params: { s: "s" } } } }); const handler = await platformParams.compileHandler({ token: MyCtrTest, propertyKey: "get" }); const result = await handler({ $ctx }); expect(result).to.deep.eq("test"); }); it("should with default args", async () => { const platformParams = await invokePlatformParams(); @Injectable() class MyCtrTest { get(query: any, params: any) { return {query, params}; } } const $ctx = PlatformTest.createRequestContext({ event: { request: { query: { test: "test" }, params: { s: "s" } } } }); const handler = await platformParams.compileHandler({ token: MyCtrTest, propertyKey: "get", async getCustomArgs(scope: any) { return [scope.$ctx.request.query, scope.$ctx.request.params]; } }); const result = await handler({ $ctx }); expect(result).to.deep.eq({ params: { s: "s" }, query: { test: "test" } }); }); }); });
the_stack
import { EventEmitter } from "@okikio/emitter"; import { Manager } from "@okikio/manager"; import { KeyframeParse, parseOffset } from "./builtin-effects"; import { ParseTransformableCSSProperties, ParseTransformableCSSKeyframes } from "./css-properties"; import { flatten, mapObject, convertToDash, isValid, omit } from "./utils"; import type { TypeEventInput, TypeListenerCallback } from "@okikio/emitter"; import type { TypeAnimationTarget, TypeAnimationOptionTypes, TypeCallbackArgs, TypeComputedAnimationOptions, IAnimationOptions, TypeComputedOptions, TypeKeyFrameOptionsType, TypeCSSLikeKeyframe, ICSSComputedTransformableProperties, TypeAnimationEvents, TypePlayStates } from "./types"; /* DOM */ export const getElements = (selector: string | Node): Node[] => { return typeof selector === "string" ? Array.from(document.querySelectorAll(selector as string)) : [selector]; }; export const getTargets = (targets: TypeAnimationTarget): Node[] => { if (Array.isArray(targets)) { return flatten((targets as TypeAnimationTarget[]).map(getTargets)); } if (typeof targets == "string" || targets instanceof Node) return getElements(targets); if (targets instanceof NodeList || targets instanceof HTMLCollection) return Array.from(targets); return []; }; /* VALUES */ export const computeOption = (value: TypeAnimationOptionTypes, args: TypeCallbackArgs, context: Animate): TypeComputedAnimationOptions => { if (typeof value === "function") { return value.apply(context, args); } else return value; }; export const mapAnimationOptions = (options: IAnimationOptions, args: TypeCallbackArgs, animate: Animate): TypeComputedOptions => { return mapObject(options, (value) => computeOption(value, args, animate)); }; /** * From: [https://easings.net] * * Read More about easings on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/easing) * * ```ts * { * "in": "ease-in", * "out": "ease-out", * "in-out": "ease-in-out", * * // Sine * "in-sine": "cubic-bezier(0.47, 0, 0.745, 0.715)", * "out-sine": "cubic-bezier(0.39, 0.575, 0.565, 1)", * "in-out-sine": "cubic-bezier(0.445, 0.05, 0.55, 0.95)", * * // Quad * "in-quad": "cubic-bezier(0.55, 0.085, 0.68, 0.53)", * "out-quad": "cubic-bezier(0.25, 0.46, 0.45, 0.94)", * "in-out-quad": "cubic-bezier(0.455, 0.03, 0.515, 0.955)", * * // Cubic * "in-cubic": "cubic-bezier(0.55, 0.055, 0.675, 0.19)", * "out-cubic": "cubic-bezier(0.215, 0.61, 0.355, 1)", * "in-out-cubic": "cubic-bezier(0.645, 0.045, 0.355, 1)", * * // Quart * "in-quart": "cubic-bezier(0.895, 0.03, 0.685, 0.22)", * "out-quart": "cubic-bezier(0.165, 0.84, 0.44, 1)", * "in-out-quart": "cubic-bezier(0.77, 0, 0.175, 1)", * * // Quint * "in-quint": "cubic-bezier(0.755, 0.05, 0.855, 0.06)", * "out-quint": "cubic-bezier(0.23, 1, 0.32, 1)", * "in-out-quint": "cubic-bezier(0.86, 0, 0.07, 1)", * * // Expo * "in-expo": "cubic-bezier(0.95, 0.05, 0.795, 0.035)", * "out-expo": "cubic-bezier(0.19, 1, 0.22, 1)", * "in-out-expo": "cubic-bezier(1, 0, 0, 1)", * * // Circ * "in-circ": "cubic-bezier(0.6, 0.04, 0.98, 0.335)", * "out-circ": "cubic-bezier(0.075, 0.82, 0.165, 1)", * "in-out-circ": "cubic-bezier(0.785, 0.135, 0.15, 0.86)", * * // Back * "in-back": "cubic-bezier(0.6, -0.28, 0.735, 0.045)", * "out-back": "cubic-bezier(0.175, 0.885, 0.32, 1.275)", * "in-out-back": "cubic-bezier(0.68, -0.55, 0.265, 1.55)" * } * ``` */ export const EASINGS = { "in": "ease-in", "out": "ease-out", "in-out": "ease-in-out", // Sine "in-sine": "cubic-bezier(0.47, 0, 0.745, 0.715)", "out-sine": "cubic-bezier(0.39, 0.575, 0.565, 1)", "in-out-sine": "cubic-bezier(0.445, 0.05, 0.55, 0.95)", // Quad "in-quad": "cubic-bezier(0.55, 0.085, 0.68, 0.53)", "out-quad": "cubic-bezier(0.25, 0.46, 0.45, 0.94)", "in-out-quad": "cubic-bezier(0.455, 0.03, 0.515, 0.955)", // Cubic "in-cubic": "cubic-bezier(0.55, 0.055, 0.675, 0.19)", "out-cubic": "cubic-bezier(0.215, 0.61, 0.355, 1)", "in-out-cubic": "cubic-bezier(0.645, 0.045, 0.355, 1)", // Quart "in-quart": "cubic-bezier(0.895, 0.03, 0.685, 0.22)", "out-quart": "cubic-bezier(0.165, 0.84, 0.44, 1)", "in-out-quart": "cubic-bezier(0.77, 0, 0.175, 1)", // Quint "in-quint": "cubic-bezier(0.755, 0.05, 0.855, 0.06)", "out-quint": "cubic-bezier(0.23, 1, 0.32, 1)", "in-out-quint": "cubic-bezier(0.86, 0, 0.07, 1)", // Expo "in-expo": "cubic-bezier(0.95, 0.05, 0.795, 0.035)", "out-expo": "cubic-bezier(0.19, 1, 0.22, 1)", "in-out-expo": "cubic-bezier(1, 0, 0, 1)", // Circ "in-circ": "cubic-bezier(0.6, 0.04, 0.98, 0.335)", "out-circ": "cubic-bezier(0.075, 0.82, 0.165, 1)", "in-out-circ": "cubic-bezier(0.785, 0.135, 0.15, 0.86)", // Back "in-back": "cubic-bezier(0.6, -0.28, 0.735, 0.045)", "out-back": "cubic-bezier(0.175, 0.885, 0.32, 1.275)", "in-out-back": "cubic-bezier(0.68, -0.55, 0.265, 1.55)" }; /** * The keys of {@link EASINGS} * * @remark * "in", "out", "in-out", "in-sine", "out-sine", "in-out-sine", "in-quad", "out-quad", "in-out-quad", "in-cubic", "out-cubic", "in-out-cubic", "in-quart", "out-quart", "in-out-quart", "in-quint", "out-quint", "in-out-quint", "in-expo", "out-expo", "in-out-expo", "in-circ", "out-circ", "in-out-circ", "in-back", "out-back", "in-out-back" */ export const EasingKeys = Object.keys(EASINGS); /** * Converts users input into a usable easing function string * * @param ease - easing functions; {@link EasingKeys}, cubic-bezier, steps, linear, etc... * @returns an easing function that `KeyframeEffect` can accept */ export const GetEase = (ease: keyof typeof EASINGS | string = "ease"): string => { // Convert camelCase strings into dashed strings, then Remove the "ease-" keyword let search = convertToDash(ease).replace(/^ease-/, ""); return EasingKeys.includes(search) ? EASINGS[search] : ease; }; /** * The default options for every Animate instance * * ```ts * { * keyframes: [], * * loop: 1, * delay: 0, * speed: 1, * endDelay: 0, * easing: "ease", * autoplay: true, * duration: 1000, * fillMode: "none", * direction: "normal", * padEndDelay: false, * timeline: document.timeline, * extend: {} * } * ``` */ export const DefaultAnimationOptions: IAnimationOptions = { keyframes: [], offset: [], loop: 1, delay: 0, speed: 1, endDelay: 0, easing: "ease", timelineOffset: 0, autoplay: true, duration: 1000, fillMode: "none", direction: "normal", padEndDelay: false, timeline: document.timeline, extend: {} }; /** Parses the different ways to define options, and returns a merged options object */ export const parseOptions = (options: IAnimationOptions): IAnimationOptions => { let { options: animation, ...rest } = options; let oldOptions = animation instanceof Animate ? animation.options : (Array.isArray(animation) ? animation?.[0]?.options : animation); return Object.assign({}, oldOptions, rest); } export const FUNCTION_SUPPORTED_TIMING_KEYS = ["easing", "loop", "endDelay", "duration", "speed", "delay", "timelineOffset", "direction", "extend", "fillMode", "offset"]; export const NOT_FUNCTION_SUPPORTED_TIMING_KEYS = ["keyframes", "padEndDelay", "onfinish", "oncancel", "autoplay", "target", "targets", "timeline"]; export const ALL_TIMING_KEYS = [...FUNCTION_SUPPORTED_TIMING_KEYS, ...NOT_FUNCTION_SUPPORTED_TIMING_KEYS]; /** * An animation library for the modern web, which. Inspired by animate plus, and animejs, [@okikio/animate](https://www.skypack.dev/view/@okikio/animate) is a Javascript animation library focused on performance and ease of use. * * You can check it out here: <https://codepen.io/okikio/pen/qBbdGaW?editors=0011> */ export class Animate { /** * Stores the options for the current animation * * Read more about the {@link DefaultAnimationOptions} */ public options: IAnimationOptions = {}; /** * The properties to animate */ public properties: object = {}; /** * The total duration of all Animation's */ public totalDuration: number = -Infinity; /** * The smallest delay out of all Animation's */ public minDelay: number = Infinity; /** * The smallest speed out of all Animation's */ public maxSpeed: number = Infinity; /** * The Element the mainAnimation runs on */ public mainElement: HTMLElement; /** * Stores an animation that runs on the total duration of all the `Animation` instances, and as such it's the main Animation. */ public mainAnimation: Animation; /** * The Keyframe Effect for the mainAnimation */ public mainkeyframeEffect: KeyframeEffect; /** * An event emitter */ public emitter: EventEmitter = new EventEmitter(); /** * Returns a promise that is fulfilled when the mainAnimation is finished */ public promise: Promise<Animate[]>; /** * The list of Elements to Animate */ public targets: Manager<number, Node> = new Manager(); /** * The indexs of target Elements in Animate */ public targetIndexes: WeakMap<Node, number> = new WeakMap(); /** * A WeakMap of KeyFrameEffects */ public keyframeEffects: WeakMap<HTMLElement, KeyframeEffect> = new WeakMap(); /** * The options for individual animations * * A WeakMap that stores all the fully calculated options for individual Animation instances. * * _**Note**: the computedOptions are changed to their proper Animation instance options, so, some of the names are different, and options that can't be computed are not present. E.g. fillMode in the animation options is now just fill in the computedOptions.*_ * * _**Note**: keyframes are not included, both the array form and the object form; the options, speed, extend, padEndDelay, and autoplay animation options are not included_ */ public computedOptions: WeakMap<HTMLElement, TypeComputedOptions> = new WeakMap(); /** * A WeakMap of Animations */ public animations: WeakMap<KeyframeEffect, Animation> = new WeakMap(); /** * The keyframes for individual animations * * A WeakMap that stores all the fully calculated keyframes for individual Animation instances. * * _**Note**: the computedKeyframes are changed to their proper Animation instance options, so, some of the names are different, and options that can't be computed are not present. E.g. translateX, skew, etc..., they've all been turned into the transform property.*_ */ public computedKeyframes: WeakMap<HTMLElement, TypeKeyFrameOptionsType> = new WeakMap(); constructor(options: IAnimationOptions) { this.loop = this.loop.bind(this); this.onVisibilityChange = this.onVisibilityChange.bind(this); this.on("error", console.error); this.updateOptions(options); if (this.mainAnimation) { this.visibilityPlayState = this.getPlayState(); if (Animate.pauseOnPageHidden) { document.addEventListener('visibilitychange', this.onVisibilityChange, false); } } this.newPromise(); } /** * Tells all animate instances to pause when the page is hidden */ static pauseOnPageHidden: Boolean = true; /** * Stores all currently running instances of the Animate Class that are actively using requestAnimationFrame to check progress, * it's meant to ensure you don't have multiple instances of the Animate Class creating multiple requestAnimationFrames at the same time * this can cause performance hiccups */ static RUNNING: Set<Animate> = new Set(); /** * Stores request frame calls */ static animationFrame: number; /** * Calls requestAnimationFrame for each running instance of Animate */ static requestFrame() { // Cancel any lingering requestAnimationFrames from preious run of the requestFrame method Animate.cancelFrame(); Animate.RUNNING.forEach((inst) => { if (inst.emitter.getEvent("update").length <= 0) { inst.stopLoop(); } else { inst.loop(); } }); // If there are no more Animate instances in the RUNNING WeakSet, // cancel the requestAnimationFrame if (Animate.RUNNING.size > 0) { Animate.animationFrame = window.requestAnimationFrame(Animate.requestFrame); } else Animate.cancelFrame(); } /** * Cancels animationFrame */ static cancelFrame() { window.cancelAnimationFrame(Animate.animationFrame); Animate.animationFrame = null; } /** * Represents an Animation Frame Loop */ public loop(): void { this.emit("update", this.getProgress(), this); } /** * Cancels animation frame */ public stopLoop() { Animate.RUNNING.delete(this); } /** * Store the last remebered playstate before page was hidden */ protected visibilityPlayState: TypePlayStates; /** * document `visibilitychange` event handler */ protected onVisibilityChange() { if (document.hidden) { this.visibilityPlayState = this.getPlayState(); if (this.is("running")) { this.loop(); this.pause(); } } else { if (this.visibilityPlayState == "running" && this.is("paused")) this.play(); } } /** * Returns a new Promise that is resolved when the animation finishes */ public newPromise(): Promise<Animate[]> { this.promise = new Promise((resolve, reject) => { /* Note that the `this` keyword is in an Array when it is resolved, this is due to Promises not wanting to resolve references, so, you can't resolve `this` directly, so, I chose to resolve `this` in an Array Note: the `resolve` method by default will only run once so to avoid */ this.emitter?.once?.("finish", () => resolve([this])); this.emitter?.once?.("error", err => reject(err)); }); return this.promise; } /** * Fulfills the `this.promise` Promise */ public then( onFulfilled?: (value?: any) => any, onRejected?: (reason?: any) => any ): Animate { onFulfilled = onFulfilled?.bind(this); onRejected = onRejected?.bind(this); this.promise?.then?.(onFulfilled, onRejected); return this; } /** * Catches error that occur in the `this.promise` Promise */ public catch(onRejected: (reason?: any) => any): Animate { onRejected = onRejected?.bind(this); this.promise?.catch?.(onRejected); return this; } /** * If you don't care if the `this.promise` Promise has either been rejected or resolved */ public finally(onFinally: () => any): Animate { onFinally = onFinally?.bind(this); this.promise?.finally?.(onFinally); return this; } /** * Calls a method that affects all animations **excluding** the mainAnimation; the method only allows the animation parameter */ public allAnimations(method: (animation?: Animation, target?: HTMLElement) => void) { this.targets.forEach((target: HTMLElement) => { let keyframeEffect = this.keyframeEffects.get(target); let animation = this.animations.get(keyframeEffect); return method(animation, target); }); return this; } /** * Calls a method that affects all animations **including** the mainAnimation; the method only allows the animation parameter */ public all(method: (animation?: Animation, target?: HTMLElement) => void) { this.mainAnimation && method(this.mainAnimation, this.mainElement); this.allAnimations(method); return this; } /** * Register the begin event */ protected beginEvent() { if (this.getProgress() == 0) this.emit("begin", this); } /** * Play Animation */ public play(): Animate { let playstate = this.getPlayState(); this.beginEvent(); this.all(anim => anim.play()); this.emit("play", playstate, this); if (!this.is(playstate)) this.emit("playstate-change", playstate, this); this.loop(); // Because the Web Animation API doesn't require requestAnimationFrame for animations, // we only run the requestAnimationFrame when there is a "update" event listener Animate.RUNNING.add(this); Animate.requestFrame(); return this; } /** * Pause Animation */ public pause(): Animate { let playstate = this.getPlayState(); this.all(anim => anim.pause()); this.emit("pause", playstate, this); if (!this.is(playstate)) this.emit("playstate-change", playstate, this); this.stopLoop(); return this; } /** * Reverse Animation */ public reverse() { this.all(anim => anim.reverse()); return this; } /** * Reset all Animations */ public reset() { this.setProgress(0); if (this.options.autoplay) this.play(); else this.pause(); return this; } /** * Cancels all Animations */ public cancel() { this.all(anim => anim.cancel()); return this; } /** * Force complete all Animations */ public finish() { this.all(anim => anim.finish()); return this; } /** * Cancels & Clears all Animations */ public stop() { this.cancel(); this.stopLoop(); document.removeEventListener('visibilitychange', this.onVisibilityChange, false); this.targets.forEach((target: HTMLElement) => this.removeTarget(target)); this.emit("stop"); this.emitter.clear(); this.mainkeyframeEffect = null; this.mainAnimation = null; this.mainElement?.remove?.(); this.mainElement = null; this.promise = null; this.computedOptions = null; this.animations = null; this.keyframeEffects = null; this.emitter = null; this.targets = null; this.options = null; this.properties = null; } /** * Get a specific Animation from an Animate instance */ public getAnimation(target: HTMLElement) { let keyframeEffect = this.keyframeEffects.get(target); return this.animations.get(keyframeEffect); } /** * Returns the timings of an Animation, given a target * E.g. { duration, endDelay, delay, iterations, iterationStart, direction, easing, fill, etc... } */ public getTiming(target: HTMLElement): TypeComputedAnimationOptions { let keyframeOptions = this.computedOptions.get(target) ?? {}; let timings = this.keyframeEffects.get(target).getTiming?.() ?? {}; return { ...keyframeOptions, ...timings }; } /** * Returns the current time of the Main Animation */ public getCurrentTime(): number { return this.mainAnimation.currentTime; } /** * Returns the Animation progress as a fraction of the current time / duration * 100 */ public getProgress() { return (this.getCurrentTime() / this.totalDuration) * 100; } /** * Return the playback speed of the animation */ public getSpeed(): number { return this.mainAnimation.playbackRate; } /** * Returns the current playing state */ public getPlayState(): TypePlayStates { return this.mainAnimation.playState; } /** * Returns a boolean determining if the `animate` instances playstate is equal to the `playstate` parameter. */ public is(playstate: TypePlayStates) { return this.getPlayState() == playstate; } /** * Set the current time of the Main Animation */ public setCurrentTime(time: number): Animate { this.all(anim => (anim.currentTime = time)); this.emit("update", this.getProgress()); return this; } /** * Set the Animation progress as a value from 0 to 100 */ public setProgress(percent: number): Animate { let time = (percent / 100) * this.totalDuration; this.setCurrentTime(time); return this; } /** * Set the playback speed of an Animation */ public setSpeed(speed: number = 1): Animate { this.maxSpeed = speed; this.all(anim => { if (anim.updatePlaybackRate) anim.updatePlaybackRate(speed); else anim.playbackRate = speed; }); return this; } /** * Returns an array of computed options */ protected createArrayOfComputedOptions(optionsFromParam: IAnimationOptions, len: number) { let result: TypeComputedAnimationOptions = []; this.targets.forEach((target: HTMLElement, i) => { // Basically if there is already a computedOption for the target element use it, but don't ovveride any new options let oldComputedOptions: IAnimationOptions = this.computedOptions.get(target) ?? {}; let getOption = (key: string) => { let computedKey = key; if (key == "loop") computedKey = "iterations"; if (key == "fillMode") computedKey = "fill"; return optionsFromParam[key] ?? oldComputedOptions[computedKey] ?? this.options[key] ?? DefaultAnimationOptions[key]; }; let animationOptions = Object.assign({ easing: getOption("easing"), iterations: getOption("loop"), direction: getOption("direction"), endDelay: getOption("endDelay"), duration: getOption("duration"), speed: getOption("speed"), delay: getOption("delay"), timelineOffset: getOption("timelineOffset"), keyframes: getOption("keyframes"), }, getOption("extend") ?? {}); // let oldComputedOptions = this.computedOptions.get(target) // Allows the use of functions as the values, for both the keyframes and the animation object // It adds the capability of advanced stagger animation, similar to the animejs stagger functions let computedOptions = mapAnimationOptions(animationOptions as IAnimationOptions, [i, len, target], this); if (typeof computedOptions.easing == "string") computedOptions.easing = GetEase(computedOptions.easing); if (computedOptions.iterations === true) computedOptions.iterations = Infinity; computedOptions.fill = getOption("fillMode"); // Add timelineOffset to delay, this is future proofing; // if you want to create a custom timeline similar to animejs this will help you // I don't intend to make a timeline function for this project let { timelineOffset, speed, endDelay, delay, duration, iterations, ...remainingComputedOptions } = computedOptions; iterations = Number(iterations); duration = Number(duration); endDelay = Number(endDelay); speed = Number(speed); delay = Number(delay) + Number(timelineOffset); let tempDurations = delay + (duration * iterations) + endDelay; // Set the totalDuration to be the Animation with the largest totalDuration if (this.totalDuration < tempDurations) this.totalDuration = tempDurations; result[i] = { ...remainingComputedOptions, speed, tempDurations, endDelay, delay, duration, iterations, }; if (this.minDelay > delay) this.minDelay = delay; if (this.maxSpeed > speed) this.maxSpeed = speed; }); return result; } /** * Creates animations out of an array of computed options */ protected createAnimations(param: { arrOfComputedOptions: any; padEndDelay: any; oldCSSProperties: any; onfinish: any; oncancel: any; timeline?: any; }, len: number) { let { arrOfComputedOptions, padEndDelay, oldCSSProperties, onfinish, oncancel, timeline } = param; this.targets.forEach((target: HTMLElement, i) => { let { speed, keyframes, tempDurations, ...computedOptions } = arrOfComputedOptions[i]; // You cannot use the `padEndDelay` option and set a value for `endDelay`, the `endDelay` value will // replace the padded endDelay // This ensures all `animations` match up to the total duration, and don't finish too early, // if animations finish too early, when the `.play()` method is called, some animations // that are finished will restart, while the rest will continue playing. // This is mostly for progress control, but depending on your usage may truly benefit you if (padEndDelay && computedOptions.endDelay == 0 && Math.abs(computedOptions.iterations) != Math.abs(Infinity)) { computedOptions.endDelay = this.totalDuration - tempDurations; } let computedKeyframes: Keyframe[] | PropertyIndexedKeyframes; let animationKeyframe: TypeKeyFrameOptionsType; // Accept keyframes as a keyframes Object, or a method, // if there are no animations in the keyframes array, // uses css properties from the options object let arrKeyframes = keyframes as (Keyframe[] | TypeCSSLikeKeyframe); if (typeof arrKeyframes == "object") arrKeyframes = KeyframeParse(arrKeyframes); // If `computedKeyframes` have been previously computed for this target element replace // the old uncomputed CSS properties with it, otherwise, use the uncomputed property let oldComputedKeyframe = this.computedKeyframes.get(target) ?? {}; let fullProperties = Object.assign({}, oldCSSProperties, oldComputedKeyframe); // Replace old CSS properties with new CSS properties if there is a new value for the CSS property // As in the new CSS property is not null or null let properties = mapObject(fullProperties, (value, key) => (this.properties[key] ?? value)); // Prefer arrays of keyframes over pure CSS Properties animationKeyframe = isValid(arrKeyframes) ? arrKeyframes : properties as PropertyIndexedKeyframes; if (!Array.isArray(animationKeyframe)) { // Remove `keyframes` animation option, it's not a valid CSS property let remaining: IAnimationOptions = omit(["keyframes"], animationKeyframe); let { offset, ...CSSProperties } = mapAnimationOptions(remaining, [i, len, target], this); // transform, is often used so, to make them easier to use we parse them for strings, number, and/or arrays of both; // for transform we parse the translate, skew, scale, and perspective functions (including all their varients) as CSS properties; // it then turns these properties into valid `PropertyIndexedKeyframes` // Read the documentation for `ParseTransformableCSSProperties` CSSProperties = ParseTransformableCSSProperties(CSSProperties as ICSSComputedTransformableProperties); let _offset = offset as (string | number)[]; computedKeyframes = Object.assign({}, CSSProperties, isValid(_offset) ? { offset: _offset.map(parseOffset) } : null ) as PropertyIndexedKeyframes; } else { computedKeyframes = animationKeyframe.map((keyframe: Keyframe) => { // Remove `speed` & `loop`, they are not valid CSS properties let { easing, offset, ...remaining } = omit(["speed", "loop"], keyframe); return Object.assign({}, remaining, typeof easing == "string" ? { easing: GetEase(easing) } : null, typeof offset == "string" || typeof offset == "number" ? { offset: parseOffset(offset) } : null ); }); // Transform transformable CSS properties in each keyframe of the keyframe array computedKeyframes = ParseTransformableCSSKeyframes(computedKeyframes) as Keyframe[]; } let animation: Animation, keyFrameEffect: KeyframeEffect; if (this.keyframeEffects.has(target)) { // Update the animation, if the target already is already being animated keyFrameEffect = this.keyframeEffects.get(target); animation = this.animations.get(keyFrameEffect); keyFrameEffect?.setKeyframes?.(computedKeyframes); keyFrameEffect?.updateTiming?.(computedOptions as KeyframeAnimationOptions); } else { // Create animation and add it to the Animations Set keyFrameEffect = new KeyframeEffect(target, computedKeyframes, computedOptions as KeyframeAnimationOptions); animation = new Animation(keyFrameEffect, timeline); this.keyframeEffects.set(target, keyFrameEffect); this.animations.set(keyFrameEffect, animation); } animation.playbackRate = speed; // Support for on finish animation.onfinish = () => { typeof onfinish == "function" && onfinish.call(this, target, i, len, animation); }; // // Support for on cancel animation.oncancel = () => { typeof oncancel == "function" && oncancel.call(this, target, i, len, animation); }; // Set the calculated options & keyframes for each individual animation this.computedOptions.set(target, computedOptions); this.computedKeyframes.set(target, computedKeyframes); }); } /** * Update the options for all targets * * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `updateOptions` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_ * * @beta */ public updateOptions(options: IAnimationOptions = {}) { try { let optionsFromParam = parseOptions(options); this.options = Object.assign({}, DefaultAnimationOptions, this.options, optionsFromParam); // This removes all none CSS properties from `properties` let { // These values cannot be functions padEndDelay, autoplay, target, targets, timeline, onfinish, oncancel, /** * Theses are the CSS properties to be animated as Keyframes */ ...oldCSSProperties } = omit(FUNCTION_SUPPORTED_TIMING_KEYS, this.options); // This removes all none CSS properties from `optionsFromParam` this.properties = omit(ALL_TIMING_KEYS, optionsFromParam); // Avoid duplicate elements let oldTargets = this.targets.values(); let targetSet = [...new Set([...oldTargets, ...getTargets(targets), ...getTargets(target)])]; this.targets.clear(); targetSet.forEach((value, i) => { this.targets.set(i, value); this.targetIndexes.set(value, i); }); let len = this.targets.size; let arrOfComputedOptions = this.createArrayOfComputedOptions(optionsFromParam, len); this.createAnimations({ arrOfComputedOptions, padEndDelay, oldCSSProperties, onfinish, oncancel, timeline }, len); // If the total number of targets is zero or less, it means there not values in `arrOfComputedOptions` // So, set the values for `totalDuration`, `minDelay`, and `maxSpeed` to the options directly // This is for anyone who wants to build a `timeline` in the future if (len <= 0) { if (this.maxSpeed == Infinity) this.maxSpeed = Number(this.options.speed); if (this.minDelay == Infinity) this.minDelay = Number(this.options.delay) + Number(this.options.timelineOffset); if (this.totalDuration == -Infinity) this.totalDuration = Number(this.options.duration); } if (!this.mainAnimation) { this.mainkeyframeEffect = new KeyframeEffect(this.mainElement, null, { duration: this.totalDuration }); this.mainAnimation = new Animation(this.mainkeyframeEffect, timeline); } else { this.mainkeyframeEffect?.updateTiming?.({ duration: this.totalDuration }); if (!this.mainkeyframeEffect.setKeyframes || !this.mainkeyframeEffect.updateTiming) console.warn("@okikio/animate - `KeyframeEffect.setKeyframes` and/or `KeyframeEffect.updateTiming` are not supported in this browser."); } this.mainAnimation.playbackRate = this.maxSpeed; this.mainAnimation.onfinish = () => { if (this.mainAnimation) { let playstate = this.getPlayState(); if (!this.is(playstate)) this.emit("playstate-change", playstate, this); // Ensure the progress reaches 100% this.loop(); this.stopLoop(); } this.emit("finish", this); }; this.mainAnimation.oncancel = () => { if (this.mainAnimation) { let playstate = this.getPlayState(); if (!this.is(playstate)) this.emit("playstate-change", playstate, this); // Ensure the progress is accurate this.loop(); this.stopLoop(); } this.emit("cancel", this); }; if (autoplay) { // By the time events are registered the animation would have started and there wouldn't have be a `begin` event listener to actually emit // So, this defers the emitting for a 0ms time allowing the rest of the js to run, the `begin` event to be registered thus // the `begin` event can be emitter let timer: number | void = window.setTimeout(() => { this.emit("begin", this); timer = window.clearTimeout(timer as number); }, 0); this.play(); } else this.pause(); } catch (err) { this.emit("error", err); } } /** * Adds a target to the Animate instance, and update the animation options with the change * * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `add` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_ * * @beta */ public add(target: HTMLElement) { let progress = this.getProgress(); let running = this.is("running"); let paused = this.is("paused"); this.updateOptions({ target }); this.setProgress(progress); if (running) this.play(); else if (paused) this.pause(); } /** * Removes a target from an Animate instance * * _**Note**: it doesn't update the current running options, you need to use the `Animate.prototype.remove(...)` method if you want to also update the running options_ */ public removeTarget(target: HTMLElement) { let keyframeEffect = this.keyframeEffects.get(target); this.animations.delete(keyframeEffect); keyframeEffect = null; this.computedKeyframes.delete(target); this.computedOptions.delete(target); this.keyframeEffects.delete(target); let index = this.targetIndexes.get(target); this.targets.delete(index); this.targetIndexes.delete(target); } /** * Removes a target from an Animate instance, and update the animation options with the change * * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `remove` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_ * * @beta */ public remove(target: HTMLElement) { this.removeTarget(target); let targetSet = new Set([].concat(this.targets.values())); this.options.target = [...targetSet]; this.options.targets = []; targetSet.clear(); targetSet = null; let progress = this.getProgress(); let running = this.is("running"); let paused = this.is("paused"); this.updateOptions(); if (running) this.play(); else if (paused) this.pause(); this.setProgress(progress); } /** * Adds a listener for a given event */ public on(events: TypeAnimationEvents[] | TypeAnimationEvents | TypeEventInput, callback?: TypeListenerCallback | object, scope?: object): Animate { this.emitter?.on?.(events, callback, scope ?? this); // Because the Web Animation API doesn't require requestAnimationFrame for animations, // we only run the requestAnimationFrame when there is a "update" event listener if (this.emitter.getEvent("update").length > 0) { Animate.RUNNING.add(this); if (Animate.animationFrame == null) Animate.requestFrame(); } return this; } /** * Removes a listener from an event */ public off(events: TypeAnimationEvents[] | TypeAnimationEvents | TypeEventInput, callback?: TypeListenerCallback | object, scope?: object): Animate { this.emitter?.off?.(events, callback, scope ?? this); return this; } /** * Call all listeners within an event */ public emit(events: TypeAnimationEvents[] | TypeAnimationEvents | string | any[], ...args: any): Animate { this.emitter?.emit?.(events, ...args); return this; } /** Returns the Animate options, as JSON */ public toJSON(): IAnimationOptions { return this.options; } /** * The Symbol.toStringTag well-known symbol is a string valued property that is used * in the creation of the default string description of an object. * It is accessed internally by the Object.prototype.toString() method. */ get [Symbol.toStringTag]() { return `Animate`; } } /** * Creates a new Animate instance * * @remark * `@okikio/animate` create animations by creating instances of `Animate`, a class that acts as a wrapper around the Web Animation API. To create new instances of the `Animate` class, you can either import the `Animate` class and do this, `new Animate({ ... })` or import the `animate` (lowercase) method and do this, `animate({ ... })`. The `animate` method creates new instances of the `Animate` class and passes the options it recieves as arguments to the `Animate` class. * * The `Animate` class recieves a set of targets to animate, it then creates a list of Web Animation API `Animation` instances, along side a main animation, which is small `Animation` instance that is set to animate the opacity of a non visible element, the `Animate` class then plays each `Animation` instances keyframes including the main animation. * The main animation is there to ensure accuracy in different browser vendor implementation of the Web Animation API. The main animation is stored in `Animate.prototype.mainAnimation: Animation`, the other `Animation` instances are stored in a `Manager` (from [@okikio/manager](https://www.npmjs.com/package/@okikio/manager)) `Animate.prototype.animations: Manager<HTMLElement, Animation>`. * @example * ```ts * import animate from "@okikio/animate"; * * // Do note, on the web you need to do this, if you installed it via the script tag: * // const { animate } = window.animate; * * (async () => { * let [options] = await animate({ * target: ".div", * // NOTE: If you turn this on you have to comment out the transform property. The keyframes property is a different format for animation you cannot you both styles of formatting in the same animation * // keyframes: [ * // { transform: "translateX(0px)" }, * // { transform: "translateX(300px)" } * // ], * transform: ["translateX(0px)", "translateX(300px)"], * easing: "out", * duration(i) { * return (i + 1) * 500; * }, * loop: 1, * speed: 2, * fillMode: "both", * direction: "normal", * autoplay: true, * delay(i) { * return (i + 1) * 100; * }, * endDelay(i) { * return (i + 1) * 100; * }, * }); * * animate({ * options, * transform: ["translateX(300px)", "translateX(0px)"], * }); * })(); * * // or you can use the .then() method * animate({ * target: ".div", * // NOTE: If you turn this on you have to comment out the transform property. The keyframes property is a different format for animation you cannot you both styles of formatting in the same animation * // keyframes: [ * // { transform: "translateX(0px)" }, * // { transform: "translateX(300px)" } * // ], * transform: ["translateX(0px)", "translateX(300px)"], * easing: "out", * duration(i) { * return (i + 1) * 500; * }, * loop: 1, * speed: 2, * fillMode: "both", * direction: "normal", * delay(i) { * return (i + 1) * 100; * }, * autoplay: true, * endDelay(i) { * return (i + 1) * 100; * } * }).then((options) => { * animate({ * options, * transform: ["translateX(300px)", "translateX(0px)"] * }); * }); * ``` * * [Preview this example &#8594;](https://codepen.io/okikio/pen/mdPwNbJ?editors=0010) * * @packageDocumentation */ export const animate = (options: IAnimationOptions = {}): Animate => { return new Animate(options); }; export default animate;
the_stack
import { KVStore, formatInt, getFirstPrefix, getLastPrefix, NotFoundError } from '@liskhq/lisk-db'; import { codec } from '@liskhq/lisk-codec'; import { getAddressFromPublicKey, hash } from '@liskhq/lisk-cryptography'; import { RawBlock, StateDiff } from '../types'; import { StateStore } from '../state_store'; import { DB_KEY_BLOCKS_ID, DB_KEY_BLOCKS_HEIGHT, DB_KEY_TRANSACTIONS_BLOCK_ID, DB_KEY_TRANSACTIONS_ID, DB_KEY_TEMPBLOCKS_HEIGHT, DB_KEY_ACCOUNTS_ADDRESS, DB_KEY_CHAIN_STATE, DB_KEY_CONSENSUS_STATE, DB_KEY_DIFF_STATE, } from './constants'; import { keyString } from '../utils'; import { stateDiffSchema } from '../schema'; export class Storage { private readonly _db: KVStore; public constructor(db: KVStore) { this._db = db; } /* Block headers */ public async getBlockHeaderByID(id: Buffer): Promise<Buffer> { const block = await this._db.get(`${DB_KEY_BLOCKS_ID}:${keyString(id)}`); return block; } public async getBlockHeadersByIDs(arrayOfBlockIds: ReadonlyArray<Buffer>): Promise<Buffer[]> { const blocks = []; for (const id of arrayOfBlockIds) { try { const block = await this._db.get(`${DB_KEY_BLOCKS_ID}:${keyString(id)}`); blocks.push(block); } catch (dbError) { if (dbError instanceof NotFoundError) { continue; } throw dbError; } } return blocks; } public async getBlockHeaderByHeight(height: number): Promise<Buffer> { const stringHeight = formatInt(height); const id = await this._db.get(`${DB_KEY_BLOCKS_HEIGHT}:${stringHeight}`); return this.getBlockHeaderByID(id); } public async getBlockHeadersByHeightBetween( fromHeight: number, toHeight: number, ): Promise<Buffer[]> { const stream = this._db.createReadStream({ gte: `${DB_KEY_BLOCKS_HEIGHT}:${formatInt(fromHeight)}`, lte: `${DB_KEY_BLOCKS_HEIGHT}:${formatInt(toHeight)}`, reverse: true, }); const blockIDs = await new Promise<Buffer[]>((resolve, reject) => { const ids: Buffer[] = []; stream .on('data', ({ value }: { value: Buffer }) => { ids.push(value); }) .on('error', error => { reject(error); }) .on('end', () => { resolve(ids); }); }); return this.getBlockHeadersByIDs(blockIDs); } public async getBlockHeadersWithHeights(heightList: ReadonlyArray<number>): Promise<Buffer[]> { const blocks = []; for (const height of heightList) { try { const block = await this.getBlockHeaderByHeight(height); blocks.push(block); } catch (dbError) { if (dbError instanceof NotFoundError) { continue; } throw dbError; } } return blocks; } public async getLastBlockHeader(): Promise<Buffer> { const stream = this._db.createReadStream({ gte: getFirstPrefix(DB_KEY_BLOCKS_HEIGHT), lte: getLastPrefix(DB_KEY_BLOCKS_HEIGHT), reverse: true, limit: 1, }); const [blockID] = await new Promise<Buffer[]>((resolve, reject) => { const ids: Buffer[] = []; stream .on('data', ({ value }: { value: Buffer }) => { ids.push(value); }) .on('error', error => { reject(error); }) .on('end', () => { resolve(ids); }); }); if (!blockID) { throw new NotFoundError('Last block header not found'); } return this.getBlockHeaderByID(blockID); } /* Extended blocks with transaction payload */ public async getBlockByID(id: Buffer): Promise<RawBlock> { const blockHeader = await this.getBlockHeaderByID(id); const transactions = await this._getTransactions(id); return { header: blockHeader, payload: transactions, }; } public async getBlocksByIDs(arrayOfBlockIds: ReadonlyArray<Buffer>): Promise<RawBlock[]> { const blocks = []; for (const id of arrayOfBlockIds) { try { const block = await this.getBlockByID(id); blocks.push(block); } catch (dbError) { if (dbError instanceof NotFoundError) { continue; } throw dbError; } } return blocks; } public async getBlockByHeight(height: number): Promise<RawBlock> { const header = await this.getBlockHeaderByHeight(height); const blockID = hash(header); const transactions = await this._getTransactions(blockID); return { header, payload: transactions, }; } public async getBlocksByHeightBetween(fromHeight: number, toHeight: number): Promise<RawBlock[]> { const headers = await this.getBlockHeadersByHeightBetween(fromHeight, toHeight); const blocks = []; for (const header of headers) { const blockID = hash(header); const transactions = await this._getTransactions(blockID); blocks.push({ header, payload: transactions }); } return blocks; } public async getLastBlock(): Promise<RawBlock> { const header = await this.getLastBlockHeader(); const blockID = hash(header); const transactions = await this._getTransactions(blockID); return { header, payload: transactions, }; } public async getTempBlocks(): Promise<Buffer[]> { const stream = this._db.createReadStream({ gte: getFirstPrefix(DB_KEY_TEMPBLOCKS_HEIGHT), lte: getLastPrefix(DB_KEY_TEMPBLOCKS_HEIGHT), reverse: true, }); const tempBlocks = await new Promise<Buffer[]>((resolve, reject) => { const blocks: Buffer[] = []; stream .on('data', ({ value }: { value: Buffer }) => { blocks.push(value); }) .on('error', error => { reject(error); }) .on('end', () => { resolve(blocks); }); }); return tempBlocks; } public async isTempBlockEmpty(): Promise<boolean> { const stream = this._db.createReadStream({ gte: getFirstPrefix(DB_KEY_TEMPBLOCKS_HEIGHT), lte: getLastPrefix(DB_KEY_TEMPBLOCKS_HEIGHT), limit: 1, }); const tempBlocks = await new Promise<Buffer[]>((resolve, reject) => { const blocks: Buffer[] = []; stream .on('data', ({ value }: { value: Buffer }) => { blocks.push(value); }) .on('error', error => { reject(error); }) .on('end', () => { resolve(blocks); }); }); return tempBlocks.length === 0; } public async clearTempBlocks(): Promise<void> { await this._db.clear({ gte: getFirstPrefix(DB_KEY_TEMPBLOCKS_HEIGHT), lte: getLastPrefix(DB_KEY_TEMPBLOCKS_HEIGHT), }); } public async isBlockPersisted(blockID: Buffer): Promise<boolean> { return this._db.exists(`${DB_KEY_BLOCKS_ID}:${keyString(blockID)}`); } /* ChainState */ public async getChainState(key: string): Promise<Buffer | undefined> { try { const value = await this._db.get(`${DB_KEY_CHAIN_STATE}:${key}`); return value; } catch (error) { if (error instanceof NotFoundError) { return undefined; } throw error; } } /* ConsensusState */ public async getConsensusState(key: string): Promise<Buffer | undefined> { try { const value = await this._db.get(`${DB_KEY_CONSENSUS_STATE}:${key}`); return value; } catch (error) { if (error instanceof NotFoundError) { return undefined; } throw error; } } // TODO: Remove in next version // Warning: This function should never be used. This exist only for migration purpose. // Specifically, only to set genesis state between 5.1.2 => 5.1.3 public async setConsensusState(key: string, val: Buffer): Promise<void> { await this._db.put(`${DB_KEY_CONSENSUS_STATE}:${key}`, val); } /* Accounts */ public async getAccountByAddress(address: Buffer): Promise<Buffer> { const account = await this._db.get(`${DB_KEY_ACCOUNTS_ADDRESS}:${keyString(address)}`); return account; } public async getAccountsByPublicKey(arrayOfPublicKeys: ReadonlyArray<Buffer>): Promise<Buffer[]> { const addresses = arrayOfPublicKeys.map(getAddressFromPublicKey); return this.getAccountsByAddress(addresses); } public async getAccountsByAddress(arrayOfAddresses: ReadonlyArray<Buffer>): Promise<Buffer[]> { const accounts = []; for (const address of arrayOfAddresses) { try { const account = await this.getAccountByAddress(address); accounts.push(account); } catch (dbError) { if (dbError instanceof NotFoundError) { continue; } throw dbError; } } return accounts; } /* Transactions */ public async getTransactionByID(id: Buffer): Promise<Buffer> { const transaction = await this._db.get(`${DB_KEY_TRANSACTIONS_ID}:${keyString(id)}`); return transaction; } public async getTransactionsByIDs( arrayOfTransactionIds: ReadonlyArray<Buffer>, ): Promise<Buffer[]> { const transactions = []; for (const id of arrayOfTransactionIds) { try { const transaction = await this.getTransactionByID(id); transactions.push(transaction); } catch (dbError) { if (dbError instanceof NotFoundError) { continue; } throw dbError; } } return transactions; } public async isTransactionPersisted(transactionId: Buffer): Promise<boolean> { return this._db.exists(`${DB_KEY_TRANSACTIONS_ID}:${keyString(transactionId)}`); } /* Save Block */ public async saveBlock( id: Buffer, height: number, finalizedHeight: number, header: Buffer, payload: { id: Buffer; value: Buffer }[], stateStore: StateStore, removeFromTemp = false, ): Promise<void> { const heightStr = formatInt(height); const batch = this._db.batch(); batch.put(`${DB_KEY_BLOCKS_ID}:${keyString(id)}`, header); batch.put(`${DB_KEY_BLOCKS_HEIGHT}:${heightStr}`, id); if (payload.length > 0) { const ids = []; for (const { id: txID, value } of payload) { ids.push(txID); batch.put(`${DB_KEY_TRANSACTIONS_ID}:${keyString(txID)}`, value); } batch.put(`${DB_KEY_TRANSACTIONS_BLOCK_ID}:${keyString(id)}`, Buffer.concat(ids)); } if (removeFromTemp) { batch.del(`${DB_KEY_TEMPBLOCKS_HEIGHT}:${heightStr}`); } stateStore.finalize(heightStr, batch); await batch.write(); await this._cleanUntil(finalizedHeight); } public async deleteBlock( id: Buffer, height: number, txIDs: Buffer[], fullBlock: Buffer, stateStore: StateStore, saveToTemp = false, ): Promise<StateDiff> { const batch = this._db.batch(); const heightStr = formatInt(height); batch.del(`${DB_KEY_BLOCKS_ID}:${keyString(id)}`); batch.del(`${DB_KEY_BLOCKS_HEIGHT}:${heightStr}`); if (txIDs.length > 0) { for (const txID of txIDs) { batch.del(`${DB_KEY_TRANSACTIONS_ID}:${keyString(txID)}`); } batch.del(`${DB_KEY_TRANSACTIONS_BLOCK_ID}:${keyString(id)}`); } if (saveToTemp) { batch.put(`${DB_KEY_TEMPBLOCKS_HEIGHT}:${heightStr}`, fullBlock); } // Take the diff to revert back states const diffKey = `${DB_KEY_DIFF_STATE}:${heightStr}`; // If there is no diff, the key might not exist const stateDiff = await this._db.get(diffKey); const { created: createdStates, updated: updatedStates, deleted: deletedStates, } = codec.decode<StateDiff>(stateDiffSchema, stateDiff); // Delete all the newly created states for (const key of createdStates) { batch.del(key); } // Revert all deleted values for (const { key, value: previousValue } of deletedStates) { batch.put(key, previousValue); } for (const { key, value: previousValue } of updatedStates) { batch.put(key, previousValue); } stateStore.finalize(heightStr, batch); // Delete stored diff at particular height batch.del(diffKey); // Persist the whole batch await batch.write(); return { deleted: deletedStates, created: createdStates, updated: updatedStates, }; } // This function is out of batch, but even if it fails, it will run again next time private async _cleanUntil(height: number): Promise<void> { await this._db.clear({ gte: `${DB_KEY_DIFF_STATE}:${formatInt(0)}`, lt: `${DB_KEY_DIFF_STATE}:${formatInt(height)}`, }); } private async _getTransactions(blockID: Buffer): Promise<Buffer[]> { const txIDs: Buffer[] = []; try { const ids = await this._db.get(`${DB_KEY_TRANSACTIONS_BLOCK_ID}:${keyString(blockID)}`); const idLength = 32; for (let i = 0; i < ids.length; i += idLength) { txIDs.push(ids.slice(i, i + idLength)); } } catch (error) { if (!(error instanceof NotFoundError)) { throw error; } } if (txIDs.length === 0) { return []; } const transactions = []; for (const txID of txIDs) { const tx = await this._db.get(`${DB_KEY_TRANSACTIONS_ID}:${keyString(txID)}`); transactions.push(tx); } return transactions; } }
the_stack
import { assert } from "chai"; import * as Plottable from "../../src"; import * as TestMethods from "../testMethods"; describe("Utils.Methods", () => { it("inRange()", () => { assert.isTrue(Plottable.Utils.Math.inRange(0, -1, 1), "basic functionality works"); assert.isTrue(Plottable.Utils.Math.inRange(0, 0, 1), "it is a closed interval"); assert.isTrue(!Plottable.Utils.Math.inRange(0, 1, 2), "returns false when false"); }); describe("max() and min()", () => { const max = Plottable.Utils.Math.max; const min = Plottable.Utils.Math.min; const today = new Date(); it("return the default value if max() or min() can't be computed", () => { const minValue = 1; const maxValue = 5; const defaultValue = 3; const goodArray: number[][] = [ [minValue], [maxValue], ]; // bad array is technically of type number[][], but subarrays are empty! const badArray: number[][] = [ [], [], ]; const accessor = (arr: number[]) => arr[0]; assert.strictEqual(min<number[], number>(goodArray, accessor, defaultValue), minValue, "min(): minimum value is returned in good case"); assert.strictEqual(min<number[], number>(badArray, accessor, defaultValue), defaultValue, "min(): default value is returned in bad case"); assert.strictEqual(max<number[], number>(goodArray, accessor, defaultValue), maxValue, "max(): maximum value is returned in good case"); assert.strictEqual(max<number[], number>(badArray, accessor, defaultValue), defaultValue, "max(): default value is returned in bad case"); }); it("max() and min() work on numbers", () => { const alist = [1, 2, 3, 4, 5]; const dbl = (x: number) => x * 2; const dblIndexOffset = (x: number, i: number) => x * 2 - i; const numToDate = (x: number) => { const t = new Date(today.getTime()); t.setDate(today.getDate() + x); return t; }; assert.deepEqual(max(alist, 99), 5, "max ignores default on non-empty array"); assert.deepEqual(max(alist, dbl, 0), 10, "max applies function appropriately"); assert.deepEqual(max(alist, dblIndexOffset, 5), 6, "max applies function with index"); assert.deepEqual(max(alist, numToDate, today), numToDate(5), "max applies non-numeric function appropriately"); assert.deepEqual(max([], 10), 10, "works as intended with default value"); assert.deepEqual(max([], dbl, 5), 5, "default value works with function"); assert.deepEqual(max([], numToDate, today), today, "default non-numeric value works with non-numeric function"); assert.deepEqual(min(alist, 0), 1, "min works for basic list"); assert.deepEqual(min(alist, dbl, 0), 2, "min works with function arg"); assert.deepEqual(min(alist, dblIndexOffset, 0), 2, "min works with function index arg"); assert.deepEqual(min(alist, numToDate, today), numToDate(1), "min works with non-numeric function arg"); assert.deepEqual(min([], dbl, 5), 5, "min accepts custom default and function"); assert.deepEqual(min([], numToDate, today), today, "min accepts non-numeric default and function"); }); it("max() and min() work on strings", () => { const strings = ["a", "bb", "ccc", "ddd"]; assert.deepEqual(max(strings, (s: string) => s.length, 0), 3, "works on arrays of non-numbers with a function"); assert.deepEqual(max([], (s: string) => s.length, 5), 5, "defaults work even with non-number function type"); }); it("max() and min() work on dates", () => { const tomorrow = new Date(today.getTime()); tomorrow.setDate(today.getDate() + 1); const dayAfterTomorrow = new Date(today.getTime()); dayAfterTomorrow.setDate(today.getDate() + 2); const dates: Date[] = [today, tomorrow, dayAfterTomorrow, null]; assert.deepEqual(min<Date>(dates, dayAfterTomorrow), today, "works on arrays of non-numeric values but comparable"); assert.deepEqual(max<Date>(dates, today), dayAfterTomorrow, "works on arrays of non-number values but comparable"); assert.deepEqual(max<Date>([null], today), today, "returns default value if passed array of null values"); assert.deepEqual(max<Date>([], today), today, "returns default value if passed empty"); }); }); it("isNaN()", () => { const isNaN = Plottable.Utils.Math.isNaN; assert.isTrue(isNaN(NaN), "Only NaN should pass the isNaN check"); assert.isFalse(isNaN(undefined), "undefined should fail the isNaN check"); assert.isFalse(isNaN(null), "null should fail the isNaN check"); assert.isFalse(isNaN(Infinity), "Infinity should fail the isNaN check"); assert.isFalse(isNaN(1), "numbers should fail the isNaN check"); assert.isFalse(isNaN(0), "0 should fail the isNaN check"); assert.isFalse(isNaN("foo"), "strings should fail the isNaN check"); assert.isFalse(isNaN(""), "empty strings should fail the isNaN check"); assert.isFalse(isNaN({}), "empty Objects should fail the isNaN check"); }); it("isValidNumber()", () => { const isValidNumber = Plottable.Utils.Math.isValidNumber; assert.isTrue(isValidNumber(0), "(0 is a valid number"); assert.isTrue(isValidNumber(1), "(1 is a valid number"); assert.isTrue(isValidNumber(-1), "(-1 is a valid number"); assert.isTrue(isValidNumber(0.1), "(0.1 is a valid number"); assert.isFalse(isValidNumber(null), "(null is not a valid number"); assert.isFalse(isValidNumber(NaN), "(NaN is not a valid number"); assert.isFalse(isValidNumber(undefined), "(undefined is not a valid number"); assert.isFalse(isValidNumber(Infinity), "(Infinity is not a valid number"); assert.isFalse(isValidNumber(-Infinity), "(-Infinity is not a valid number"); assert.isFalse(isValidNumber("number"), "('number' is not a valid number"); assert.isFalse(isValidNumber("string"), "('string' is not a valid number"); assert.isFalse(isValidNumber("0"), "('0' is not a valid number"); assert.isFalse(isValidNumber("1"), "('1' is not a valid number"); assert.isFalse(isValidNumber([]), "([] is not a valid number"); assert.isFalse(isValidNumber([1]), "([1] is not a valid number"); assert.isFalse(isValidNumber({}), "({} is not a valid number"); assert.isFalse(isValidNumber({1: 1}), "({1: 1} is not a valid number"); }); it("range()", () => { const start = 0; const end = 6; let range = Plottable.Utils.Math.range(start, end); assert.deepEqual(range, [0, 1, 2, 3, 4, 5], "all entries has been generated"); range = Plottable.Utils.Math.range(start, end, 2); assert.deepEqual(range, [0, 2, 4], "all entries has been generated"); range = Plottable.Utils.Math.range(start, end, 11); assert.deepEqual(range, [0], "all entries has been generated"); assert.throws(() => Plottable.Utils.Math.range(start, end, 0), "step cannot be 0"); range = Plottable.Utils.Math.range(start, end, -1); assert.lengthOf(range, 0, "no entries because of invalid step"); range = Plottable.Utils.Math.range(end, start, -1); assert.deepEqual(range, [6, 5, 4, 3, 2, 1], "all entries has been generated"); range = Plottable.Utils.Math.range(-2, 2); assert.deepEqual(range, [-2, -1, 0, 1], "all entries has been generated range crossing 0"); range = Plottable.Utils.Math.range(0.2, 4); assert.deepEqual(range, [0.2, 1.2, 2.2, 3.2], "all entries has been generated with float start"); range = Plottable.Utils.Math.range(0.6, 2.2, 0.5); assert.deepEqual(range, [0.6, 1.1, 1.6, 2.1], "all entries has been generated with float step"); }); }); describe("Utils Matrix", () => { type Matrix = Plottable.Utils.Math.ICssTransformMatrix; const identity: Matrix = [1, 0, 0, 1, 0, 0]; const { multiplyMatrix, invertMatrix, applyTransform } = Plottable.Utils.Math; const rotationMatrix = (theta: number): Matrix => { return [Math.cos(theta), Math.sin(theta), -Math.sin(theta), Math.cos(theta), 0, 0]; }; const scaleMatrix = (sx: number, sy: number): Matrix => { return [sx, 0, 0, sy, 0, 0]; }; const translationMatrix = (tx: number, ty: number): Matrix => { return [1, 0, 0, 1, tx, ty]; }; const assertMatricesEqual = (a: Matrix, b: Matrix, msg: string, epsilon = 1e-12) => { for (let i = 0; i < 6; i++) { assert.closeTo(a[i], b[i], epsilon, `${msg} (${i})`); } }; it("multiplication by identity results in same matrix", () => { const m0 = rotationMatrix(Plottable.Utils.Math.degreesToRadians(45)); assertMatricesEqual(m0, multiplyMatrix(m0, identity), "multiply identity"); assertMatricesEqual(m0, multiplyMatrix(identity, m0), "pre-multiply identity"); }); it("multiplication by rotations returns to identity", () => { // rotate by 60 degrees 6 times => 360 degree rotation const rotate = rotationMatrix(Plottable.Utils.Math.degreesToRadians(60)); let m = identity; for (let i = 0; i < 6; i++) { m = multiplyMatrix(m, rotate); } assertMatricesEqual(m, identity, "rotation"); }); it("multiplication by scales returns to identity", () => { const bigger = scaleMatrix(16, 4); const smaller = scaleMatrix(1/16, 1/4); let m = identity; m = multiplyMatrix(m, bigger); m = multiplyMatrix(m, smaller); assertMatricesEqual(m, identity, "scale"); }); it("multiplication by translation returns to identity", () => { const moveFoo = translationMatrix(127, -8); const moveBar = translationMatrix(-127, 8); let m = identity; m = multiplyMatrix(m, moveFoo); m = multiplyMatrix(m, moveBar); assertMatricesEqual(m, identity, "translate"); }); it("inverse of identity is identity", () => { assertMatricesEqual(invertMatrix(identity), identity, "I = I^-1"); }); it("multiplication by inverse returns to identity", () => { let m = identity; m = multiplyMatrix(m, rotationMatrix(Plottable.Utils.Math.degreesToRadians(60))); m = multiplyMatrix(m, translationMatrix(127, -8)); m = multiplyMatrix(m, scaleMatrix(16, 4)); m = multiplyMatrix(m, invertMatrix(m)); assertMatricesEqual(m, identity, "A * A^-1 = I"); }); it("pre-post multiplication order", () => { const rotate = rotationMatrix(Plottable.Utils.Math.degreesToRadians(60)); const translate = translationMatrix(127, -8); const scale = scaleMatrix(16, 4); let m0 = identity; m0 = multiplyMatrix(m0, rotate); m0 = multiplyMatrix(m0, translate); m0 = multiplyMatrix(m0, scale); let m1 = identity; m1 = multiplyMatrix(scale, m1); m1 = multiplyMatrix(translate, m1); m1 = multiplyMatrix(rotate, m1); assertMatricesEqual(m0, m1, "multiplication order"); }); it("apply transform to point", () => { // use 3-4-5 triangle identity const point = {x: 0, y: 5}; const rotate = rotationMatrix(Plottable.Utils.Math.degreesToRadians(36.87)); const rotated = applyTransform(rotate, point); TestMethods.assertPointsClose(rotated, {x: -3, y: 4}, 1e-3, "rotates to 3-4-5 triangle point"); }); it("throws error when trying to invert singular matrix", () => { const m: Matrix = [0, 0, 0, 0, 0, 0]; assert.throws(() => invertMatrix(m)); }); });
the_stack
namespace phasereditor2d.scene { import ide = colibri.ui.ide; import controls = colibri.ui.controls; export const ICON_GROUP = "group"; export const ICON_TRANSLATE = "translate"; export const ICON_ANGLE = "angle"; export const ICON_SCALE = "scale"; export const ICON_ORIGIN = "origin"; export const ICON_SELECT_REGION = "select-region"; export const ICON_BUILD = "build"; export const ICON_LOCKED = "locked"; export const ICON_UNLOCKED = "unlocked"; export const ICON_LIST = "list"; export const ICON_USER_COMPONENT = "user-component"; export const ICON_IMAGE_TYPE = "image-type"; export const ICON_SPRITE_TYPE = "sprite-type"; export const ICON_TILESPRITE_TYPE = "tilesprite"; export const ICON_TEXT_TYPE = "text-type"; export const ICON_BITMAP_FONT_TYPE = "bitmapfont-type"; export const ICON_LAYER = "layer"; export const ICON_ALIGN_LEFT = "align-left"; export const ICON_ALIGN_CENTER = "align-center"; export const ICON_ALIGN_RIGHT = "align-right"; export const ICON_ALIGN_TOP = "align-top"; export const ICON_ALIGN_MIDDLE = "align-middle"; export const ICON_ALIGN_BOTTOM = "align-bottom"; export const ICON_BORDER_LEFT = "border-left"; export const ICON_BORDER_CENTER = "border-center"; export const ICON_BORDER_RIGHT = "border-right"; export const ICON_BORDER_TOP = "border-top"; export const ICON_BORDER_MIDDLE = "border-middle"; export const ICON_BORDER_BOTTOM = "border-bottom"; export const ICON_GRID = "grid"; export const ICON_COLUMN = "column"; export const ICON_ROW = "row"; export const SCENE_OBJECT_IMAGE_CATEGORY = "Texture"; export const SCENE_OBJECT_TEXT_CATEGORY = "String"; export const SCENE_OBJECT_GROUPING_CATEGORY = "Grouping"; export const SCENE_OBJECT_TILEMAP_CATEGORY = "Tile Map"; export const SCENE_OBJECT_SHAPE_CATEGORY = "Shape"; export const SCENE_OBJECT_CATEGORIES = [ SCENE_OBJECT_IMAGE_CATEGORY, SCENE_OBJECT_GROUPING_CATEGORY, SCENE_OBJECT_TEXT_CATEGORY, SCENE_OBJECT_SHAPE_CATEGORY, SCENE_OBJECT_TILEMAP_CATEGORY, ]; export const SCENE_OBJECT_CATEGORY_SET = new Set(SCENE_OBJECT_CATEGORIES); export class ScenePlugin extends colibri.Plugin { private static _instance = new ScenePlugin(); static DEFAULT_CANVAS_CONTEXT = Phaser.WEBGL; static DEFAULT_EDITOR_CANVAS_CONTEXT = Phaser.WEBGL; private _sceneFinder: core.json.SceneFinder; private _docs: phasereditor2d.ide.core.PhaserDocs; static getInstance() { return this._instance; } private constructor() { super("phasereditor2d.scene"); this._docs = new phasereditor2d.ide.core.PhaserDocs(this, "data/phaser-docs.json"); } getPhaserDocs() { return this._docs; } registerExtensions(reg: colibri.ExtensionRegistry) { this._sceneFinder = new core.json.SceneFinder(); // preload docs reg.addExtension(new ide.PluginResourceLoaderExtension(async () => { await ScenePlugin.getInstance().getPhaserDocs().preload(); })); // preload UserComponent files reg.addExtension(new ide.PluginResourceLoaderExtension(async () => { await ui.editor.usercomponent.UserComponentCodeResources.getInstance().preload(); })); // preload project reg.addExtension(this._sceneFinder.getProjectPreloader()); // content type resolvers reg.addExtension( new colibri.core.ContentTypeExtension( [new core.SceneContentTypeResolver()], 5 )); reg.addExtension( new colibri.core.ContentTypeExtension( [new colibri.core.ContentTypeResolverByExtension( core.CONTENT_TYPE_USER_COMPONENTS + "Resolver", [ ["components", core.CONTENT_TYPE_USER_COMPONENTS] ]) ]) ) // content type renderer reg.addExtension( new files.ui.viewers.SimpleContentTypeCellRendererExtension( core.CONTENT_TYPE_SCENE, new ui.viewers.SceneFileCellRenderer() ) ); // icons loader reg.addExtension( ide.IconLoaderExtension.withPluginFiles(this, [ ICON_USER_COMPONENT, ICON_SELECT_REGION, ICON_TRANSLATE, ICON_SCALE, ICON_ANGLE, ICON_ORIGIN, ICON_TEXT_TYPE, ICON_BITMAP_FONT_TYPE, ICON_SPRITE_TYPE, ICON_TILESPRITE_TYPE, ICON_LIST, ICON_IMAGE_TYPE, ICON_GROUP, ICON_BUILD, ICON_LAYER, ICON_ALIGN_LEFT, ICON_ALIGN_CENTER, ICON_ALIGN_RIGHT, ICON_ALIGN_TOP, ICON_ALIGN_MIDDLE, ICON_ALIGN_BOTTOM, ICON_BORDER_LEFT, ICON_BORDER_CENTER, ICON_BORDER_RIGHT, ICON_BORDER_TOP, ICON_BORDER_MIDDLE, ICON_BORDER_BOTTOM, ICON_GRID, ICON_COLUMN, ICON_ROW ]) ); reg.addExtension( ide.IconLoaderExtension.withPluginFiles(this, [ ICON_LOCKED, ICON_UNLOCKED ]) ); reg.addExtension( colibri.ui.ide.ContentTypeIconExtension.withPluginIcons(this, [ { iconName: ICON_USER_COMPONENT, contentType: core.CONTENT_TYPE_USER_COMPONENTS } ])); // loader updates reg.addExtension( new ui.sceneobjects.ImageLoaderUpdater(), new ui.sceneobjects.BitmapFontLoaderUpdater(), new ui.sceneobjects.TilemapLoaderUpdater() ); // outline extensions reg.addExtension( new ui.sceneobjects.TilemapOutlineExtension() ); // commands reg.addExtension( new ide.commands.CommandExtension(m => ui.editor.commands.SceneEditorCommands.registerCommands(m))); reg.addExtension( new ide.commands.CommandExtension(m => ui.editor.usercomponent.UserComponentsEditor.registerCommands(m))); // compile project reg.addExtension( new ui.editor.usercomponent.UserComponentCompileAllExtension(), new core.code.SceneCompileAllExtension()); // editors reg.addExtension( new ide.EditorExtension([ ui.editor.SceneEditor.getFactory(), ui.editor.usercomponent.UserComponentsEditor.getFactory() ])); // new file wizards reg.addExtension( new ui.dialogs.NewSceneFileDialogExtension(), new ui.dialogs.NewPrefabFileDialogExtension(), new ui.dialogs.NewUserComponentsFileDialogExtension() ); // file properties reg.addExtension(new files.ui.views.FilePropertySectionExtension( page => new ui.SceneFileSection(page), page => new ui.ManySceneFileSection(page) )); // scene game object extensions reg.addExtension( ui.sceneobjects.ImageExtension.getInstance(), ui.sceneobjects.SpriteExtension.getInstance(), ui.sceneobjects.TileSpriteExtension.getInstance(), ui.sceneobjects.TextExtension.getInstance(), ui.sceneobjects.BitmapTextExtension.getInstance(), ui.sceneobjects.ContainerExtension.getInstance(), ui.sceneobjects.LayerExtension.getInstance(), ui.sceneobjects.TilemapLayerExtension.getInstance(), ui.sceneobjects.RectangleExtension.getInstance(), ui.sceneobjects.EllipseExtension.getInstance(), ui.sceneobjects.TriangleExtension.getInstance() ); // scene plain object extensions reg.addExtension( ui.sceneobjects.TilemapExtension.getInstance() ); // align extensions reg.addExtension(...ui.editor.layout.DefaultLayoutExtensions.ALL); // property sections reg.addExtension(new ui.editor.properties.SceneEditorPropertySectionExtension( page => new ui.sceneobjects.GameObjectVariableSection(page), page => new ui.sceneobjects.PrefabInstanceSection(page), page => new ui.sceneobjects.UserComponentInstancePropertySection(page), page => new ui.sceneobjects.ListVariableSection(page), page => new ui.sceneobjects.GameObjectListSection(page), page => new ui.sceneobjects.ParentSection(page), page => new ui.sceneobjects.ChildrenSection(page), page => new ui.sceneobjects.TransformSection(page), page => new ui.sceneobjects.OriginSection(page), page => new ui.sceneobjects.FlipSection(page), page => new ui.sceneobjects.VisibleSection(page), page => new ui.sceneobjects.AlphaSection(page), page => new ui.sceneobjects.AlphaSingleSection(page), page => new ui.sceneobjects.TintSection(page), page => new ui.sceneobjects.SizeSection(page), page => new ui.sceneobjects.TileSpriteSection(page), page => new ui.sceneobjects.TextureSection(page), page => new ui.sceneobjects.TextContentSection(page), page => new ui.sceneobjects.TextSection(page), page => new ui.sceneobjects.BitmapTextSection(page), page => new ui.sceneobjects.ListSection(page), page => new ui.sceneobjects.ScenePlainObjectVariableSection(page), page => new ui.sceneobjects.TilemapSection(page), page => new ui.sceneobjects.TilesetSection(page), page => new ui.sceneobjects.TilesetPreviewSection(page), page => new ui.sceneobjects.TilemapLayerSection(page), page => new ui.sceneobjects.ShapeSection(page), page => new ui.sceneobjects.EllipseSection(page), page => new ui.sceneobjects.TriangleSection(page) )); // scene tools reg.addExtension(new ui.editor.tools.SceneToolExtension( new ui.sceneobjects.TranslateTool(), new ui.sceneobjects.RotateTool(), new ui.sceneobjects.ScaleTool(), new ui.sceneobjects.OriginTool(), new ui.sceneobjects.SizeTool(), new ui.sceneobjects.SelectionRegionTool(), new ui.sceneobjects.PanTool(), )); // files view sections reg.addExtension(new phasereditor2d.files.ui.views.ContentTypeSectionExtension( { section: phasereditor2d.files.ui.views.TAB_SECTION_DESIGN, contentType: core.CONTENT_TYPE_SCENE }, { section: phasereditor2d.files.ui.views.TAB_SECTION_DESIGN, contentType: core.CONTENT_TYPE_USER_COMPONENTS } )); } getTools() { return colibri.Platform.getExtensions<ui.editor.tools.SceneToolExtension> (ui.editor.tools.SceneToolExtension.POINT_ID) .flatMap(ext => ext.getTools()); } getTool(toolId: string) { return this.getTools().find(tool => tool.getId() === toolId); } getDefaultSceneSettings() { const settings = new core.json.SceneSettings(); try { const finder = ScenePlugin.getInstance().getSceneFinder(); const files = [...finder.getSceneFiles()]; files.sort((a, b) => b.getModTime() - a.getModTime()); if (files.length > 0) { const file = files[0]; settings.readJSON(finder.getSceneData(file).settings); } } catch (e) { console.error(e); } return settings; } createUserPropertyTypes() { // TODO: we should do this via extension return [ new ui.sceneobjects.NumberPropertyType(), new ui.sceneobjects.StringPropertyType(), new ui.sceneobjects.BooleanPropertyType(), new ui.sceneobjects.ExpressionPropertyType(), new ui.sceneobjects.OptionPropertyType(), new ui.sceneobjects.TextureConfigPropertyType(), new ui.sceneobjects.AnimationKeyPropertyType(), new ui.sceneobjects.AudioKeyPropertyType(), new ui.sceneobjects.AssetKeyPropertyType(), ]; } createUserPropertyType(typeId: string) { return this.createUserPropertyTypes().find(t => t.getId() === typeId); } getSceneFinder() { return this._sceneFinder; } isSceneContentType(file: colibri.core.io.FilePath) { return !file.isFolder() && colibri.Platform.getWorkbench().getContentTypeRegistry().getCachedContentType(file) === core.CONTENT_TYPE_SCENE; } getPlainObjectExtensions() { return colibri.Platform .getExtensions<ui.sceneobjects.ScenePlainObjectExtension>(ui.sceneobjects.ScenePlainObjectExtension.POINT_ID); } getPlainObjectCategories() { return this.getPlainObjectExtensions().map(e => e.getCategory()); } getPlainObjectExtensionByObjectType(type: string) { return this.getPlainObjectExtensions().find(ext => ext.getTypeName() === type); } getGameObjectExtensions(): ui.sceneobjects.SceneGameObjectExtension[] { return colibri.Platform .getExtensions<ui.sceneobjects.SceneGameObjectExtension>(ui.sceneobjects.SceneGameObjectExtension.POINT_ID); } getGameObjectExtensionByObjectType(type: string) { return this.getGameObjectExtensions().find(ext => { if (ext.getTypeName() === type) { return ext; } if (ext.getTypeNameAlias().indexOf(type) >= 0) { return ext; } }); } getSceneEditorOutlineExtensions() { return colibri.Platform .getExtensions<ui.editor.outline.SceneEditorOutlineExtension>( ui.editor.outline.SceneEditorOutlineExtension.POINT_ID); } getLayoutExtensions() { return colibri.Platform .getExtensions<ui.editor.layout.LayoutExtension>( ui.editor.layout.LayoutExtension.POINT_ID); } getLayoutExtensionsByGroup() { const allExtensions = ScenePlugin.getInstance().getLayoutExtensions() const groups: string[] = []; for (const ext of allExtensions) { if (groups.indexOf(ext.getConfig().group) < 0) { groups.push(ext.getConfig().group); } } const result: Array<{ group: string, extensions: ui.editor.layout.LayoutExtension[] }> = []; for (const group of groups) { const extensions = allExtensions.filter(e => e.getConfig().group === group); result.push({ group, extensions }); } return result; } getLoaderUpdaterForAsset(asset: any) { const exts = colibri.Platform .getExtensions<ui.sceneobjects.LoaderUpdaterExtension>(ui.sceneobjects.LoaderUpdaterExtension.POINT_ID); for (const ext of exts) { if (ext.acceptAsset(asset)) { return ext; } } return null; } getLoaderUpdaters() { const exts = colibri.Platform .getExtensions<ui.sceneobjects.LoaderUpdaterExtension>(ui.sceneobjects.LoaderUpdaterExtension.POINT_ID); return exts; } async compileAll() { const files = this._sceneFinder.getSceneFiles(); const dlg = new controls.dialogs.ProgressDialog(); dlg.create(); dlg.setTitle("Compiling Scene Files"); const monitor = new controls.dialogs.ProgressDialogMonitor(dlg); monitor.addTotal(files.length); for (const file of files) { const data = this.getSceneFinder().getSceneData(file); const scene = await ui.OfflineScene.createScene(data); const compiler = new core.code.SceneCompiler(scene, file); await compiler.compile(); scene.destroyGame(); monitor.step(); } dlg.close(); } } colibri.Platform.addPlugin(ScenePlugin.getInstance()); }
the_stack
import path from 'path' import FabricTools from '../instance/fabricTools' import FabricInstance from '../instance/fabricInstance' import { ChaincodeApproveStepApproveOnInstanceType, ChaincodeApproveType, ChaincodeCommitStepCommitOnInstanceType, ChaincodeApproveWithoutDiscoverType, ChaincodeCommitType, ChaincodeInstallStepSavePackageIdType, ChaincodeInstallType, ChaincodeInvokeType, ChaincodePackageType, ChaincodeQueryType, ChaincodeCommitWithoutDiscoverType, ChaincodeInvokeStepInvokeOnInstanceType, ChaincodeInvokeWithoutDiscoverType } from '../model/type/chaincode.type' import { ParserType, AbstractService } from './Service.abstract' import { logger } from '../util/logger' import { DockerResultType, InfraRunnerResultType } from '../instance/infra/InfraRunner.interface' import Discover from './discover' import { randomFromArray } from '../util/utils' interface ChaincodeParser extends ParserType { installToPeer: (result: DockerResultType, options: {chaincodeLabel: string}) => string invoke: (result: DockerResultType) => any query: (result: DockerResultType) => any getChaincodePackageId: (result: DockerResultType, options: {chaincodeLabel: string}) => string getCommittedChaincode: (result: DockerResultType) => string[] approveStepDiscover: (result: DockerResultType) => string commitStepDiscoverChannelConfig: (result: DockerResultType) => string commitStepDiscoverPeers: (result: DockerResultType) => string[] invokeStepDiscoverChannelConfig: (result: DockerResultType) => string invokeStepDiscoverEndorsers: (result: DockerResultType) => string[] } export default class Chaincode extends AbstractService { static readonly parser: ChaincodeParser = { installToPeer: (result, options: {chaincodeLabel: string}) => result.stdout.match(RegExp(`(?<=Chaincode code package identifier: )${options.chaincodeLabel}:.*(?=\r\n$)`))?.[0] || '', invoke: (result) => JSON.parse(result.stdout.match(/(?<=Chaincode invoke successful. result: status:200 payload:").*(?=" \r\n)/)?.[0].replace(/\\"/g, '"') || '{}'), query: (result) => JSON.parse(result.stdout || '{}'), getChaincodePackageId: (result, options: {chaincodeLabel: string}) => result.stdout.match(RegExp(`(?<=Package ID: )${options.chaincodeLabel}:.*(?=, Label: ${options.chaincodeLabel})`))?.[0] || '', getCommittedChaincode: (result) => result.stdout.match(/(?<=Name: ).*(?=, Version)/g) || [], approveStepDiscover: (result) => Discover.chooseOneRandomOrderer(Discover.parser.channelConfig(result)), commitStepDiscoverChannelConfig: (result) => Discover.chooseOneRandomOrderer(Discover.parser.channelConfig(result)), commitStepDiscoverPeers: (result) => { const peerDiscoverResult = Discover.parser.peers(result) const peerList: Map<string, string[]> = new Map() peerDiscoverResult.forEach(peer => { peerList.has(peer.MSPID) ? peerList.get(peer.MSPID)?.push(peer.Endpoint) : peerList.set(peer.MSPID, [peer.Endpoint]) }) const peers: string[] = [] Array.from(peerList.keys()).forEach(org => { const peersOfOrg = peerList.get(org) || [] peers.push(randomFromArray(peersOfOrg)) }) return peers }, invokeStepDiscoverChannelConfig: (result) => Discover.chooseOneRandomOrderer(Discover.parser.channelConfig(result)), invokeStepDiscoverEndorsers: (result) => { const endorserDiscoverResult = Discover.parser.chaincodeEndorsers(result) const layout = randomFromArray(endorserDiscoverResult[0].Layouts) return (Object.keys(layout.quantities_by_group).map(group => (randomFromArray(endorserDiscoverResult[0].EndorsersByGroups[group]).Endpoint))) }, } /** * @description 打包 chaincode 成 tar 檔案 * @returns 在 ./chaincode 中 [chaincode 的名稱]_[cahincode 的版本].tar */ public async package (payload: ChaincodePackageType) { logger.debug('Package chaincode') this.bdkFile.createChaincodeFolder() await (new FabricTools(this.config, this.infra)).packageChaincode(payload.name, payload.version, path.resolve(payload.path)) } /** * @description 執行 chaincode 上的 function 發送交易 * @returns 執行 chaincode function 的回覆 */ public async invoke (payload: ChaincodeInvokeType | ChaincodeInvokeWithoutDiscoverType): Promise<InfraRunnerResultType> { let orderer: string let peerAddresses: string[] if ('orderer' in payload) { orderer = payload.orderer } else { const discoverChannelConfigResult = await this.invokeSteps().discoverChannelConfig(payload) if (!('stdout' in discoverChannelConfigResult)) { logger.error('this service only for docker infra') throw new Error('this service for docker infra') } orderer = Chaincode.parser.invokeStepDiscoverChannelConfig(discoverChannelConfigResult) } if ('peerAddresses' in payload) { peerAddresses = payload.peerAddresses } else { const discoverEndorsersResult = await this.invokeSteps().discoverEndorsers(payload) if (!('stdout' in discoverEndorsersResult)) { logger.error('this service only for docker infra') throw new Error('this service for docker infra') } peerAddresses = Chaincode.parser.invokeStepDiscoverEndorsers(discoverEndorsersResult) } return await this.invokeSteps().invokeOnInstance({ ...payload, orderer, peerAddresses }) } /** * @ignore */ public invokeSteps () { return { discoverEndorsers: async (payload: ChaincodeInvokeType): Promise<InfraRunnerResultType> => { logger.debug('invoke chaincode step 1 (discover endorsers)') return await (new Discover(this.config)).chaincodeEndorsers({ channel: payload.channelId, chaincode: payload.chaincodeName }) }, discoverChannelConfig: async (payload: ChaincodeInvokeType): Promise<InfraRunnerResultType> => { logger.debug('invoke chaincode step 2 (discover channel config)') return await (new Discover(this.config)).channelConfig({ channel: payload.channelId }) }, invokeOnInstance: async (payload: ChaincodeInvokeStepInvokeOnInstanceType): Promise<InfraRunnerResultType> => { logger.debug('invoke chaincode step 3 (invoke)') return await (new FabricInstance(this.config, this.infra)).invokeChaincode(payload.channelId, payload.chaincodeName, payload.chaincodeFunction, payload.args, payload.isInit, payload.orderer, payload.peerAddresses) }, } } /** * @description 執行 chaincode 上的 function 查詢 * @returns 執行 chaincode function 的回覆 */ public async query (payload: ChaincodeQueryType): Promise<InfraRunnerResultType> { logger.debug('query chaincode') return await (new FabricInstance(this.config, this.infra)).queryChaincode(payload.channelId, payload.chaincodeName, payload.chaincodeFunction, payload.args) } /** * @ignore */ public async install (dto: ChaincodeInstallType): Promise<string> { const installToPeerResult = await this.installSteps().installToPeer(dto) if (!('stdout' in installToPeerResult)) { logger.error('this service only for docker infra') throw new Error('this service for docker infra') } const packageId = Chaincode.parser.installToPeer(installToPeerResult, { chaincodeLabel: dto.chaincodeLabel }) return this.installSteps().savePackageId({ ...dto, packageId }) } /** * @ignore */ public installSteps () { return { installToPeer: async (dto: ChaincodeInstallType): Promise<InfraRunnerResultType> => { logger.debug('install chaincode step 1 (install chaincode)') return await (new FabricInstance(this.config, this.infra)).installChaincode(dto.chaincodeLabel) }, savePackageId: (dto: ChaincodeInstallStepSavePackageIdType): string => { logger.debug('install chaincode step 2 (save package id)') this.bdkFile.savePackageId(dto.chaincodeLabel, dto.packageId || '') return dto.packageId || '' }, } } /** * @description 取得 chaincode 安裝編號 * @param chaincodeLabel - chaincode 的標籤名稱 * @returns chaincode 的安裝編號 */ public async getChaincodePackageId (): Promise<InfraRunnerResultType> { logger.debug('query installed and get package id') return await (new FabricInstance(this.config, this.infra)).queryInstalledChaincode() } /** * @description 同意 chaincode */ public async approve (payload: ChaincodeApproveType | ChaincodeApproveWithoutDiscoverType): Promise<InfraRunnerResultType> { let orderer: string if ('orderer' in payload) { orderer = payload.orderer } else { const discoverResult = await this.approveSteps().discover(payload) if (!('stdout' in discoverResult)) { logger.error('this service only for docker infra') throw new Error('this service for docker infra') } orderer = Chaincode.parser.approveStepDiscover(discoverResult) } return await this.approveSteps().approveOnInstance({ ...payload, orderer }) } /** * @ignore */ public approveSteps () { return { discover: async (payload: ChaincodeApproveType): Promise<InfraRunnerResultType> => { logger.debug('approve chaincode step 1 (discover)') return await (new Discover(this.config)).channelConfig({ channel: payload.channelId }) }, approveOnInstance: async (payload: ChaincodeApproveStepApproveOnInstanceType): Promise<InfraRunnerResultType> => { logger.debug('approve chaincode step 2 (approve)') const packageId = this.bdkFile.getPackageId(`${payload.chaincodeName}_${payload.chaincodeVersion}`) return await (new FabricInstance(this.config, this.infra)).approveChaincode(payload.channelId, payload.chaincodeName, payload.chaincodeVersion, packageId, payload.initRequired, payload.orderer) }, } } /** * @description 發布 chaincode */ public async commit (payload: ChaincodeCommitType | ChaincodeCommitWithoutDiscoverType): Promise<InfraRunnerResultType> { let orderer: string let peerAddresses: string[] if ('orderer' in payload) { orderer = payload.orderer } else { const discoverChannelConfigResult = await this.commitSteps().discoverChannelConfig(payload) if (!('stdout' in discoverChannelConfigResult)) { logger.error('this service only for docker infra') throw new Error('this service for docker infra') } orderer = Chaincode.parser.commitStepDiscoverChannelConfig(discoverChannelConfigResult) } if ('peerAddresses' in payload) { peerAddresses = payload.peerAddresses } else { const discoverPeersResult = await this.commitSteps().discoverPeers(payload) if (!('stdout' in discoverPeersResult)) { logger.error('this service only for docker infra') throw new Error('this service for docker infra') } peerAddresses = Chaincode.parser.commitStepDiscoverPeers(discoverPeersResult) } return await this.commitSteps().commitOnInstance({ ...payload, orderer, peerAddresses }) } /** * @ignore */ public commitSteps () { return { discoverPeers: async (payload: ChaincodeCommitType): Promise<InfraRunnerResultType> => { logger.debug('commit chaincode step 1 (discover peers)') return await (new Discover(this.config)).peers({ channel: payload.channelId }) }, discoverChannelConfig: async (payload: ChaincodeCommitType): Promise<InfraRunnerResultType> => { logger.debug('commit chaincode step 2 (discover channel config)') return await (new Discover(this.config)).channelConfig({ channel: payload.channelId }) }, commitOnInstance: async (payload: ChaincodeCommitStepCommitOnInstanceType): Promise<InfraRunnerResultType> => { logger.debug('commit chaincode step 3 (commit)') return await (new FabricInstance(this.config, this.infra)).commitChaincode(payload.channelId, payload.chaincodeName.replace('_', '-'), payload.chaincodeVersion, payload.initRequired, payload.orderer, payload.peerAddresses) }, } } /** * @description 查詢已發布的chaincode */ public async getCommittedChaincode (channelId: string): Promise<InfraRunnerResultType> { logger.debug('Get committed chaincode') return await (new FabricInstance(this.config, this.infra)).queryCommittedChaincode(channelId) } }
the_stack
import { ServiceType } from "@protobuf-ts/runtime-rpc"; import type { BinaryWriteOptions } from "@protobuf-ts/runtime"; import type { IBinaryWriter } from "@protobuf-ts/runtime"; import { WireType } from "@protobuf-ts/runtime"; import type { BinaryReadOptions } from "@protobuf-ts/runtime"; import type { IBinaryReader } from "@protobuf-ts/runtime"; import { UnknownFieldHandler } from "@protobuf-ts/runtime"; import type { PartialMessage } from "@protobuf-ts/runtime"; import { reflectionMergePartial } from "@protobuf-ts/runtime"; import { MESSAGE_TYPE } from "@protobuf-ts/runtime"; import { MessageType } from "@protobuf-ts/runtime"; /** * WriteRawRequest writes a pprof profile for a given tenant * * @generated from protobuf message parca.profilestore.v1alpha1.WriteRawRequest */ export interface WriteRawRequest { /** * tenant is the given tenant to store the pprof profile under * * @deprecated * @generated from protobuf field: string tenant = 1 [deprecated = true]; */ tenant: string; /** * series is a set raw pprof profiles and accompanying labels * * @generated from protobuf field: repeated parca.profilestore.v1alpha1.RawProfileSeries series = 2; */ series: RawProfileSeries[]; /** * normalized is a flag indicating if the addresses in the profile is normalized for position independent code * * @generated from protobuf field: bool normalized = 3; */ normalized: boolean; } /** * WriteRawResponse is the empty response * * @generated from protobuf message parca.profilestore.v1alpha1.WriteRawResponse */ export interface WriteRawResponse { } /** * RawProfileSeries represents the pprof profile and its associated labels * * @generated from protobuf message parca.profilestore.v1alpha1.RawProfileSeries */ export interface RawProfileSeries { /** * LabelSet is the key value pairs to identify the corresponding profile * * @generated from protobuf field: parca.profilestore.v1alpha1.LabelSet labels = 1; */ labels?: LabelSet; /** * samples are the set of profile bytes * * @generated from protobuf field: repeated parca.profilestore.v1alpha1.RawSample samples = 2; */ samples: RawSample[]; } /** * Label is a key value pair of identifiers * * @generated from protobuf message parca.profilestore.v1alpha1.Label */ export interface Label { /** * name is the label name * * @generated from protobuf field: string name = 1; */ name: string; /** * value is the value for the label name * * @generated from protobuf field: string value = 2; */ value: string; } /** * LabelSet is a group of labels * * @generated from protobuf message parca.profilestore.v1alpha1.LabelSet */ export interface LabelSet { /** * labels are the grouping of labels * * @generated from protobuf field: repeated parca.profilestore.v1alpha1.Label labels = 1; */ labels: Label[]; } /** * RawSample is the set of bytes that correspond to a pprof profile * * @generated from protobuf message parca.profilestore.v1alpha1.RawSample */ export interface RawSample { /** * raw_profile is the set of bytes of the pprof profile * * @generated from protobuf field: bytes raw_profile = 1; */ rawProfile: Uint8Array; } // @generated message type with reflection information, may provide speed optimized methods class WriteRawRequest$Type extends MessageType<WriteRawRequest> { constructor() { super("parca.profilestore.v1alpha1.WriteRawRequest", [ { no: 1, name: "tenant", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "series", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => RawProfileSeries }, { no: 3, name: "normalized", kind: "scalar", T: 8 /*ScalarType.BOOL*/ } ]); } create(value?: PartialMessage<WriteRawRequest>): WriteRawRequest { const message = { tenant: "", series: [], normalized: false }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<WriteRawRequest>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: WriteRawRequest): WriteRawRequest { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* string tenant = 1 [deprecated = true];*/ 1: message.tenant = reader.string(); break; case /* repeated parca.profilestore.v1alpha1.RawProfileSeries series */ 2: message.series.push(RawProfileSeries.internalBinaryRead(reader, reader.uint32(), options)); break; case /* bool normalized */ 3: message.normalized = reader.bool(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: WriteRawRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* string tenant = 1 [deprecated = true]; */ if (message.tenant !== "") writer.tag(1, WireType.LengthDelimited).string(message.tenant); /* repeated parca.profilestore.v1alpha1.RawProfileSeries series = 2; */ for (let i = 0; i < message.series.length; i++) RawProfileSeries.internalBinaryWrite(message.series[i], writer.tag(2, WireType.LengthDelimited).fork(), options).join(); /* bool normalized = 3; */ if (message.normalized !== false) writer.tag(3, WireType.Varint).bool(message.normalized); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.profilestore.v1alpha1.WriteRawRequest */ export const WriteRawRequest = new WriteRawRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class WriteRawResponse$Type extends MessageType<WriteRawResponse> { constructor() { super("parca.profilestore.v1alpha1.WriteRawResponse", []); } create(value?: PartialMessage<WriteRawResponse>): WriteRawResponse { const message = {}; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<WriteRawResponse>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: WriteRawResponse): WriteRawResponse { return target ?? this.create(); } internalBinaryWrite(message: WriteRawResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.profilestore.v1alpha1.WriteRawResponse */ export const WriteRawResponse = new WriteRawResponse$Type(); // @generated message type with reflection information, may provide speed optimized methods class RawProfileSeries$Type extends MessageType<RawProfileSeries> { constructor() { super("parca.profilestore.v1alpha1.RawProfileSeries", [ { no: 1, name: "labels", kind: "message", T: () => LabelSet }, { no: 2, name: "samples", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => RawSample } ]); } create(value?: PartialMessage<RawProfileSeries>): RawProfileSeries { const message = { samples: [] }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<RawProfileSeries>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: RawProfileSeries): RawProfileSeries { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* parca.profilestore.v1alpha1.LabelSet labels */ 1: message.labels = LabelSet.internalBinaryRead(reader, reader.uint32(), options, message.labels); break; case /* repeated parca.profilestore.v1alpha1.RawSample samples */ 2: message.samples.push(RawSample.internalBinaryRead(reader, reader.uint32(), options)); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: RawProfileSeries, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* parca.profilestore.v1alpha1.LabelSet labels = 1; */ if (message.labels) LabelSet.internalBinaryWrite(message.labels, writer.tag(1, WireType.LengthDelimited).fork(), options).join(); /* repeated parca.profilestore.v1alpha1.RawSample samples = 2; */ for (let i = 0; i < message.samples.length; i++) RawSample.internalBinaryWrite(message.samples[i], writer.tag(2, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.profilestore.v1alpha1.RawProfileSeries */ export const RawProfileSeries = new RawProfileSeries$Type(); // @generated message type with reflection information, may provide speed optimized methods class Label$Type extends MessageType<Label> { constructor() { super("parca.profilestore.v1alpha1.Label", [ { no: 1, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "value", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value?: PartialMessage<Label>): Label { const message = { name: "", value: "" }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<Label>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Label): Label { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* string name */ 1: message.name = reader.string(); break; case /* string value */ 2: message.value = reader.string(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: Label, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* string name = 1; */ if (message.name !== "") writer.tag(1, WireType.LengthDelimited).string(message.name); /* string value = 2; */ if (message.value !== "") writer.tag(2, WireType.LengthDelimited).string(message.value); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.profilestore.v1alpha1.Label */ export const Label = new Label$Type(); // @generated message type with reflection information, may provide speed optimized methods class LabelSet$Type extends MessageType<LabelSet> { constructor() { super("parca.profilestore.v1alpha1.LabelSet", [ { no: 1, name: "labels", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => Label } ]); } create(value?: PartialMessage<LabelSet>): LabelSet { const message = { labels: [] }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<LabelSet>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: LabelSet): LabelSet { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* repeated parca.profilestore.v1alpha1.Label labels */ 1: message.labels.push(Label.internalBinaryRead(reader, reader.uint32(), options)); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: LabelSet, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* repeated parca.profilestore.v1alpha1.Label labels = 1; */ for (let i = 0; i < message.labels.length; i++) Label.internalBinaryWrite(message.labels[i], writer.tag(1, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.profilestore.v1alpha1.LabelSet */ export const LabelSet = new LabelSet$Type(); // @generated message type with reflection information, may provide speed optimized methods class RawSample$Type extends MessageType<RawSample> { constructor() { super("parca.profilestore.v1alpha1.RawSample", [ { no: 1, name: "raw_profile", kind: "scalar", T: 12 /*ScalarType.BYTES*/ } ]); } create(value?: PartialMessage<RawSample>): RawSample { const message = { rawProfile: new Uint8Array(0) }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<RawSample>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: RawSample): RawSample { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* bytes raw_profile */ 1: message.rawProfile = reader.bytes(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: RawSample, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* bytes raw_profile = 1; */ if (message.rawProfile.length) writer.tag(1, WireType.LengthDelimited).bytes(message.rawProfile); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.profilestore.v1alpha1.RawSample */ export const RawSample = new RawSample$Type(); /** * @generated ServiceType for protobuf service parca.profilestore.v1alpha1.ProfileStoreService */ export const ProfileStoreService = new ServiceType("parca.profilestore.v1alpha1.ProfileStoreService", [ { name: "WriteRaw", options: { "google.api.http": { post: "/profiles/writeraw", body: "*" } }, I: WriteRawRequest, O: WriteRawResponse } ]);
the_stack
import { scaleQuantize, scaleOrdinal, scaleLinear } from 'd3-scale'; import { hsl, rgb } from 'd3-color'; export const visaColors = { pri_grey: '#5C5C5C', sec_blue: '#003ea9', sec_orange: '#ef8400', sec_yellow: '#ffd700', comp_blue: '#2bb4da', comp_green: '#00a25e', supp_pink: '#ae48b4', supp_purple: '#7f48b4', supp_green: '#649f4a', supp_red: '#a50026', // for data viz component base_grey: '#D7D7DE', light_text: '#ffffff', grey_text: '#565656', dark_text: '#222222', // blue to black theme oss_blue: '#0051dc', oss_light_blue: '#7FA8ED', oss_dark_grey: '#363636', oss_light_grey: '#D7D7D7', // for categorical palettes categorical_blue: '#226092', categorical_light_blue: '#7c99b1', categorical_blue_text: '#164d79', categorical_purple: '#796aaf', categorical_light_purple: '#cacae7', categorical_purple_text: '#66589b', categorical_olive: '#829e46', categorical_light_olive: '#abb798', categorical_olive_text: '#498329', categorical_grey: '#7a6763', categorical_light_grey: '#a19491', categorical_grey_text: '#6e5a55', categorical_rose: '#c18174', categorical_light_rose: '#e7c0b8', categorical_rose_text: '#954737', categorical_brown: '#43312d', categorical_light_brown: '#624c48', categorical_brown_text: '#43312d' }; export function darkerColor(color) { let hexColor = visaColors[color] || color; return hsl(hexColor) .darker(1.5) .hex(); } export function brighterColor(color) { let hexColor = visaColors[color] || color; let brighterScale = scaleLinear() .domain([0, 0.45]) .range([4, 2]); return hsl(hexColor) .brighter(brighterScale(hsl(hexColor).l)) .hex(); // return "white" } export function outlineColor(color) { let hexColor = visaColors[color] || color; return hsl(hexColor).l > 0.4 ? darkerColor(hexColor) : brighterColor(hexColor); } const sequentialColorIndex = [ [7], [7], [2, 6], [0, 3, 6], [0, 2, 4, 6], [0, 1, 3, 5, 7], [1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7] ]; const divergingColorIndex = [ [0], [0], [0, 9], [0, 4, 9], [0, 3, 6, 9], [0, 2, 4, 6, 9], [0, 2, 4, 5, 7, 9], [0, 1, 2, 4, 7, 8, 9], [0, 1, 2, 3, 6, 7, 8, 9], [0, 1, 2, 3, 4, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ]; const categoricalColorIndex = [ [0], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6], // 1- 7 [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] //8-11 ]; export function getColors(colorPalette, dataRange) { const colorArr = []; colorArr['single_blue'] = [visaColors.categorical_blue]; colorArr['single_brown'] = [visaColors.categorical_brown]; colorArr['single_grey'] = [visaColors.pri_grey]; colorArr['single_secBlue'] = [visaColors.sec_blue]; colorArr['single_secOrange'] = [visaColors.sec_orange]; colorArr['single_compBlue'] = [visaColors.comp_blue]; colorArr['single_compGreen'] = [visaColors.comp_green]; colorArr['single_suppPink'] = [visaColors.supp_pink]; colorArr['single_suppPurple'] = [visaColors.supp_purple]; colorArr['single_suppGreen'] = [visaColors.supp_green]; colorArr['single_ossBlue'] = [visaColors.oss_blue]; colorArr['single_ossLightBlue'] = [visaColors.oss_light_blue]; colorArr['single_ossGrey'] = [visaColors.oss_dark_grey]; colorArr['single_ossLightGrey'] = [visaColors.oss_light_grey]; colorArr['single_categorical_blue'] = [visaColors.categorical_blue]; colorArr['single_categorical_light_blue'] = [visaColors.categorical_light_blue]; colorArr['single_categorical_blue_text'] = [visaColors.categorical_blue_text]; colorArr['single_categorical_purple'] = [visaColors.categorical_purple]; colorArr['single_categorical_light_purple'] = [visaColors.categorical_light_purple]; colorArr['single_categorical_purple_text'] = [visaColors.categorical_purple_text]; colorArr['single_categorical_olive'] = [visaColors.categorical_olive]; colorArr['single_categorical_light_olive'] = [visaColors.categorical_light_olive]; colorArr['single_categorical_olive_text'] = [visaColors.categorical_olive_text]; colorArr['single_categorical_grey'] = [visaColors.categorical_grey]; colorArr['single_categorical_light_grey'] = [visaColors.categorical_light_grey]; colorArr['single_categorical_grey_text'] = [visaColors.categorical_grey_text]; colorArr['single_categorical_rose'] = [visaColors.categorical_rose]; colorArr['single_categorical_light_rose'] = [visaColors.categorical_light_rose]; colorArr['single_categorical_rose_text'] = [visaColors.categorical_rose_text]; colorArr['single_categorical_brown'] = [visaColors.categorical_brown]; colorArr['single_categorical_light_brown'] = [visaColors.categorical_light_brown]; colorArr['single_categorical_brown_text'] = [visaColors.categorical_brown_text]; colorArr['sequential_grey'] = [ '#f2f2f2', '#d7d7d7', '#bdbdbd', '#a3a3a3', '#898989', '#717171', '#595959', '#434343', '#2e2e2e' ]; colorArr['sequential_secBlue'] = [ '#ecf9f9', '#c0e0f1', '#91c8ea', '#57b0e2', '#0c96d7', '#1778c7', '#145bb8', '#003da8', '#002c76' ]; colorArr['sequential_secOrange'] = [ '#fee9c7', '#ffc78d', '#faa654', '#ef8506', '#e36001', '#c04e04', '#9c3d05', '#7b2c05', '#5c1c00' ]; colorArr['sequential_compBlue'] = [ '#f3fbfe', '#bde3f2', '#81cae6', '#2ab1d7', '#2294b5', '#1b7994', '#135d74', '#0c4557', '#062c3a' ]; colorArr['sequential_compGreen'] = [ '#eafed4', '#bae7b4', '#89cf95', '#53b677', '#009e5c', '#00814b', '#00663b', '#004b2b', '#00321d' ]; colorArr['sequential_suppPink'] = [ '#f8f4f9', '#f3cef3', '#eca6ed', '#e37ce6', '#d74adf', '#aa45af', '#86378a', '#632a66', '#421b44' ]; colorArr['sequential_suppPurple'] = [ '#f7fcfd', '#e3daec', '#cebadd', '#b59acc', '#977ebb', '#7367a5', '#554f87', '#423667', '#331d48' ]; colorArr['sequential_suppGreen'] = [ '#ffffe5', '#deebc3', '#bed6a2', '#9ec283', '#7fae61', '#5e9a48', '#448340', '#286e3a', '#005a32' ]; colorArr['diverging_RtoB'] = [ '#a50026', '#c7422a', '#df7232', '#f3a14b', '#ffcf7b', '#afdbf1', '#7ab7e5', '#5390d1', '#386bb6', '#2d4697' ]; colorArr['diverging_RtoG'] = [ '#972800', '#ba4d18', '#df7131', '#f0a04e', '#fecd6e', '#bcdeba', '#72c1a7', '#529f8e', '#307e75', '#015e5d' ]; colorArr['diverging_GtoP'] = [ '#194f46', '#377258', '#57976f', '#7abb8c', '#a6e0b5', '#bbd4f9', '#aba6ea', '#9879d2', '#7655b2', '#3c3f85' ]; colorArr['categorical'] = ['#7c99b1', '#cacae7', '#abb798', '#a19491', '#e7c0b8', '#624c48']; colorArr['categorical_light'] = ['#7c99b1', '#cacae7', '#abb798', '#a19491', '#e7c0b8', '#624c48']; colorArr['categorical_dark'] = ['#226092', '#796aaf', '#829e46', '#7a6763', '#c18174', '#43312d']; colorArr['categorical_text'] = ['#164d79', '#66589b', '#498329', '#6e5a55', '#954737', '#43312d']; const selectedColor = typeof colorPalette === 'string' ? colorArr[colorPalette] : colorPalette; if (Array.isArray(dataRange)) { // range of data keys is passed let colorScale; if (typeof dataRange[0] === 'string') { let newColorArr = []; let colorIndex = colorPalette.includes('diverging') ? divergingColorIndex : colorPalette.includes('categorical') ? categoricalColorIndex : sequentialColorIndex; typeof colorPalette === 'string' && colorIndex[dataRange.length] ? colorIndex[dataRange.length].map(key => { selectedColor[key] ? newColorArr.push(selectedColor[key]) : newColorArr.push(selectedColor[0]); }) : (newColorArr = selectedColor); colorScale = scaleOrdinal() .domain(dataRange) .range(newColorArr); } else { colorScale = scaleQuantize() .domain(dataRange) .range(selectedColor); } return colorScale; } else if (Number.isInteger(dataRange)) { // number of colors is passed let newColorArr = []; let colorIndex = colorPalette.includes('diverging') ? divergingColorIndex : colorPalette.includes('categorical') ? categoricalColorIndex : sequentialColorIndex; colorIndex[dataRange] ? colorIndex[dataRange].map(key => { selectedColor[key] ? newColorArr.push(selectedColor[key]) : newColorArr.push(selectedColor[0]); }) : (newColorArr = selectedColor); return newColorArr; } else return selectedColor; } /** * This function will find up to two strokes for a given input color. This is only designed for accessible graphics. * * This function is designed with VGAR compliance in mind, using the WCAG 2.1 contrast ratio formula to find the highest contrast stroke colors possible for a graphical element. Formula: https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests * * @see uses two visa/visa-charts-utils functions: calculateLuminance() and calculateRelativeLuminance(). * * @param {string} fillColor Any valid HTML string may be passed for color: 'red', '#ffffff', 'rgb(12,200,15)', even 'hsl(0,60%,50%)'. Alpha values will be ignored (for accessibility purposes, web authors are strongly encouraged to avoid using opacity or alpha channels in styling). * * @return {string[]} Returns an array containing color hex values as strings. The first array position is always contrasted against the fill color. The second array position is sometimes empty but if it has a value it will always be the original color. The second value only populates if the original color has more than 3:1 contrast against white. */ export function getAccessibleStrokes(fillColor: string) { const strokes = []; strokes.push(getContrastingStroke(fillColor)); const luminanceToWhite = calculateRelativeLuminance(calculateLuminance(fillColor), 1); if (luminanceToWhite >= 3) { strokes.push(fillColor); } return strokes; } // experimental function // early tests show that this method can still fail to produce a valid stroke // this is abandoned until further need export function getRecursiveStroke(foreground: string, background: string) { const extents = {}; const foregroundLuminance = calculateLuminance(foreground); const backgroundLuminance = calculateLuminance(background); const foregroundToWhite = calculateRelativeLuminance(foregroundLuminance, 1); const backgroundToWhite = calculateRelativeLuminance(backgroundLuminance, 1); extents[foreground] = {}; extents[background] = {}; extents[foreground].min = foregroundToWhite - 3 > 1 ? foregroundToWhite - 3 : 1; extents[foreground].max = foregroundToWhite + 3 < 21 ? foregroundToWhite + 3 : 21; extents[background].min = backgroundToWhite - 3 > 1 ? backgroundToWhite - 3 : 1; extents[background].max = backgroundToWhite + 3 < 21 ? backgroundToWhite + 3 : 21; const darkerColor = extents[foreground].max >= extents[background].max ? foreground : background; const lighterColor = extents[foreground].min <= extents[background].min ? foreground : background; const lightestValue = extents[lighterColor].min; const darkestValue = extents[darkerColor].max; const gaps = { dark: 21 - darkestValue > 0 ? 21 - darkestValue : 0, light: lightestValue - 1 > 0 ? lightestValue - 1 : 0 }; let foundStroke = ''; let operation = ''; let target = ''; if (lighterColor === foreground && extents[foreground].max < extents[background].min) { // try darkening foreground into the inner gap space operation = 'darken'; target = foreground; } else if (darkerColor === foreground && extents[foreground].min > extents[background].max) { // try lightening foreground into the inner gap space operation = 'lighten'; target = foreground; } if (operation) { const colorAttempt = processColor(target, operation, 3); const attemptLuminance = calculateLuminance(colorAttempt); foundStroke = calculateRelativeLuminance(backgroundLuminance, attemptLuminance) >= 3 ? colorAttempt : 0; } if (!foundStroke) { // the inner gap didn't work, must try exterior gaps if (darkerColor === foreground && gaps.dark) { // try darkening foreground into the outer gap space operation = 'darken'; target = foreground; } else if (lighterColor === foreground && gaps.light) { // try lightening foreground into the outer gap space operation = 'lighten'; target = foreground; } foundStroke = operation ? processColor(target, operation, 3) : ''; } if (!foundStroke) { // must try exterior gaps using the background color if (gaps.dark > gaps.light) { // try darkening foreground into the gap space operation = 'darken'; target = background; } else { // try lighting foreground into the gap space operation = 'lighten'; target = background; } foundStroke = operation ? processColor(target, operation, 3) : ''; } if (!foundStroke) { foundStroke = foreground; } return foundStroke; } function processColor(color: string, operation: string, contrast: number) { const originalLuminance = calculateLuminance(color); const hslObject = hsl(color); let limitReached = false; let impossible = false; if (operation === 'darken') { hslObject.l -= 0.01; while ( calculateRelativeLuminance(calculateLuminance(hslObject.hex()), originalLuminance) < contrast && !impossible ) { hslObject.l -= 0.01; if (limitReached) { impossible = true; } if (hslObject.l < 0) { hslObject.l = 0; limitReached = true; } } } else { hslObject.l += 0.01; while ( calculateRelativeLuminance(calculateLuminance(hslObject.hex()), originalLuminance) < contrast && !impossible ) { hslObject.l += 0.01; if (limitReached) { impossible = true; } if (hslObject.l > 1) { hslObject.l = 1; limitReached = true; } } } return !impossible ? hslObject.hex() : ''; } export function getContrastingStroke(fillColor: string) { const originalLuminance = calculateLuminance(fillColor); const luminanceToWhite = calculateRelativeLuminance(originalLuminance, 1); const hslObject = hsl(fillColor); if (luminanceToWhite < 3) { hslObject.l -= 0.01; while ( hslObject.l > 0 && calculateRelativeLuminance(calculateLuminance(hslObject.hex()), originalLuminance) < 3 && hslObject.l ) { hslObject.l -= 0.01; if (hslObject.l < 0) { hslObject.l = 0; } } } else { hslObject.l += 0.01; while ( calculateRelativeLuminance(calculateLuminance(hslObject.hex()), originalLuminance) < 3 && hslObject.l !== 1 ) { hslObject.l += 0.01; if (hslObject.l > 1) { hslObject.l = 1; } } } return hslObject.hex(); } export function ensureTextContrast(textColor: string) { const originalLuminance = calculateLuminance(textColor); const luminanceToWhite = calculateRelativeLuminance(originalLuminance, 1); const hslObject = hsl(textColor); if (luminanceToWhite < 4.5) { hslObject.l -= 0.01; while (hslObject.l > 0 && calculateRelativeLuminance(calculateLuminance(hslObject.hex()), 1) < 4.5 && hslObject.l) { hslObject.l -= 0.01; if (hslObject.l < 0) { hslObject.l = 0; } } } return hslObject.hex(); } /** * This function will calculate the perceived luminance of a valid HTML color. * * Formula and specification from WCAG 2.0: https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests. * * @param {string} color Any valid HTML string may be passed for color: 'red', '#ffffff', 'rgb(12,200,15)', even 'hsl(0,60%,50%)'. Alpha values will be ignored (for accessibility purposes, web authors are strongly encouraged to avoid using opacity or alpha channels in styling). * * @return {number} Returns a luminance value between 0 (black, no luminance) and 1 (white, full luminance). */ export function calculateLuminance(color: string) { function calcColorScore(normalizedColor) { return normalizedColor <= 0.03928 ? normalizedColor / 12.92 : Math.pow((normalizedColor + 0.055) / 1.055, 2.4); } const rgbObject = rgb(color); const rLuminance = 0.2126 * calcColorScore(rgbObject.r / 255); const gLuminance = 0.7152 * calcColorScore(rgbObject.g / 255); const bLuminance = 0.0722 * calcColorScore(rgbObject.b / 255); return rLuminance + gLuminance + bLuminance; } /** * This function will calculate the contrast ratio between two luminance values. * * Input luminance values may be supplied in any order. The output will always place the highest value as the numerator. Formula and specification from WCAG 2.0: https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests. * * @see visa/visa-charts-utils: calculateLuminance() to convert an HTML color into a luminance value (which is the expected input of this function). * * @param {number} luminance1 This value must be the calculated luminance of a color. * @param {number} luminance2 This value must be the calculated luminance of another color. * * @return {number} Returns a contrast ratio between luminance values ranging from 1 (identical luminance) to 21 (complete opposites - black against white). */ export function calculateRelativeLuminance(luminance1: number, luminance2: number) { return luminance1 >= luminance2 ? (luminance1 + 0.05) / (luminance2 + 0.05) : (luminance2 + 0.05) / (luminance1 + 0.05); } /** * This function will find the most appropriate text color (foreground) given a background color. * * This function is designed with VGAR compliance in mind, using the WCAG 2 contrast ratio formula to find the highest contrast text possible. Formula: https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests * * @see uses two visa/visa-charts-utils functions: calculateLuminance() and calculateRelativeLuminance(). * * @param {string} backgroundColor Any valid HTML string may be passed for color: 'red', '#ffffff', 'rgb(12,200,15)', even 'hsl(0,60%,50%)'. Alpha values will be ignored (for accessibility purposes, web authors are strongly encouraged to avoid using opacity or alpha channels in styling). * * @return {string} Returns a color hex value, either '#ffffff' (white) or '#222222' (lead). */ export function autoTextColor(backgroundColor: string) { const lightLuminance = calculateLuminance(visaColors['light_text']); const greyLuminance = calculateLuminance(visaColors['dark_text']); const backgroundLuminance = calculateLuminance(backgroundColor); const relativeToLight = calculateRelativeLuminance(lightLuminance, backgroundLuminance); const relativeToGrey = calculateRelativeLuminance(greyLuminance, backgroundLuminance); return relativeToGrey < 4.5 && relativeToLight < 4.5 ? visaColors['dark_text'] : relativeToGrey > relativeToLight ? visaColors['dark_text'] : visaColors['light_text']; } export function convertVisaColor(colorArr) { if (colorArr[0].includes('_')) { colorArr.map((c, i) => (colorArr[i] = visaColors[c])); } return colorArr; } export function visaColorToHex(color) { let hexColor = visaColors[color] || color; return hexColor; }
the_stack
import { GraphQLString, GraphQLList, GraphQLNonNull, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLInterfaceType, GraphQLInputObjectType, GraphQLObjectType, graphql, } from '../graphql'; import { schemaComposer, SchemaComposer } from '..'; import { InterfaceTypeComposer } from '../InterfaceTypeComposer'; import { InputTypeComposer } from '../InputTypeComposer'; import { ObjectTypeComposer } from '../ObjectTypeComposer'; import { ScalarTypeComposer } from '../ScalarTypeComposer'; import { EnumTypeComposer } from '../EnumTypeComposer'; import { UnionTypeComposer } from '../UnionTypeComposer'; import { NonNullComposer } from '../NonNullComposer'; import { ListComposer } from '../ListComposer'; import { ThunkComposer } from '../ThunkComposer'; import { graphqlVersion } from '../utils/graphqlVersion'; import { dedent } from '../utils/dedent'; beforeEach(() => { schemaComposer.clear(); }); describe('InterfaceTypeComposer', () => { let objectType: GraphQLInterfaceType; let iftc: InterfaceTypeComposer<any, any>; beforeEach(() => { objectType = new GraphQLInterfaceType({ name: 'Readable', fields: { field1: { type: GraphQLString }, field2: { type: GraphQLString }, }, }); iftc = new InterfaceTypeComposer(objectType, schemaComposer); }); describe('fields manipulation', () => { it('getFields()', () => { const fieldNames = Object.keys(iftc.getFields()); expect(fieldNames).toEqual(expect.arrayContaining(['field1', 'field2'])); const iftc2 = schemaComposer.createInterfaceTC('SomeType'); expect(iftc2.getFields()).toEqual({}); }); describe('getField()', () => { it('should return field config', () => { expect(iftc.getFieldType('field1')).toBe(GraphQLString); }); it('should throw error if field does not exist', () => { expect(() => iftc.getField('missing')).toThrowError(/Cannot get field.*does not exist/); }); }); describe('setFields()', () => { it('should add field with standard config', () => { iftc.setFields({ field3: { type: GraphQLString }, }); const fields = iftc.getType().getFields(); expect(Object.keys(fields)).toContain('field3'); expect(fields.field3.type).toBe(GraphQLString); }); it('should add fields with converting types from string to object', () => { iftc.setFields({ field3: { type: 'String' }, field4: { type: '[Int]' }, field5: 'Boolean!', }); expect(iftc.getFieldType('field3')).toBe(GraphQLString); expect(iftc.getFieldType('field4')).toBeInstanceOf(GraphQLList); expect((iftc.getFieldType('field4') as any).ofType).toBe(GraphQLInt); expect(iftc.getFieldType('field5')).toBeInstanceOf(GraphQLNonNull); expect((iftc.getFieldType('field5') as any).ofType).toBe(GraphQLBoolean); }); it('should add fields with converting args types from string to object', () => { iftc.setFields({ field3: { type: 'String', args: { arg1: { type: 'String!' }, arg2: '[Float]', arg3: (sc) => { expect(sc).toBeInstanceOf(SchemaComposer); return 'String'; }, }, }, }); expect(iftc.getFieldArgType('field3', 'arg1')).toBeInstanceOf(GraphQLNonNull); expect((iftc.getFieldArgType('field3', 'arg1') as any).ofType).toBe(GraphQLString); expect(iftc.getFieldArgType('field3', 'arg2')).toBeInstanceOf(GraphQLList); expect((iftc.getFieldArgType('field3', 'arg2') as any).ofType).toBe(GraphQLFloat); expect(iftc.getFieldArgTypeName('field3', 'arg1')).toBe('String!'); expect(iftc.getFieldArgTypeName('field3', 'arg2')).toBe('[Float]'); expect(iftc.getFieldArgTypeName('field3', 'arg3')).toBe('String'); }); it('should add projection via `setField` and `addFields`', () => { iftc.setFields({ field3: { type: GraphQLString, projection: { field1: true, field2: true }, }, field4: { type: GraphQLString }, field5: { type: GraphQLString, projection: { field4: true } }, }); }); it('accept types as function', () => { const typeAsFn = (sc: SchemaComposer<any>) => { expect(sc).toBeInstanceOf(SchemaComposer); return GraphQLString; }; iftc.setFields({ field6: { type: typeAsFn }, }); expect(iftc.getField('field6').type).toBeInstanceOf(ThunkComposer); expect(iftc.getFieldType('field6')).toBe(GraphQLString); // show provide unwrapped/unhoisted type for graphql if (graphqlVersion >= 14) { expect((iftc.getType() as any)._fields().field6.type).toBe(GraphQLString); } else { expect((iftc.getType() as any)._typeConfig.fields().field6.type).toBe(GraphQLString); } }); it('accept fieldConfig as function', () => { iftc.setFields({ input4: (sc) => { expect(sc).toBeInstanceOf(SchemaComposer); return { type: 'String' }; }, }); // show provide unwrapped/unhoisted type for graphql if (graphqlVersion >= 14) { expect((iftc.getType() as any)._fields().input4.type).toBe(GraphQLString); } else { expect((iftc.getType() as any)._typeConfig.fields().input4.type).toBe(GraphQLString); } }); }); it('addFields()', () => { iftc.addFields({ field3: { type: GraphQLString }, field4: { type: '[Int]' }, field5: 'Boolean!', }); expect(iftc.getFieldType('field3')).toBe(GraphQLString); expect(iftc.getFieldType('field4')).toBeInstanceOf(GraphQLList); expect((iftc.getFieldType('field4') as any).ofType).toBe(GraphQLInt); expect(iftc.getFieldType('field5')).toBeInstanceOf(GraphQLNonNull); expect((iftc.getFieldType('field5') as any).ofType).toBe(GraphQLBoolean); expect(iftc.getFieldTypeName('field3')).toBe('String'); expect(iftc.getFieldTypeName('field4')).toBe('[Int]'); expect(iftc.getFieldTypeName('field5')).toBe('Boolean!'); }); describe('removeField()', () => { it('should remove one field', () => { iftc.removeField('field1'); expect(iftc.getFieldNames()).toEqual(expect.arrayContaining(['field2'])); }); it('should remove list of fields', () => { iftc.removeField(['field1', 'field2']); expect(iftc.getFieldNames()).toEqual(expect.arrayContaining([])); }); it('should remove field via dot-notation', () => { schemaComposer.addTypeDefs(` interface IFace { field1: [SubType!] field2: Int field3: Int } type SubType { subField1: SubSubType subField2: Int subField3: Int } type SubSubType { subSubField1: Int subSubField2: Int } `); schemaComposer .getIFTC('IFace') .removeField([ 'field1.subField1.subSubField1', 'field1.subField1.nonexistent', 'field1.nonexistent.nonexistent', 'field1.subField3', 'field2', '', '..', ]); expect(schemaComposer.getIFTC('IFace').toSDL({ deep: true, omitDescriptions: true })) .toEqual(dedent` interface IFace { field1: [SubType!] field3: Int } type SubType { subField1: SubSubType subField2: Int } type SubSubType { subSubField2: Int } scalar Int `); }); }); describe('removeOtherFields()', () => { it('should remove one field', () => { iftc.removeOtherFields('field1'); expect(iftc.getFieldNames()).not.toEqual(expect.arrayContaining(['field2'])); expect(iftc.getFieldNames()).toEqual(expect.arrayContaining(['field1'])); }); it('should remove list of fields', () => { iftc.setField('field3', 'String'); iftc.removeOtherFields(['field1', 'field2']); expect(iftc.getFieldNames()).toEqual(expect.arrayContaining(['field1', 'field2'])); expect(iftc.getFieldNames()).not.toEqual(expect.arrayContaining(['field3'])); }); }); describe('reorderFields()', () => { it('should change fields order', () => { iftc.setFields({ f1: 'Int', f2: 'Int', f3: 'Int' }); expect(iftc.getFieldNames().join(',')).toBe('f1,f2,f3'); iftc.reorderFields(['f3', 'f2', 'f1']); expect(iftc.getFieldNames().join(',')).toBe('f3,f2,f1'); }); it('should append not listed fields', () => { iftc.setFields({ f1: 'Int', f2: 'Int', f3: 'Int' }); expect(iftc.getFieldNames().join(',')).toBe('f1,f2,f3'); iftc.reorderFields(['f3']); expect(iftc.getFieldNames().join(',')).toBe('f3,f1,f2'); }); it('should skip non existed fields', () => { iftc.setFields({ f1: 'Int', f2: 'Int', f3: 'Int' }); expect(iftc.getFieldNames().join(',')).toBe('f1,f2,f3'); iftc.reorderFields(['f22', 'f3', 'f55', 'f1', 'f2']); expect(iftc.getFieldNames().join(',')).toBe('f3,f1,f2'); }); }); describe('field arguments', () => { beforeEach(() => { iftc.extendField('field1', { args: { arg1: 'Int', arg2: 'String', }, }); }); it('getFieldArgs()', () => { const args = iftc.getFieldArgs('field1'); expect(Object.keys(args)).toEqual(['arg1', 'arg2']); expect(args.arg1.type.getType()).toBe(GraphQLInt); expect(iftc.getFieldArgType('field1', 'arg1')).toBe(GraphQLInt); expect(() => iftc.getFieldArgs('missingField')).toThrow(); }); it('hasFieldArg()', () => { expect(iftc.hasFieldArg('field1', 'arg1')).toBeTruthy(); expect(iftc.hasFieldArg('field1', 'arg222')).toBeFalsy(); expect(iftc.hasFieldArg('missingField', 'arg1')).toBeFalsy(); }); it('getFieldArg()', () => { expect(iftc.getFieldArg('field1', 'arg1')).toBeTruthy(); expect(() => iftc.getFieldArg('field1', 'arg222')).toThrow(/Argument does not exist/); expect(iftc.hasFieldArg('missingField', 'arg1')).toBeFalsy(); }); it('getFieldArgTC()', () => { iftc.setField('fieldWithArgs', { type: 'Int', args: { scalarArg: '[Int]', complexArg: `input SomeInput { a: Int, b: Int }`, }, }); expect(iftc.getFieldArgTC('fieldWithArgs', 'scalarArg')).toBeInstanceOf(ScalarTypeComposer); const argTC = iftc.getFieldArgTC('fieldWithArgs', 'complexArg'); expect(argTC).toBeInstanceOf(InputTypeComposer); // should return the same TC instance expect(iftc.getFieldArgITC('fieldWithArgs', 'complexArg')).toBe(argTC); expect(() => iftc.getFieldArgITC('fieldWithArgs', 'scalarArg')).toThrow( 'must be InputTypeComposer' ); }); }); describe('extendField()', () => { it('should extend existed fields', () => { iftc.setField('field3', { type: GraphQLString, projection: { field1: true, field2: true }, }); iftc.extendField('field3', { description: 'this is field #3', }); expect(iftc.getFieldConfig('field3').type).toBe(GraphQLString); expect(iftc.getFieldConfig('field3').description).toBe('this is field #3'); iftc.extendField('field3', { type: 'Int', }); expect(iftc.getFieldType('field3')).toBe(GraphQLInt); }); it('should extend field extensions', () => { iftc.setField('field3', { type: GraphQLString, extensions: { first: true }, }); iftc.extendField('field3', { description: 'this is field #3', extensions: { second: true }, }); expect(iftc.getFieldConfig('field3').extensions).toEqual({ first: true, second: true, }); }); it('should work with fieldConfig as string', () => { iftc.setField('field4', 'String'); iftc.extendField('field4', { description: 'this is field #4', }); expect(iftc.getFieldConfig('field4').type).toBe(GraphQLString); expect(iftc.getFieldConfig('field4').description).toBe('this is field #4'); }); it('should throw error if field does not exists', () => { expect(() => iftc.extendField('missing', { description: '123' })).toThrow( /Cannot extend field.*Field does not exist/ ); }); }); it('isFieldNonNull()', () => { iftc.setField('fieldNN', 'String'); expect(iftc.isFieldNonNull('fieldNN')).toBe(false); iftc.setField('fieldNN', 'String!'); expect(iftc.isFieldNonNull('fieldNN')).toBe(true); }); it('makeFieldNonNull()', () => { iftc.setField('fieldNN', 'String'); expect(iftc.getFieldType('fieldNN')).toBe(GraphQLString); // should wrap with GraphQLNonNull iftc.makeFieldNonNull('fieldNN'); expect(iftc.getFieldType('fieldNN')).toBeInstanceOf(GraphQLNonNull); expect((iftc.getFieldType('fieldNN') as any).ofType).toBe(GraphQLString); // should not wrap twice iftc.makeFieldNonNull('fieldNN'); expect(iftc.getFieldType('fieldNN')).toBeInstanceOf(GraphQLNonNull); expect((iftc.getFieldType('fieldNN') as any).ofType).toBe(GraphQLString); }); it('makeFieldNullable()', () => { iftc.setField('fieldNN', 'String!'); expect(iftc.getFieldType('fieldNN')).toBeInstanceOf(GraphQLNonNull); expect((iftc.getFieldType('fieldNN') as any).ofType).toBe(GraphQLString); // should unwrap GraphQLNonNull iftc.makeFieldNullable('fieldNN'); expect(iftc.getFieldType('fieldNN')).toBe(GraphQLString); // should work for already unwrapped type iftc.makeFieldNullable('fieldNN'); expect(iftc.getFieldType('fieldNN')).toBe(GraphQLString); }); it('check field Plural methods, wrap/unwrap from ListComposer', () => { iftc.setFields({ b1: { type: new GraphQLNonNull(GraphQLString) }, b2: { type: '[String]' }, b3: 'String!', b4: '[String!]!', }); expect(iftc.isFieldPlural('b1')).toBe(false); expect(iftc.isFieldPlural('b2')).toBe(true); expect(iftc.isFieldPlural('b3')).toBe(false); expect(iftc.isFieldPlural('b4')).toBe(true); expect(iftc.isFieldNonNull('b1')).toBe(true); expect(iftc.isFieldNonNull('b2')).toBe(false); expect(iftc.isFieldNonNull('b3')).toBe(true); expect(iftc.isFieldNonNull('b4')).toBe(true); iftc.makeFieldPlural(['b1', 'b2', 'b3', 'missing']); expect(iftc.isFieldPlural('b1')).toBe(true); expect(iftc.isFieldPlural('b2')).toBe(true); expect(iftc.isFieldPlural('b3')).toBe(true); iftc.makeFieldNonNull('b2'); expect(iftc.isFieldPlural('b2')).toBe(true); expect(iftc.isFieldNonNull('b2')).toBe(true); iftc.makeFieldNonPlural(['b2', 'b4', 'missing']); expect(iftc.isFieldPlural('b2')).toBe(false); expect(iftc.isFieldNonNull('b2')).toBe(true); expect(iftc.isFieldPlural('b4')).toBe(false); iftc.makeFieldNullable(['b2', 'b4', 'missing']); expect(iftc.isFieldNonNull('b2')).toBe(false); expect(iftc.isFieldNonNull('b4')).toBe(false); }); it('check Plural methods, wrap/unwrap from ListComposer', () => { iftc.setFields({ f: { type: 'Int', args: { b1: { type: new GraphQLNonNull(GraphQLString) }, b2: { type: '[String]' }, b3: 'String!', b4: '[String!]!', }, }, }); expect(iftc.isFieldArgPlural('f', 'b1')).toBe(false); expect(iftc.isFieldArgPlural('f', 'b2')).toBe(true); expect(iftc.isFieldArgPlural('f', 'b3')).toBe(false); expect(iftc.isFieldArgPlural('f', 'b4')).toBe(true); expect(iftc.isFieldArgNonNull('f', 'b1')).toBe(true); expect(iftc.isFieldArgNonNull('f', 'b2')).toBe(false); expect(iftc.isFieldArgNonNull('f', 'b3')).toBe(true); expect(iftc.isFieldArgNonNull('f', 'b4')).toBe(true); iftc.makeFieldArgPlural('f', ['b1', 'b2', 'b3', 'missing']); expect(iftc.isFieldArgPlural('f', 'b1')).toBe(true); expect(iftc.isFieldArgPlural('f', 'b2')).toBe(true); expect(iftc.isFieldArgPlural('f', 'b3')).toBe(true); iftc.makeFieldArgNonNull('f', 'b2'); expect(iftc.isFieldArgPlural('f', 'b2')).toBe(true); expect(iftc.isFieldArgNonNull('f', 'b2')).toBe(true); iftc.makeFieldArgNonPlural('f', ['b2', 'b4', 'missing']); expect(iftc.isFieldArgPlural('f', 'b2')).toBe(false); expect(iftc.isFieldArgNonNull('f', 'b2')).toBe(true); expect(iftc.isFieldArgPlural('f', 'b4')).toBe(false); iftc.makeFieldArgNullable('f', ['b2', 'b4', 'missing']); expect(iftc.isFieldArgNonNull('f', 'b2')).toBe(false); expect(iftc.isFieldArgNonNull('f', 'b4')).toBe(false); }); }); describe('interfaces manipulation', () => { if (graphqlVersion < 15) return; const iface = new GraphQLInterfaceType({ name: 'Node', description: '', fields: () => ({ id: { type: GraphQLInt } }), resolveType: () => ({} as any), }); const iface2 = new GraphQLInterfaceType({ name: 'Node2', description: '', fields: () => ({ id: { type: GraphQLInt } }), resolveType: () => ({} as any), }); const iface3 = InterfaceTypeComposer.create( ` interface SimpleObject { id: Int name: String } `, schemaComposer ); it('getInterfaces()', () => { const iftc1 = schemaComposer.createInterfaceTC(` interface MeAnother implements SimpleObject { id: Int name: String } `); expect(iftc1.getInterfaces()).toHaveLength(1); expect(iftc1.getInterfaces()[0].getTypeName()).toBe('SimpleObject'); }); it('hasInterface()', () => { const tc1 = schemaComposer.createObjectTC(` type MeAnother implements SimpleObject { id: Int name: String } `); expect(tc1.hasInterface('SimpleObject')).toBe(true); }); it('hasInterface() should work by name or ITC', () => { const MyIface = new GraphQLInterfaceType({ name: 'MyIface', description: '', fields: () => ({ id: { type: GraphQLInt } }), resolveType: () => ({} as any), }); iftc.addInterface(MyIface); expect(iftc.hasInterface('MyIface123')).toBeFalsy(); expect(iftc.hasInterface('MyIface')).toBeTruthy(); expect(iftc.hasInterface(MyIface)).toBeTruthy(); expect(iftc.hasInterface(InterfaceTypeComposer.create(MyIface, schemaComposer))).toBeTruthy(); iftc.addInterface(InterfaceTypeComposer.create('MyIface123', schemaComposer)); expect(iftc.hasInterface('MyIface123')).toBeTruthy(); }); it('addInterface()', () => { iftc.addInterface(iface); expect(iftc.getInterfaces()).toHaveLength(1); expect(iftc.hasInterface(iface)).toBe(true); iftc.addInterface(iface2); expect(iftc.getInterfaces()).toHaveLength(2); expect(iftc.hasInterface(iface)).toBe(true); expect(iftc.hasInterface(iface2)).toBe(true); iftc.addInterface((s: SchemaComposer<any>) => { expect(s).toBeInstanceOf(SchemaComposer); return iftc; }); expect(iftc.hasInterface(iftc)).toBe(true); }); it('removeInterface()', () => { iftc.addInterface(iface); iftc.addInterface(iface2); iftc.addInterface(iftc); expect(iftc.getInterfaces()).toHaveLength(3); expect(iftc.hasInterface(iface)).toBe(true); expect(iftc.hasInterface(iftc)).toBe(true); expect(iftc.hasInterface(iface2)).toBe(true); iftc.removeInterface(iface); iftc.removeInterface(iftc); expect(iftc.hasInterface(iface)).toBe(false); expect(iftc.hasInterface(iftc)).toBe(false); expect(iftc.hasInterface(iface2)).toBe(true); }); it('check proper interface definition in GraphQLType', () => { iftc.addInterface(iface); iftc.addInterface(iface2); iftc.addInterface(iface3); const gqType = iftc.getType(); const ifaces = gqType.getInterfaces(); expect(ifaces[0]).toBeInstanceOf(GraphQLInterfaceType); expect(ifaces[1]).toBeInstanceOf(GraphQLInterfaceType); expect(ifaces[2]).toBeInstanceOf(GraphQLInterfaceType); expect(ifaces[0].name).toBe('Node'); expect(ifaces[1].name).toBe('Node2'); expect(ifaces[2].name).toBe('SimpleObject'); }); }); describe('create() [static method]', () => { it('should create Interface by typeName as a string', () => { const myIFTC = schemaComposer.createInterfaceTC('TypeStub'); expect(myIFTC).toBeInstanceOf(InterfaceTypeComposer); expect(myIFTC.getType()).toBeInstanceOf(GraphQLInterfaceType); expect(myIFTC.getFields()).toEqual({}); }); it('should create Interface by type template string', () => { const myIFTC = schemaComposer.createInterfaceTC( ` interface TestTypeTpl { f1: String # Description for some required Int field f2: Int! } ` ); expect(myIFTC).toBeInstanceOf(InterfaceTypeComposer); expect(myIFTC.getTypeName()).toBe('TestTypeTpl'); expect(myIFTC.getFieldType('f1')).toBe(GraphQLString); expect(myIFTC.getFieldType('f2')).toBeInstanceOf(GraphQLNonNull); expect((myIFTC.getFieldType('f2') as any).ofType).toBe(GraphQLInt); }); it('should create TC by GraphQLInterfaceTypeConfig', () => { const myIFTC = schemaComposer.createInterfaceTC({ name: 'TestType', fields: { f1: { type: 'String', }, f2: 'Int!', }, }); expect(myIFTC).toBeInstanceOf(InterfaceTypeComposer); expect(myIFTC.getFieldType('f1')).toBe(GraphQLString); expect(myIFTC.getFieldType('f2')).toBeInstanceOf(GraphQLNonNull); expect((myIFTC.getFieldType('f2') as any).ofType).toBe(GraphQLInt); }); it('should create TC by ComposeInterfaceTypeConfig with non-existent types', () => { const myIFTC = schemaComposer.createInterfaceTC({ name: 'TestType', fields: { f1: { type: 'Type1', }, f2: 'Type2!', }, }); expect(myIFTC).toBeInstanceOf(InterfaceTypeComposer); expect(myIFTC.getField('f1').type.getTypeName()).toEqual('Type1'); expect(myIFTC.getField('f2').type.getTypeName()).toEqual('Type2!'); }); it('should create TC by GraphQLInterfaceTypeConfig with fields as Thunk', () => { const myIFTC = schemaComposer.createInterfaceTC({ name: 'TestType', fields: (() => ({ f1: { type: 'String', }, f2: 'Int!', })) as any, }); expect(myIFTC).toBeInstanceOf(InterfaceTypeComposer); expect(myIFTC.getFieldType('f1')).toBe(GraphQLString); expect(myIFTC.getFieldType('f2')).toBeInstanceOf(GraphQLNonNull); expect((myIFTC.getFieldType('f2') as any).ofType).toBe(GraphQLInt); }); it('should create TC by GraphQLInterfaceType', () => { const objType = new GraphQLInterfaceType({ name: 'TestTypeObj', fields: { f1: { type: GraphQLString, }, }, }); const myIFTC = schemaComposer.createInterfaceTC(objType); expect(myIFTC).toBeInstanceOf(InterfaceTypeComposer); expect(myIFTC.getType()).toBe(objType); expect(myIFTC.getFieldType('f1')).toBe(GraphQLString); }); it('should create type and store it in schemaComposer', () => { const SomeUserTC = schemaComposer.createInterfaceTC('SomeUser'); expect(schemaComposer.getIFTC('SomeUser')).toBe(SomeUserTC); }); it('createTemp() should not store type in schemaComposer', () => { InterfaceTypeComposer.createTemp('SomeUser'); expect(schemaComposer.has('SomeUser')).toBeFalsy(); }); }); describe('clone()', () => { it('should clone type', () => { const cloned = iftc.clone('NewObject'); expect(cloned).not.toBe(iftc); expect(cloned.getTypeName()).toBe('NewObject'); }); it('field config should be different', () => { const cloned = iftc.clone('NewObject'); cloned.setField('field4', 'String'); expect(cloned.hasField('field4')).toBeTruthy(); expect(iftc.hasField('field4')).toBeFalsy(); }); it('field args should be different', () => { iftc.setField('field3', { type: 'String', args: { a1: 'Int' }, }); const cloned = iftc.clone('NewObject'); cloned.setFieldArg('field3', 'a2', 'String'); expect(cloned.hasFieldArg('field3', 'a2')).toBeTruthy(); expect(iftc.hasFieldArg('field3', 'a2')).toBeFalsy(); }); it('extensions should be different', () => { iftc.setExtension('ext1', 123); iftc.setFieldExtension('field1', 'ext2', 456); const cloned = iftc.clone('NewObject'); expect(cloned.getExtension('ext1')).toBe(123); cloned.setExtension('ext1', 300); expect(cloned.getExtension('ext1')).toBe(300); expect(iftc.getExtension('ext1')).toBe(123); expect(cloned.getFieldExtension('field1', 'ext2')).toBe(456); cloned.setFieldExtension('field1', 'ext2', 600); expect(cloned.getFieldExtension('field1', 'ext2')).toBe(600); expect(iftc.getFieldExtension('field1', 'ext2')).toBe(456); }); it('typeResolvers should be the same', () => { const UserTC = schemaComposer.createObjectTC(`type User { field1: String }`); iftc.addTypeResolver(UserTC, () => true); const cloned = iftc.clone('NewObject'); const clonedUserTC = cloned.getTypeResolvers().keys().next().value; expect(clonedUserTC).toBe(UserTC); }); }); describe('cloneTo()', () => { let anotherSchemaComposer: SchemaComposer<any>; beforeEach(() => { anotherSchemaComposer = new SchemaComposer(); }); it('should clone type', () => { const cloned = iftc.cloneTo(anotherSchemaComposer); expect(cloned).not.toBe(iftc); expect(cloned.getTypeName()).toBe(iftc.getTypeName()); }); it('should clone field complex type', () => { const ComplexTC = schemaComposer.createObjectTC(`type Complex { a: String }`); iftc.setField('field3', { type: ComplexTC, args: { a1: 'Int' }, }); const cloned = iftc.cloneTo(anotherSchemaComposer); const fc = cloned.getField('field3'); expect(fc.type.getTypeName()).toBe('Complex'); expect(fc.type).not.toBe(ComplexTC); expect(fc.type.getType()).not.toBe(ComplexTC.getType()); }); it('field config should be different', () => { const cloned = iftc.cloneTo(anotherSchemaComposer); cloned.setField('field4', 'String'); expect(cloned.hasField('field4')).toBeTruthy(); expect(iftc.hasField('field4')).toBeFalsy(); }); it('field args should be different', () => { const cloned = iftc.cloneTo(anotherSchemaComposer); cloned.setFieldArg('field1', 'a2', 'String'); expect(cloned.hasFieldArg('field1', 'a2')).toBeTruthy(); expect(iftc.hasFieldArg('field1', 'a2')).toBeFalsy(); }); it('extensions should be different', () => { iftc.setExtension('ext1', 123); iftc.setFieldExtension('field1', 'ext2', 456); const cloned = iftc.cloneTo(anotherSchemaComposer); expect(cloned.getExtension('ext1')).toBe(123); cloned.setExtension('ext1', 300); expect(cloned.getExtension('ext1')).toBe(300); expect(iftc.getExtension('ext1')).toBe(123); expect(cloned.getFieldExtension('field1', 'ext2')).toBe(456); cloned.setFieldExtension('field1', 'ext2', 600); expect(cloned.getFieldExtension('field1', 'ext2')).toBe(600); expect(iftc.getFieldExtension('field1', 'ext2')).toBe(456); }); it('typeResolvers should be different', () => { const UserTC = schemaComposer.createObjectTC(`type User { field1: String }`); iftc.addTypeResolver(UserTC, () => true); const cloned = iftc.cloneTo(anotherSchemaComposer); const clonedUserTC = cloned.getTypeResolvers().keys().next().value; expect(clonedUserTC).not.toBe(UserTC); expect(clonedUserTC.getTypeName()).toBe(UserTC.getTypeName()); }); }); describe('get()', () => { it('should return type by path', () => { const myIFTC = new InterfaceTypeComposer( new GraphQLInterfaceType({ name: 'Readable', fields: { field1: { type: GraphQLString, args: { arg1: { type: GraphQLInt, }, }, }, }, }), schemaComposer ); expect((myIFTC.get('field1') as any).getType()).toBe(GraphQLString); expect((myIFTC.get('field1.@arg1') as any).getType()).toBe(GraphQLInt); }); }); describe('get type methods', () => { it('getTypePlural() should return wrapped type with ListComposer', () => { expect(iftc.getTypePlural()).toBeInstanceOf(ListComposer); expect(iftc.getTypePlural().getType().ofType).toBe(iftc.getType()); }); it('getTypeNonNull() should return wrapped type with NonNullComposer', () => { expect(iftc.getTypeNonNull()).toBeInstanceOf(NonNullComposer); expect(iftc.getTypeNonNull().getType().ofType).toBe(iftc.getType()); }); it('check getters List, NonNull', () => { const UserTC = schemaComposer.createInterfaceTC(`interface UserIface { name: String }`); expect(UserTC.List).toBeInstanceOf(ListComposer); expect(UserTC.List.ofType).toBe(UserTC); expect(UserTC.List.getTypeName()).toBe('[UserIface]'); expect(UserTC.NonNull).toBeInstanceOf(NonNullComposer); expect(UserTC.NonNull.ofType).toBe(UserTC); expect(UserTC.NonNull.getTypeName()).toBe('UserIface!'); expect(UserTC.NonNull.List).toBeInstanceOf(ListComposer); expect(UserTC.NonNull.List.getTypeName()).toBe('[UserIface!]'); expect(UserTC.NonNull.List.NonNull).toBeInstanceOf(NonNullComposer); expect(UserTC.NonNull.List.NonNull.getTypeName()).toBe('[UserIface!]!'); }); }); it('should have chain-methods', () => { expect(iftc.setFields({})).toBe(iftc); expect(iftc.setField('f1', { type: 'Int' })).toBe(iftc); expect(iftc.extendField('f1', { description: 'Ok' })).toBe(iftc); expect(iftc.deprecateFields('f1')).toBe(iftc); expect(iftc.addFields({})).toBe(iftc); expect(iftc.removeField('f1')).toBe(iftc); expect(iftc.removeOtherFields('f1')).toBe(iftc); expect(iftc.reorderFields(['f1'])).toBe(iftc); }); describe('deprecateFields()', () => { let iftc1: InterfaceTypeComposer<any, any>; beforeEach(() => { iftc1 = schemaComposer.createInterfaceTC({ name: 'MyType', fields: { name: 'String', age: 'Int', dob: 'Date', }, }); }); it('should accept string', () => { iftc1.deprecateFields('name'); expect(iftc1.getFieldConfig('name').deprecationReason).toBe('deprecated'); expect(iftc1.getFieldConfig('age').deprecationReason).toBeUndefined(); expect(iftc1.getFieldConfig('dob').deprecationReason).toBeUndefined(); }); it('should accept array of string', () => { iftc1.deprecateFields(['name', 'age']); expect(iftc1.getFieldConfig('name').deprecationReason).toBe('deprecated'); expect(iftc1.getFieldConfig('age').deprecationReason).toBe('deprecated'); expect(iftc1.getFieldConfig('dob').deprecationReason).toBeUndefined(); }); it('should accept object with fields and reasons', () => { iftc1.deprecateFields({ age: 'do not use', dob: 'old field', }); expect(iftc1.getFieldConfig('name').deprecationReason).toBeUndefined(); expect(iftc1.getFieldConfig('age').deprecationReason).toBe('do not use'); expect(iftc1.getFieldConfig('dob').deprecationReason).toBe('old field'); }); it('should throw error on non-existent field', () => { expect(() => { iftc1.deprecateFields('missing'); }).toThrowError(/Cannot deprecate non-existent field/); expect(() => { iftc1.deprecateFields(['missing']); }).toThrowError(/Cannot deprecate non-existent field/); expect(() => { iftc1.deprecateFields({ missing: 'Deprecate reason' }); }).toThrowError(/Cannot deprecate non-existent field/); }); }); describe('getFieldTC()', () => { const myIFTC = ObjectTypeComposer.create('MyCustomType', schemaComposer); myIFTC.addFields({ scalar: 'String', list: '[Int]', obj: ObjectTypeComposer.create(`type MyCustomObjType { name: String }`, schemaComposer), objArr: [ObjectTypeComposer.create(`type MyCustomObjType2 { name: String }`, schemaComposer)], iface: InterfaceTypeComposer.create( `interface MyInterfaceType { field: String }`, schemaComposer ), enum: EnumTypeComposer.create(`enum MyEnumType { FOO BAR }`, schemaComposer), union: UnionTypeComposer.create( `union MyUnionType = MyCustomObjType | MyCustomObjType2`, schemaComposer ), }); it('should return TypeComposer for object field', () => { const tco = myIFTC.getFieldTC('obj'); expect(tco).toBeInstanceOf(ObjectTypeComposer); expect(tco.getTypeName()).toBe('MyCustomObjType'); }); it('should return TypeComposer for wrapped object field', () => { const tco = myIFTC.getFieldTC('objArr'); expect(tco).toBeInstanceOf(ObjectTypeComposer); expect(tco.getTypeName()).toBe('MyCustomObjType2'); const tco2 = myIFTC.getFieldOTC('objArr'); expect(tco).toBe(tco2); }); it('should return TypeComposer for scalar fields', () => { const tco = myIFTC.getFieldTC('scalar'); expect(tco).toBeInstanceOf(ScalarTypeComposer); expect(tco.getTypeName()).toBe('String'); expect(() => myIFTC.getFieldOTC('scalar')).toThrow('must be ObjectTypeComposer'); }); it('should return TypeComposer for scalar list fields', () => { const tco = myIFTC.getFieldTC('list'); expect(tco).toBeInstanceOf(ScalarTypeComposer); expect(tco.getTypeName()).toBe('Int'); }); it('should return TypeComposer for enum fields', () => { const tco = myIFTC.getFieldTC('enum'); expect(tco).toBeInstanceOf(EnumTypeComposer); expect(tco.getTypeName()).toBe('MyEnumType'); }); it('should return TypeComposer for interface list fields', () => { const tco = myIFTC.getFieldTC('iface'); expect(tco).toBeInstanceOf(InterfaceTypeComposer); expect(tco.getTypeName()).toBe('MyInterfaceType'); }); it('should return TypeComposer for union list fields', () => { const tco = myIFTC.getFieldTC('union'); expect(tco).toBeInstanceOf(UnionTypeComposer); expect(tco.getTypeName()).toBe('MyUnionType'); }); }); describe('typeResolvers methods', () => { let PersonTC: ObjectTypeComposer; let KindRedTC: ObjectTypeComposer; let KindBlueTC: ObjectTypeComposer; beforeEach(() => { PersonTC = schemaComposer.createObjectTC(` type Person { age: Int, field1: String, field2: String } `); PersonTC.addInterface(iftc); iftc.addTypeResolver(PersonTC, (value) => { return value.hasOwnProperty('age'); }); KindRedTC = schemaComposer.createObjectTC(` type KindRed { kind: String, field1: String, field2: String, red: String } `); // You may not call `KindRedTC.addInterface(iftc)` it will be done internally by `addTypeResolver` iftc.addTypeResolver(KindRedTC, (value) => { return value.kind === 'red'; }); KindBlueTC = schemaComposer.createObjectTC(` type KindBlue { kind: String, field1: String, field2: String, blue: String } `); iftc.addTypeResolver(KindBlueTC, (value) => { return value.kind === 'blue'; }); }); it('hasTypeResolver()', () => { expect(iftc.hasTypeResolver(PersonTC)).toBeTruthy(); expect(iftc.hasTypeResolver(KindRedTC)).toBeTruthy(); expect(iftc.hasTypeResolver(KindBlueTC)).toBeTruthy(); expect(iftc.hasTypeResolver(schemaComposer.createObjectTC('NewOne'))).toBeFalsy(); }); it('to Object Types should be added current interface', () => { expect(PersonTC.hasInterface(iftc)).toBeTruthy(); expect(KindRedTC.hasInterface(iftc)).toBeTruthy(); expect(KindBlueTC.hasInterface(iftc)).toBeTruthy(); }); it('getTypeResolvers()', () => { const trm = iftc.getTypeResolvers(); expect(trm).toBeInstanceOf(Map); expect(trm.size).toBe(3); }); it('getTypeResolverCheckFn()', () => { const checkFn = iftc.getTypeResolverCheckFn(PersonTC) as any; expect(checkFn({ age: 15 })).toBeTruthy(); expect(checkFn({ nope: 'other type' })).toBeFalsy(); }); it('setTypeResolverFallback()', () => { const checkFn1 = iftc.getResolveType() as any; expect(checkFn1({})).toBeFalsy(); const FallbackTC = schemaComposer.createObjectTC(` type Fallback { field1: String, field2: String } `); iftc.setTypeResolverFallback(FallbackTC); expect(FallbackTC.hasInterface(iftc)).toBeTruthy(); const checkFn2 = iftc.getResolveType() as any; expect(checkFn2({})).toBe(FallbackTC.getType()); iftc.setTypeResolverFallback(null); }); it('getTypeResolverNames()', () => { expect(iftc.getTypeResolverNames()).toEqual( expect.arrayContaining(['Person', 'KindRed', 'KindBlue']) ); }); it('getTypeResolverTypes()', () => { expect(iftc.getTypeResolverTypes()).toEqual( expect.arrayContaining([PersonTC.getType(), KindRedTC.getType(), KindBlueTC.getType()]) ); }); describe('setTypeResolvers()', () => { it('async mode', async () => { const map = new Map<any, any>([ [PersonTC.getType(), async () => Promise.resolve(false)], [KindRedTC, async () => Promise.resolve(true)], ]); iftc.setTypeResolvers(map); const resolveType = (iftc as any)._gqType.resolveType as any; expect(resolveType()).toBeInstanceOf(Promise); if (graphqlVersion >= 16) { expect(await resolveType()).toBe(KindRedTC.getTypeName()); } else { expect(await resolveType()).toBe(KindRedTC.getType()); } }); it('sync mode', () => { const map = new Map<any, any>([ [PersonTC.getType(), () => false], [KindRedTC, () => false], [KindBlueTC, () => true], ]); iftc.setTypeResolvers(map); const resolveType = (iftc as any)._gqType.resolveType; if (graphqlVersion >= 16) { expect(resolveType()).toBe(KindBlueTC.getTypeName()); } else { expect(resolveType()).toBe(KindBlueTC.getType()); } }); it('throw error on wrong type', () => { expect(() => { const map = new Map<any, any>([[false, () => true]]); iftc.setTypeResolvers(map); }).toThrowError(); }); it('throw error on wrong checkFn', () => { expect(() => { const map = new Map<any, any>([[PersonTC, true]]); iftc.setTypeResolvers(map); }).toThrowError(); }); }); it('addTypeResolver()', () => { const fn = () => false; iftc.addTypeResolver(PersonTC, fn); expect(iftc.getTypeResolverCheckFn(PersonTC)).toBe(fn); expect(() => { iftc.addTypeResolver(PersonTC as any, undefined as any); }).toThrowError(); }); it('removeTypeResolver()', () => { expect(iftc.hasTypeResolver(PersonTC)).toBeTruthy(); iftc.removeTypeResolver(PersonTC); expect(iftc.hasTypeResolver(PersonTC)).toBeFalsy(); }); describe('check native resolveType methods', () => { it('check methods setResolveType() getResolveType()', () => { const iftc1 = schemaComposer.createInterfaceTC(`interface F { f: Int }`); const resolveType = () => 'A'; expect(iftc1.getResolveType()).toBeUndefined(); iftc1.setResolveType(resolveType); expect(iftc1.getResolveType()).toBe(resolveType); }); it('integration test', async () => { const iftc1 = schemaComposer.createInterfaceTC(`interface F { f: Int }`); const aTC = schemaComposer.createObjectTC('type A implements F { a: Int, f: Int }'); const bTC = schemaComposer.createObjectTC('type B implements F { b: Int, f: Int }'); const resolveType = (value: any) => { if (value) { if (value.a) return 'A'; else if (value.b) return 'B'; } return undefined; }; iftc1.setResolveType(resolveType); schemaComposer.addSchemaMustHaveType(aTC); schemaComposer.addSchemaMustHaveType(bTC); schemaComposer.Query.addFields({ check: { type: '[F]', resolve: () => [ { f: 'A', a: 1 }, { f: 'B', b: 2 }, { f: 'C', c: 3 }, ], }, }); const res = await graphql({ schema: schemaComposer.buildSchema(), source: ` query { check { __typename ... on A { a } ... on B { b } } } `, }); expect(res.data).toEqual({ check: [{ __typename: 'A', a: 1 }, { __typename: 'B', b: 2 }, null], }); }); }); }); describe('InputType convert methods', () => { it('getInputType()', () => { const input = iftc.getInputType(); expect(input).toBeInstanceOf(GraphQLInputObjectType); // must return the same instance! expect(input).toBe(iftc.getInputType()); }); it('hasInputTypeComposer()', () => { expect(iftc.hasInputTypeComposer()).toBeFalsy(); const input = iftc.getInputType(); expect(input).toBeInstanceOf(GraphQLInputObjectType); expect(iftc.hasInputTypeComposer()).toBeTruthy(); }); it('setInputTypeComposer()', () => { const itc1 = InputTypeComposer.createTemp(`Input`); iftc.setInputTypeComposer(itc1); const itc2 = iftc.getInputTypeComposer(); expect(itc1).toBe(itc2); }); it('getInputTypeComposer()', () => { const itc = iftc.getInputTypeComposer(); expect(itc).toBeInstanceOf(InputTypeComposer); // must return the same instance! expect(itc).toBe(iftc.getInputTypeComposer()); }); it('getITC()', () => { expect(iftc.getITC()).toBe(iftc.getInputTypeComposer()); }); it('removeInputTypeComposer()', () => { const iftc3 = schemaComposer.createInterfaceTC(` interface Point { x: Int y: Int } `); let itc3 = iftc3.getInputTypeComposer(); expect(itc3.getFieldNames()).toEqual(['x', 'y']); iftc3.addFields({ z: 'Int', }); expect(itc3.getFieldNames()).toEqual(['x', 'y']); iftc3.removeInputTypeComposer(); itc3 = iftc3.getInputTypeComposer(); expect(itc3.getFieldNames()).toEqual(['x', 'y', 'z']); }); }); describe('directive methods', () => { it('type level directive methods', () => { const tc1 = schemaComposer.createInterfaceTC(` interface My1 @d0(a: false) @d1(b: "3") @d0(a: true) { field: Int }`); expect(tc1.getDirectives()).toEqual([ { args: { a: false }, name: 'd0' }, { args: { b: '3' }, name: 'd1' }, { args: { a: true }, name: 'd0' }, ]); expect(tc1.getDirectiveNames()).toEqual(['d0', 'd1', 'd0']); expect(tc1.getDirectiveByName('d0')).toEqual({ a: false }); expect(tc1.getDirectiveById(0)).toEqual({ a: false }); expect(tc1.getDirectiveByName('d1')).toEqual({ b: '3' }); expect(tc1.getDirectiveById(1)).toEqual({ b: '3' }); expect(tc1.getDirectiveByName('d2')).toEqual(undefined); expect(tc1.getDirectiveById(333)).toEqual(undefined); }); it('field level directive methods', () => { const tc1 = schemaComposer.createInterfaceTC(` interface My1 { field: Int @f0(a: false) @f1(b: "3") @f0(a: true) }`); expect(tc1.getFieldDirectives('field')).toEqual([ { args: { a: false }, name: 'f0' }, { args: { b: '3' }, name: 'f1' }, { args: { a: true }, name: 'f0' }, ]); expect(tc1.getFieldDirectiveNames('field')).toEqual(['f0', 'f1', 'f0']); expect(tc1.getFieldDirectiveByName('field', 'f0')).toEqual({ a: false }); expect(tc1.getFieldDirectiveById('field', 0)).toEqual({ a: false }); expect(tc1.getFieldDirectiveByName('field', 'f1')).toEqual({ b: '3' }); expect(tc1.getFieldDirectiveById('field', 1)).toEqual({ b: '3' }); expect(tc1.getFieldDirectiveByName('field', 'f2')).toEqual(undefined); expect(tc1.getFieldDirectiveById('field', 333)).toEqual(undefined); }); it('arg level directive methods', () => { const tc1 = schemaComposer.createInterfaceTC(` interface My1 { field( arg: Int @a0(a: false) @a1(b: "3") @a0(a: true) ): Int }`); expect(tc1.getFieldArgDirectives('field', 'arg')).toEqual([ { args: { a: false }, name: 'a0' }, { args: { b: '3' }, name: 'a1' }, { args: { a: true }, name: 'a0' }, ]); expect(tc1.getFieldArgDirectiveNames('field', 'arg')).toEqual(['a0', 'a1', 'a0']); expect(tc1.getFieldArgDirectiveByName('field', 'arg', 'a0')).toEqual({ a: false }); expect(tc1.getFieldArgDirectiveById('field', 'arg', 0)).toEqual({ a: false }); expect(tc1.getFieldArgDirectiveByName('field', 'arg', 'a1')).toEqual({ b: '3' }); expect(tc1.getFieldArgDirectiveById('field', 'arg', 1)).toEqual({ b: '3' }); expect(tc1.getFieldArgDirectiveByName('field', 'arg', 'a2')).toEqual(undefined); expect(tc1.getFieldArgDirectiveById('field', 'arg', 333)).toEqual(undefined); }); it('check directive set-methods', () => { const tc1 = schemaComposer.createInterfaceTC(` interface My1 @d0(a: true) { field: Int @d2(a: false, b: true) field2(ok: Int = 15 @d5(a: 5)): Int } `); expect(tc1.toSDL()).toBe(dedent` interface My1 @d0(a: true) { field: Int @d2(a: false, b: true) field2(ok: Int = 15 @d5(a: 5)): Int } `); tc1.setDirectives([ { args: { a: false }, name: 'd0' }, { args: { b: '3' }, name: 'd1' }, { args: { a: true }, name: 'd0' }, ]); tc1.setFieldDirectives('field', [{ args: { b: '6' }, name: 'd1' }]); tc1.setFieldArgDirectives('field2', 'ok', [{ args: { b: '7' }, name: 'd1' }]); expect(tc1.toSDL()).toBe(dedent` interface My1 @d0(a: false) @d1(b: "3") @d0(a: true) { field: Int @d1(b: "6") field2(ok: Int = 15 @d1(b: "7")): Int } `); }); it('should create directives via config as object', () => { const tc2 = schemaComposer.createInterfaceTC({ name: 'MyObject', fields: { red: { type: 'Int', directives: [{ name: 'skip', args: { if: true } }] }, }, directives: [{ name: 'ok', args: { a: 1, b: '123', c: true } }, { name: 'go' }], }); expect(tc2.toSDL()).toEqual(dedent` interface MyObject @ok(a: 1, b: "123", c: true) @go { red: Int @skip(if: true) } `); }); it('setDirectiveByName should add directive if does not exist', () => { const tc2 = schemaComposer.createInterfaceTC({ name: 'MyObject', fields: { red: { type: 'Int', directives: [{ name: 'skip', args: { if: true } }] }, }, directives: [{ name: 'ok', args: { a: 1 } }], }); tc2.setDirectiveByName('go'); expect(tc2.toSDL()).toEqual(dedent` interface MyObject @ok(a: 1) @go { red: Int @skip(if: true) } `); }); it('setDirectiveByName should replace first directive args if exists', () => { const tc2 = schemaComposer.createInterfaceTC({ name: 'MyObject', fields: { red: { type: 'Int', directives: [{ name: 'skip', args: { if: true } }] }, }, directives: [{ name: 'ok', args: { a: 1 } }, { name: 'go' }], }); tc2.setDirectiveByName('ok', { b: 2 }); expect(tc2.toSDL()).toEqual(dedent` interface MyObject @ok(b: 2) @go { red: Int @skip(if: true) } `); }); it('setFieldDirectiveByName should add directive if does not exist', () => { const tc2 = schemaComposer.createInterfaceTC({ name: 'MyObject', fields: { red: { type: 'Int', directives: [{ name: 'ok', args: { a: 1 } }] }, }, }); tc2.setFieldDirectiveByName('red', 'go'); expect(tc2.toSDL()).toEqual(dedent` interface MyObject { red: Int @ok(a: 1) @go } `); }); it('setFieldDirectiveByName should replace first directive args if exists', () => { const tc2 = schemaComposer.createInterfaceTC({ name: 'MyObject', fields: { red: { type: 'Int', directives: [{ name: 'ok', args: { a: 1 } }, { name: 'go' }] }, }, }); tc2.setFieldDirectiveByName('red', 'ok', { b: 2 }); expect(tc2.toSDL()).toEqual(dedent` interface MyObject { red: Int @ok(b: 2) @go } `); }); it('setFieldArgDirectiveByName should add directive if does not exist', () => { const tc2 = schemaComposer.createInterfaceTC({ name: 'MyObject', fields: { red: { type: 'Int', args: { a1: { type: 'Int', directives: [{ name: 'ok', args: { a: 1 } }] } }, }, }, }); tc2.setFieldArgDirectiveByName('red', 'a1', 'go'); expect(tc2.toSDL()).toEqual(dedent` interface MyObject { red(a1: Int @ok(a: 1) @go): Int } `); }); it('setFieldArgDirectiveByName should replace first directive args if exists', () => { const tc2 = schemaComposer.createInterfaceTC({ name: 'MyObject', fields: { red: { type: 'Int', args: { a1: { type: 'Int', directives: [{ name: 'ok', args: { a: 1 } }, { name: 'go' }] }, }, }, }, }); tc2.setFieldArgDirectiveByName('red', 'a1', 'ok', { b: 2 }); expect(tc2.toSDL()).toEqual(dedent` interface MyObject { red(a1: Int @ok(b: 2) @go): Int } `); }); }); describe('merge()', () => { it('should merge with GraphQLInterfaceType', () => { const iface = schemaComposer.createInterfaceTC(`interface IFace { name: String }`); const iface2 = new GraphQLInterfaceType({ name: 'WithAge', fields: { age: { type: GraphQLInt }, }, }); iface.merge(iface2); expect(iface.getFieldNames()).toEqual(['name', 'age']); }); it('should merge with InterfaceTypeComposer', () => { const iface = schemaComposer.createInterfaceTC(`interface IFace { name: String }`); const sc2 = new SchemaComposer(); const iface2 = sc2.createInterfaceTC(`interface WithAge { age: Int }`); iface.merge(iface2); expect(iface.getFieldNames()).toEqual(['name', 'age']); }); it('should merge with GraphQLObjectType', () => { const iface = schemaComposer.createInterfaceTC(`interface IFace { name: String }`); const person = new GraphQLObjectType({ name: 'Person', fields: { age: { type: GraphQLInt }, }, }); iface.merge(person); expect(iface.getFieldNames()).toEqual(['name', 'age']); }); it('should merge with ObjectTypeComposer', () => { const iface = schemaComposer.createInterfaceTC(`interface IFace { name: String }`); const sc2 = new SchemaComposer(); const person = sc2.createObjectTC(`type Person { age: Int }`); iface.merge(person); expect(iface.getFieldNames()).toEqual(['name', 'age']); }); it('should throw error on wrong type', () => { const iface = schemaComposer.createInterfaceTC(`interface IFace { name: String }`); expect(() => iface.merge(schemaComposer.createScalarTC('Scalar') as any)).toThrow( 'Cannot merge ScalarTypeComposer' ); }); }); describe('misc methods', () => { if (graphqlVersion < 15) return; it('toSDL()', () => { const t = schemaComposer.createInterfaceTC(` """desc1""" interface IUser implements Node { """desc2""" name(a: String): String field: ISubField id: ID } interface ISubField { subField: Int } interface Node { id: ID } `); expect(t.toSDL()).toBe(dedent` """desc1""" interface IUser implements Node { """desc2""" name(a: String): String field: ISubField id: ID } `); expect(t.toSDL({ omitDescriptions: true })).toBe(dedent` interface IUser implements Node { name(a: String): String field: ISubField id: ID } `); expect( t.toSDL({ omitDescriptions: true, deep: true, }) ).toBe(dedent` interface IUser implements Node { name(a: String): String field: ISubField id: ID } scalar String interface Node { id: ID } scalar ID interface ISubField { subField: Int } `); expect( t.toSDL({ omitDescriptions: true, deep: true, exclude: ['ISubField', 'Node'], }) ).toBe(dedent` interface IUser implements Node { name(a: String): String field: ISubField id: ID } scalar String scalar ID `); }); }); describe('solve hoisting problems via thunk for fieldConfig', () => { it('setFields() & setField() should keep fieldConfig as thunk', () => { const HoistingTC = schemaComposer.createInterfaceTC('Hoisting'); const thunkedFieldConfig = () => ({ type: 'Int' }); HoistingTC.setFields({ field2: thunkedFieldConfig, field3: 'Int', }); HoistingTC.setField('field1', thunkedFieldConfig); expect((HoistingTC as any)._gqcFields.field1).toBe(thunkedFieldConfig); expect((HoistingTC as any)._gqcFields.field2).toBe(thunkedFieldConfig); expect((HoistingTC as any)._gqcFields.field3.type).toBeInstanceOf(ScalarTypeComposer); }); it('getField() should unwrap field from thunk & convert it to ComposeFieldConfig', () => { const HoistingTC = schemaComposer.createInterfaceTC('Hoisting'); const thunkedFieldConfig = () => ({ type: 'Int', args: { limit: 'Int' }, }); HoistingTC.setFields({ field1: thunkedFieldConfig, field2: thunkedFieldConfig, field3: 'Int', }); // by default fieldConfig is thunked expect((HoistingTC as any)._gqcFields.field1).toBe(thunkedFieldConfig); // getField it should be unwrapped from thunk and converted to ComposeFieldConfig expect(HoistingTC.getField('field1')).toEqual({ type: expect.any(ScalarTypeComposer), args: { limit: { type: expect.any(ScalarTypeComposer) } }, }); // after first getField, type should be keep un-thunked expect((HoistingTC as any)._gqcFields.field1).toEqual({ type: expect.any(ScalarTypeComposer), args: { limit: { type: expect.any(ScalarTypeComposer) } }, }); // other thunked fields should be untouched expect((HoistingTC as any)._gqcFields.field2).toBe(thunkedFieldConfig); }); }); });
the_stack
import { SelectionCharacterFormat, SelectionParagraphFormat, SelectionSectionFormat, SelectionTableFormat, SelectionCellFormat, SelectionRowFormat } from '../../src/index'; import { WParagraphFormat, WSectionFormat, WRowFormat, WCellFormat, WCharacterFormat } from '../../src/document-editor/implementation/format/index'; import { WidthType, HeightType, Strikethrough, CellVerticalAlignment, Underline, BaselineAlignment } from '../../src/document-editor/base/types'; import { DocumentEditor } from '../../src/document-editor/document-editor'; import { createElement } from '@syncfusion/ej2-base'; import { LayoutViewer, PageLayoutViewer } from '../../src/index'; import { TestHelper } from '../test-helper.spec'; import { Editor } from '../../src/index'; import { Selection } from '../../src/index'; describe('Selection Format validation -1', () => { it('Selection table format validation', () => { console.log('Selection table format validation'); let tableFormat: SelectionTableFormat = new SelectionTableFormat(undefined); expect(tableFormat.background).toBe(undefined); expect(tableFormat.tableAlignment).toBe(undefined); expect(tableFormat.leftIndent).toBe(0); expect(tableFormat.rightMargin).toBe(0); expect(tableFormat.leftMargin).toBe(0); expect(tableFormat.bottomMargin).toBe(0); expect(tableFormat.topMargin).toBe(0); tableFormat.bottomMargin = 7.2; tableFormat.preferredWidth = 12; expect(tableFormat.preferredWidth).toBe(12); tableFormat.preferredWidth = 12; tableFormat.topMargin = 7.2; tableFormat.preferredWidthType = 'Percent'; expect(tableFormat.preferredWidthType).toBe('Percent'); expect(tableFormat.table).toBe(undefined); expect(tableFormat.cellSpacing).toBe(0); tableFormat.preferredWidthType = 'Auto'; tableFormat.preferredWidthType = 'Auto'; tableFormat.destroy(); }); it('selection cell format validation', () => { console.log('selection cell format validation'); let cellFormat: SelectionCellFormat = new SelectionCellFormat(undefined); cellFormat.preferredWidth = 14; cellFormat.preferredWidth = 14; expect(cellFormat.preferredWidth).toBe(14); expect(cellFormat.preferredWidthType).toBe(undefined); cellFormat.preferredWidthType = 'Auto'; cellFormat.preferredWidthType = 'Auto'; expect(() => { cellFormat.clearCellFormat(); }).not.toThrowError(); cellFormat.leftMargin = 0; cellFormat.rightMargin = 0; cellFormat.bottomMargin = 0; cellFormat.topMargin = 0; cellFormat.background = "#000000"; cellFormat.verticalAlignment = 'Top'; let format: WCellFormat = new WCellFormat(undefined); format.leftMargin = 0; format.rightMargin = 0; format.bottomMargin = 0; format.topMargin = 0; format.shading.backgroundColor = "#000000"; format.verticalAlignment = 'Top'; expect(() => { cellFormat.combineFormat(format); }).not.toThrowError(); format.leftMargin = 1; format.rightMargin = 2; format.bottomMargin = 3; format.topMargin = 2; format.shading.backgroundColor = "#ffffff"; format.verticalAlignment = 'Bottom'; expect(() => { cellFormat.combineFormat(format); }).not.toThrowError(); cellFormat.clearFormat(); cellFormat.destroy(); }); it('selection row format validation', () => { console.log('selection row format validation'); let rowFormat: SelectionRowFormat = new SelectionRowFormat(undefined); rowFormat.height = 12; rowFormat.allowBreakAcrossPages = true; rowFormat.isHeader = false; rowFormat.heightType = 'Exactly'; let format: WRowFormat = new WRowFormat(undefined); format.height = 12; format.allowBreakAcrossPages = false; format.isHeader = true; format.heightType = 'Exactly'; rowFormat.combineFormat(format); expect(() => { rowFormat.clearRowFormat(); }).not.toThrowError(); rowFormat.combineFormat(format); rowFormat = new SelectionRowFormat(undefined); format.height = 1; format.allowBreakAcrossPages = true; format.isHeader = false; format.heightType = 'AtLeast'; expect(() => { rowFormat.combineFormat(format); }).not.toThrowError(); rowFormat.heightType = 'AtLeast'; format = new WRowFormat(undefined); format.height = 1; format.allowBreakAcrossPages = false; format.isHeader = true; format.heightType = 'Exactly'; rowFormat.combineFormat(format); rowFormat.clearFormat(); rowFormat.destroy(); }); }); describe('Selection Format validation -2', () => { it('Selection Section Format Validation', () => { console.log('Selection Section Format Validation'); let sectionFormat: WSectionFormat = new WSectionFormat(undefined); sectionFormat.pageHeight = 12; sectionFormat.pageWidth = 13; sectionFormat.differentFirstPage = true; sectionFormat.differentOddAndEvenPages = false; sectionFormat.headerDistance = 12; sectionFormat.footerDistance = 12; sectionFormat.leftMargin = 12; sectionFormat.rightMargin = 12; sectionFormat.bottomMargin = 12; sectionFormat.topMargin = 12; let selectionSection: SelectionSectionFormat = new SelectionSectionFormat(undefined); selectionSection.headerDistance = 10; selectionSection.footerDistance = 10; selectionSection.combineFormat(sectionFormat); selectionSection.pageHeight = 1; selectionSection.pageWidth = 2; selectionSection.differentFirstPage = false; selectionSection.differentOddAndEvenPages = true; selectionSection.headerDistance = 1; selectionSection.footerDistance = 1; selectionSection.leftMargin = 1; selectionSection.rightMargin = 1; selectionSection.bottomMargin = 1; selectionSection.topMargin = 1; expect(() => { selectionSection.combineFormat(sectionFormat); }).not.toThrowError(); selectionSection.clearFormat(); selectionSection.destroy(); }); it('selection character format validation', () => { console.log('selection character format validation'); let charFormat: SelectionCharacterFormat = new SelectionCharacterFormat(undefined); charFormat.baselineAlignment = 'Subscript'; charFormat.underline = 'Double'; charFormat.strikethrough = 'DoubleStrike'; charFormat.highlightColor = 'Pink'; let character: WCharacterFormat = new WCharacterFormat(undefined); character.highlightColor = 'Yellow'; expect(() => { charFormat.combineFormat(character); }).not.toThrowError(); charFormat.clearFormat(); charFormat.destroy(); }); it('selection Paragraph format validation', () => { console.log('selection Paragraph format validation'); let selFormat: SelectionParagraphFormat = new SelectionParagraphFormat(undefined, undefined); expect(() => { selFormat.clearFormat() }).not.toThrowError(); selFormat.rightIndent = 1; selFormat.lineSpacingType = 'Exactly'; let paraFormat: WParagraphFormat = new WParagraphFormat(undefined); paraFormat.rightIndent = 14; paraFormat.lineSpacingType = 'AtLeast'; paraFormat.listFormat.destroy(); expect(() => { selFormat.combineFormat(paraFormat) }).not.toThrowError(); selFormat.destroy(); }); }); describe('Selection Format validation, Paragraph Format validation- 4', () => { it('Copy to Format method validation with undefined parameter', () => { console.log('Copy to Format method validation with undefined parameter'); let selFormat: SelectionParagraphFormat = new SelectionParagraphFormat(undefined, undefined); let format = selFormat.copyToFormat(undefined); expect(format).toBe(undefined); }); it('Copy to Format method validation with paragraph format value as undefined', () => { console.log('Copy to Format method validation with paragraph format value as undefined'); let selFormat: SelectionParagraphFormat = new SelectionParagraphFormat(undefined, undefined); let paraFormat: WParagraphFormat = new WParagraphFormat(); selFormat.leftIndent = undefined; selFormat.afterSpacing = undefined; selFormat.beforeSpacing = undefined; selFormat.rightIndent = undefined; selFormat.textAlignment = undefined; selFormat.lineSpacing = undefined; selFormat.lineSpacingType = undefined; selFormat.firstLineIndent = undefined; selFormat.copyToFormat(paraFormat); expect(paraFormat.leftIndent).toBe(0); }); }); // describe('Nested table format retrievel', () => { // let editor: DocumentEditor = undefined; // beforeAll(() => { // let ele: HTMLElement = createElement('div', { id: 'container' }); // document.body.appendChild(ele); // DocumentEditor.Inject(Editor, Selection); // editor = new DocumentEditor({ enableEditor: true,enableSelection: true, isReadOnly: false }); // (editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas; // (editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas; // (editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas; // (editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas; // editor.appendTo('#container'); // }); // afterAll((done) => { // editor.destroy(); // document.body.removeChild(document.getElementById('container')); // editor = undefined; // setTimeout(function () { // done(); // }, 1000); // }); // it('load document with line spacing exactly', () => { // editor.editor.insertTable(2, 2); // editor.editorModule.insertText('Adventre', false); // editor.editorModule.onEnter(); // editor.editor.insertTable(2, 2); // let event: any; // event = { keyCode: 35, preventDefault: function () { }, ctrlKey: false, shiftKey: true, which: 0 }; // editor.documentHelper.onKeyDownInternal(event); // event = { keyCode: 39, preventDefault: function () { }, ctrlKey: false, shiftKey: true, which: 0 }; // editor.documentHelper.onKeyDownInternal(event); // event = { keyCode: 39, preventDefault: function () { }, ctrlKey: false, shiftKey: true, which: 0 }; // editor.documentHelper.onKeyDownInternal(event); // event = { keyCode: 39, preventDefault: function () { }, ctrlKey: false, shiftKey: true, which: 0 }; // editor.documentHelper.onKeyDownInternal(event); // event = { keyCode: 39, preventDefault: function () { }, ctrlKey: false, shiftKey: true, which: 0 }; // editor.documentHelper.onKeyDownInternal(event); // event = { keyCode: 39, preventDefault: function () { }, ctrlKey: false, shiftKey: true, which: 0 }; // editor.documentHelper.onKeyDownInternal(event); // event = { keyCode: 39, preventDefault: function () { }, ctrlKey: false, shiftKey: true, which: 0 }; // editor.documentHelper.onKeyDownInternal(event); // }); // });
the_stack
import { ApolloServer, PubSub, makeExecutableSchema } from 'apollo-server' import sleep from 'await-sleep' import assert from 'assert' import deepEq from 'deep-equal' import fs from 'fs' import path from 'path' import { expectType } from 'tsd' const id = () => null import { DeepPartial, MaybeUndefined } from 'tsdef' import { createClient, User, everything, isHouse, Account, isBank, Point, isUser, } from '../generated' import { GraphqlOperation } from '@genql/runtime' import { isClientErrorNameInvalid } from '../generated/guards.cjs' const PORT = 8099 const URL = `http://localhost:` + PORT const SUB_URL = `ws://localhost:` + PORT + '/graphql' type Maybe<T> = T | undefined | null async function server({ resolvers, port = PORT }) { try { const typeDefs = fs .readFileSync(path.join(__dirname, '..', 'schema.graphql')) .toString() const server = new ApolloServer({ schema: makeExecutableSchema({ typeDefs, resolvers, resolverValidationOptions: { requireResolversForResolveType: false, }, }), subscriptions: { onConnect: async (connectionParams, webSocket, context) => { console.log( `Subscription client connected using Apollo server's built-in SubscriptionServer.`, ) }, onDisconnect: async (webSocket, context) => { console.log(`Subscription client disconnected.`) }, }, }) // The `listen` method launches a web server. await server.listen(port).then(({ url, subscriptionsUrl }) => { console.log(`🚀 Server ready at ${url} and ${subscriptionsUrl}`) }) return () => server.stop() } catch (e) { console.error('server had an error: ' + e) return () => null } } describe('execute queries', async function() { const x: DeepPartial<User> = { name: 'John', } const makeServer = () => server({ resolvers: { Query: { user: () => { return x }, unionThatImplementsInterface: ({ typename = '' } = {}) => { return { message: 'A message', ownProp1: 'Own prop 1', ownProp2: 'Own prop 2', __typename: typename || 'ClientErrorNameInvalid', } }, someScalarValue: () => 'someScalarValue', repository: () => { return { createdAt: 'now', } }, account: () => { return { __typename: 'User', ...x, } }, coordinates: () => { return { __typename: 'Bank', x: '1', y: '2', address: '3', } }, }, }, }) const withServer = (func: any) => async () => { const stop = await makeServer() try { await func() } catch (e) { console.log('catch') throw e } finally { await stop() } } let client = createClient({ url: URL, headers: () => ({ Auth: 'xxx' }), }) it( 'simple ', withServer(async () => { const res = await client.query({ user: { name: true, }, }) console.log(JSON.stringify(res, null, 2)) assert.deepStrictEqual(res.user, x) }), ) it( '__typename is not optional', withServer(async () => { const res = await client.query({ user: { name: true, __typename: true, }, }) expectType<string>(res.user!.__typename) }), ) it( 'scalar value with argument ', withServer(async () => { var res = await client.query({ someScalarValue: true, }) assert(res.someScalarValue?.toLocaleLowerCase) var res = await client.query({ someScalarValue: [{ x: 3 }], }) assert(res.someScalarValue?.toLocaleLowerCase) }), ) it( 'falsy values are not fetched ', withServer(async () => { const res = await client.query({ coordinates: { x: false, y: true, }, }) console.log(JSON.stringify(res, null, 2)) assert(res.coordinates?.x === undefined) assert(res.coordinates?.y !== undefined) }), ) it( 'required field and nested fields', withServer(async () => { client .query({ // @ts-expect-error because name is required repository: [{}, { __scalar: true }], }) .catch(id) const res = await client.query({ repository: [ { name: 'genql', owner: 'remorses', }, { ...everything, forks: { edges: { node: { name: true, number: true } }, }, }, ], }) console.log(JSON.stringify(res, null, 2)) // @ts-expect-error because top level fields are filtered based on query res?.account // no optional chaining because repository is non null expectType<string>(res.repository.createdAt) expectType<Maybe<string>>(res.repository.__typename) expectType<Maybe<Maybe<string>[]>>( res.repository?.forks?.edges?.map((x) => x?.node?.name), ) expectType<Maybe<Maybe<number>[]>>( res.repository?.forks?.edges?.map((x) => x?.node?.number), ) }), ) it( 'chain syntax ', withServer(async () => { client.chain.query.user .get({ name: true, // sdf: true, }) .catch(id) const res = await client.chain.query.user.get({ __scalar: true, // sdf: true, }) console.log(JSON.stringify(res, null, 2)) expectType<Maybe<string>>(res?.name) expectType<Maybe<number>>(res?.common) expectType<Maybe<string>>(res?.__typename) }), ) it( 'recursive type chain syntax ', withServer(async () => { const res = await client.chain.query .recursiveType() .get({ recurse: { recurse: { ...everything, recurse: { value: 1, }, }, }, }) .catch(id) console.log(JSON.stringify(res, null, 2)) expectType<Maybe<string>>(res?.[0]?.recurse?.recurse?.value) expectType<Maybe<string>>( res?.[0]?.recurse?.recurse?.recurse?.value, ) expectType<Maybe<string>>(res?.[0]?.recurse?.recurse?.value) }), ) it( 'union types only 1 on_ normal syntax', withServer(async () => { const { account } = await client.query({ account: { __typename: 1, on_User: { name: 1, }, }, }) // @ts-expect-error because on_User should be removed account?.on_User assert(account?.__typename) expectType<Maybe<Account>>(account) console.log(account) }), ) it( 'union types chain syntax', withServer(async () => { const account = await client.chain.query.account.get({ on_User: { name: 1 }, }) expectType<Maybe<Account>>(account) }), ) it( 'chain syntax result type only has requested fields', withServer(async () => { const res = await client.chain.query .repository({ name: '' }) .get({ createdAt: 1 }) expectType<string>(res.createdAt) // @ts-expect-error res?.forks }), ) it( 'union types with chain and ...everything', withServer(async () => { const account = await client.chain.query.account.get({ __typename: 1, on_User: { ...everything }, }) expectType<Maybe<string>>(account?.__typename) if (isUser(account)) { expectType<Maybe<string>>(account?.name) } }), ) it( 'many union types', withServer(async () => { const account = await client.chain.query.account.get({ __typename: 1, on_User: { ...everything }, on_Guest: { ...everything }, }) expectType<Maybe<string>>(account?.__typename) // common props are on both types expectType<Maybe<number>>(account?.common) if (account && 'anonymous' in account) { account?.anonymous } }), ) it( 'ability to query interfaces that a union implements', withServer(async () => { const { unionThatImplementsInterface } = await client.query({ unionThatImplementsInterface: { __typename: 1, on_ClientErrorNameInvalid: { message: 1, ownProp2: 1, }, on_ClientError: { message: 1, }, on_ClientErrorWithoutInterface: { ownProp3: 1, }, }, }) if ( unionThatImplementsInterface?.__typename === 'ClientErrorNameInvalid' ) { assert.ok(unionThatImplementsInterface?.ownProp2) } if ( unionThatImplementsInterface?.__typename === 'ClientErrorWithoutInterface' ) { assert.ok(unionThatImplementsInterface?.ownProp3) } }), ) it( 'ability to query interfaces that a union implements, chain syntax', withServer(async () => { const unionThatImplementsInterface = await client.chain.query .unionThatImplementsInterface({}) .get({ on_ClientError: { message: 1 }, on_ClientErrorNameInvalid: { ownProp2: 1 }, }) if ( unionThatImplementsInterface?.__typename === 'ClientErrorNameInvalid' ) { assert.ok(unionThatImplementsInterface?.ownProp2) } }), ) it( 'interface types normal syntax', withServer(async () => { const res = await client.query({ coordinates: { x: 1, __typename: 1, on_Bank: { // __typename: 1, address: 1, // x: 1, }, }, }) let coordinates = res.coordinates expectType<Maybe<string>>(coordinates?.x) if (coordinates && 'address' in coordinates) { expectType<Maybe<string>>(coordinates?.address) assert(coordinates?.address) } // common types are accessible without guards assert(coordinates?.x) assert(coordinates?.__typename) }), ) it( 'interface types chain syntax', withServer(async () => { const coordinates = await client.chain.query.coordinates.get({ // x: 1, x: 1, on_Bank: { address: 1 }, }) expectType<Maybe<string>>(coordinates?.x) if (coordinates && 'address' in coordinates) { expectType<Maybe<string>>(coordinates?.address) assert(coordinates?.address) assert(coordinates?.x) } }), ) it( 'multiple interfaces types normal syntax', withServer(async () => { const { coordinates } = await client.query({ coordinates: { __typename: 1, on_Bank: { address: 1, x: 1, }, on_House: { y: 1, x: 1, owner: { name: 1, }, }, }, }) console.log(coordinates) expectType<Maybe<string>>(coordinates?.x) expectType<Maybe<Point>>(coordinates) expectType<Maybe<string>>(coordinates?.__typename) assert(coordinates?.x) assert(coordinates?.__typename) if ('address' in coordinates) { coordinates?.address coordinates?.x } else if (isHouse(coordinates)) { coordinates?.owner coordinates?.x coordinates?.y } }), ) it( 'batches requests', withServer(async () => { let batchedQueryLength = -1 const client = createClient({ url: URL, batch: true, fetcher: async (body) => { console.log(body) batchedQueryLength = Array.isArray(body) ? body.length : -1 const res = await fetch(URL, { headers: { 'Content-Type': 'application/json', }, method: 'POST', body: JSON.stringify(body), }) return await res.json() }, }) const res = await Promise.all([ client.query({ coordinates: { __typename: 1, x: 1, }, }), client.query({ coordinates: { __typename: 1, y: 1, }, }), ]) assert.strictEqual(res.length, 2) assert.strictEqual(batchedQueryLength, 2) }), ) it( 'headers function gets called every time', withServer(async () => { let headersCalledNTimes = 0 const client = createClient({ url: URL, headers: () => { headersCalledNTimes++ return {} }, }) await client.query({ coordinates: { __typename: 1, x: 1, }, }) await client.query({ coordinates: { __typename: 1, y: 1, }, }) assert.strictEqual(headersCalledNTimes, 2) }), ) it( 'async headers function gets called every time', withServer(async () => { let headersCalledNTimes = 0 const client = createClient({ url: URL, headers: async () => { headersCalledNTimes++ return {} }, }) await client.query({ coordinates: { __typename: 1, x: 1, }, }) await client.query({ coordinates: { __typename: 1, y: 1, }, }) assert.strictEqual(headersCalledNTimes, 2) }), ) }) describe('execute subscriptions', async function() { const x: DeepPartial<User> = { name: 'John', } const pubsub = new PubSub() const USER_EVENT = 'userxxx' const makeServer = () => server({ resolvers: { Subscription: { user: { subscribe: () => { return pubsub.asyncIterator([USER_EVENT]) }, }, }, }, }) it('simple ', async () => { const client = createClient({ url: SUB_URL, }) const stop = await makeServer() // await pubsub.publish(USER_EVENT, { user: x }) await sleep(100) const sub = await client .subscription({ user: { name: true, common: 1, __typename: true, }, }) .subscribe({ next: (x) => { expectType<Maybe<string>>(x.user?.name) expectType<Maybe<string>>(x.user?.__typename) expectType<Maybe<number>>(x.user?.common) console.log(x) }, complete: () => console.log('complete'), error: console.error, }) // await sleep(1000) await pubsub.publish(USER_EVENT, { user: x }) // console.log(JSON.stringify(res, null, 2)) sub.unsubscribe() client?.wsClient?.close?.() await stop() // assert(deepEq(res.user, x)) }) it('headers function gets called', async () => { let headersCalledNTimes = 0 const client = createClient({ url: SUB_URL, subscription: { headers: async () => { headersCalledNTimes++ return {} }, }, }) const stop = await makeServer() // await pubsub.publish(USER_EVENT, { user: x }) await sleep(100) let subscribeCalledNTimes = 0 const sub = client .subscription({ user: { name: true, common: 1, __typename: true, }, }) .subscribe({ next: (x) => { expectType<Maybe<string>>(x.user?.name) expectType<Maybe<string>>(x.user?.__typename) expectType<Maybe<number>>(x.user?.common) console.log(x) subscribeCalledNTimes++ }, complete: () => console.log('complete'), error: console.error, }) await sleep(100) await pubsub.publish(USER_EVENT, { user: x }) await pubsub.publish(USER_EVENT, { user: x }) await sleep(100) assert.strictEqual(subscribeCalledNTimes, 2, 'subscribeCalledNTimes') // console.log(JSON.stringify(res, null, 2)) sub.unsubscribe() client.wsClient!.close() await stop() assert.strictEqual(headersCalledNTimes, 1) }) })
the_stack
import { ident } from "../../../Data/Function" import { fmap } from "../../../Data/Functor" import { consF, countWith, foldr, List, maximum, minimum, notNull } from "../../../Data/List" import { bindF, catMaybes, elem, ensure, Just, maybe, Maybe, Nothing, sum } from "../../../Data/Maybe" import { add, gt } from "../../../Data/Num" import { lookup, lookupF, OrderedMap } from "../../../Data/OrderedMap" import { } from "../../../Data/OrderedSet" import { Record } from "../../../Data/Record" import { Pair } from "../../../Data/Tuple" import { SkillId, SpecialAbilityId } from "../../Constants/Ids" import { ActivatableDependent } from "../../Models/ActiveEntries/ActivatableDependent" import { ActiveObject } from "../../Models/ActiveEntries/ActiveObject" import { AttributeDependent } from "../../Models/ActiveEntries/AttributeDependent" import { SkillDependent } from "../../Models/ActiveEntries/SkillDependent" import { HeroModel, HeroModelRecord } from "../../Models/Hero/HeroModel" import { EntryRating } from "../../Models/Hero/heroTypeHelpers" import { SkillCombined, SkillCombinedA_ } from "../../Models/View/SkillCombined" import { ExperienceLevel } from "../../Models/Wiki/ExperienceLevel" import { Skill } from "../../Models/Wiki/Skill" import { StaticDataRecord } from "../../Models/Wiki/WikiModel" import { EntryWithCheck } from "../../Models/Wiki/wikiTypeHelpers" import { isMaybeActive } from "../Activatable/isActive" import { flattenDependencies } from "../Dependencies/flattenDependencies" import { pipe, pipe_ } from "../pipe" import { getSkillCheckValues } from "./attributeUtils" const HA = HeroModel.A const ADA = ActivatableDependent.A const AOA = ActiveObject.A const SCA = SkillCombined.A const SCA_ = SkillCombinedA_ const ELA = ExperienceLevel.A const SA = Skill.A const SAL = Skill.AL const SDA = SkillDependent.A /** * `getExceptionalSkillBonus skillId exceptionalSkillStateEntry` * @param skillId The skill's id. * @param exceptionalSkill The state entry of Exceptional Skill. */ export const getExceptionalSkillBonus = (exceptionalSkill : Maybe<Record<ActivatableDependent>>) => (skillId : string) : number => maybe (0) (pipe ( ADA.active, countWith (pipe ( AOA.sid, elem<string | number> (skillId) )) )) (exceptionalSkill) /** * Creates the base for a list for calculating the maximum of a skill based on * the skill check's atrributes' values. */ export const getMaxSRByCheckAttrs = (attrs : HeroModel["attributes"]) => (wiki_entry : EntryWithCheck) : number => pipe_ ( wiki_entry, SAL.check, getSkillCheckValues (attrs), consF (8), maximum, add (2) ) /** * Adds the maximum skill rating defined by the chosen experience level to the * list created by `getInitialMaximumList` if the hero is in character creation * phase. */ export const getMaxSRFromEL = (startEL : Record<ExperienceLevel>) => (phase : number) : Maybe<number> => phase < 3 ? Just (ELA.maxSkillRating (startEL)) : Nothing /** * Returns the maximum skill rating for the passed skill. */ export const getSkillMax = (startEL : Record<ExperienceLevel>) => (phase : number) => (attributes : OrderedMap<string, Record<AttributeDependent>>) => (exceptionalSkill : Maybe<Record<ActivatableDependent>>) => (wiki_entry : Record<Skill>) : number => pipe_ ( List ( Just (getMaxSRByCheckAttrs (attributes) (wiki_entry)), getMaxSRFromEL (startEL) (phase) ), catMaybes, minimum, add (getExceptionalSkillBonus (exceptionalSkill) (SA.id (wiki_entry))) ) /** * Returns if the passed skill's skill rating can be increased. */ export const isSkillIncreasable = (startEL : Record<ExperienceLevel>) => (phase : number) => (attrs : OrderedMap<string, Record<AttributeDependent>>) => (exceptionalSkill : Maybe<Record<ActivatableDependent>>) => (entry : Record<SkillCombined>) : boolean => SCA_.value (entry) < getSkillMax (startEL) (phase) (attrs) (exceptionalSkill) (SCA.wikiEntry (entry)) const getMinSRByCraftInstruments = (state : HeroModelRecord) => (entry : Record<SkillCombined>) : Maybe<number> => { const id = SCA_.id (entry) const { CraftInstruments } = SpecialAbilityId if ((id === SkillId.Woodworking || id === SkillId.Metalworking) && isMaybeActive (lookupF (HA.specialAbilities (state)) (CraftInstruments))) { // Sum of Woodworking and Metalworking must be at least 12. const MINIMUM_SUM = 12 const otherSkillId = id === SkillId.Woodworking ? SkillId.Metalworking : SkillId.Woodworking const otherSkillRating = pipe_ ( state, HA.skills, lookup <string> (otherSkillId), fmap (SDA.value), sum ) return Just (MINIMUM_SUM - otherSkillRating) } return Nothing } /** * Check if the dependencies allow the passed skill to be decreased. */ const getMinSRByDeps = (staticData : StaticDataRecord) => (hero : HeroModelRecord) => (entry : Record<SkillCombined>) : Maybe<number> => pipe_ ( entry, SCA_.dependencies, flattenDependencies (staticData) (hero), ensure (notNull), fmap (maximum) ) /** * Returns the minimum skill rating for the passed skill. */ export const getSkillMin = (staticData : StaticDataRecord) => (hero : HeroModelRecord) => (entry : Record<SkillCombined>) : Maybe<number> => pipe_ ( List ( getMinSRByDeps (staticData) (hero) (entry), getMinSRByCraftInstruments (hero) (entry) ), catMaybes, ensure (notNull), fmap (maximum) ) /** * Returns if the passed skill's skill rating can be decreased. */ export const isSkillDecreasable = (staticData : StaticDataRecord) => (hero : HeroModelRecord) => (entry : Record<SkillCombined>) : boolean => SCA_.value (entry) > sum (getSkillMin (staticData) (hero) (entry)) const hasSkillFrequencyRating = (category : EntryRating) => (rating : OrderedMap<string, EntryRating>) => pipe ( SA.id, lookupF (rating), elem <EntryRating> (category) ) /** * Is the skill common in the hero's culture? */ export const isSkillCommon : (rating : OrderedMap<string, EntryRating>) => (wiki_entry : Record<Skill>) => boolean = hasSkillFrequencyRating (EntryRating.Common) /** * Is the skill uncommon in the hero's culture? */ export const isSkillUncommon : (rating : OrderedMap<string, EntryRating>) => (wiki_entry : Record<Skill>) => boolean = hasSkillFrequencyRating (EntryRating.Uncommon) const ROUTINE_ATTR_THRESHOLD = 13 /** * Returns the total of missing attribute points for a routine check without * using the optional rule for routine checks, because the minimum attribute * value is 13 in that case. */ const getMissingPoints = (checkAttributeValues : List<number>) => foldr ((attr : number) : ident<number> => attr < ROUTINE_ATTR_THRESHOLD ? add (ROUTINE_ATTR_THRESHOLD - attr) : ident) (0) (checkAttributeValues) /** * Returns the minimum check modifier from which a routine check is possible * without using the optional rule for routine checks. */ const getBaseMinCheckMod = (sr : number) => -Math.floor ((sr - 1) / 3) + 3 /** * Returns the minimum check modifier from which a routine check is possible for * the passed skill rating. Returns `Nothing` if no routine check is possible, * otherwise a `Just` of a pair, where the first value is the minimum check * modifier and the second a boolean, where `True` states that the minimum check * modifier is only valid when using the optional rule for routine checks, thus * otherwise a routine check would not be possible. */ export const getMinCheckModForRoutine : (checkAttributeValues : List<number>) => (skillRating : number) => Maybe<Pair<number, boolean>> = checkAttrValues => pipe ( // Routine checks do only work if the SR is larger than 0 ensure (gt (0)), bindF (sr => { const missingPoints = getMissingPoints (checkAttrValues) const checkModThreshold = getBaseMinCheckMod (sr) const dependentCheckMod = checkModThreshold + missingPoints return dependentCheckMod < 4 ? Just (Pair (dependentCheckMod, missingPoints > 0)) : Nothing }) )
the_stack
import * as assert from "assert"; import * as llvm from "llvm-node"; import * as ts from "typescript"; import {CodeGenerationContext} from "../code-generation-context"; import {NameMangler, Parameter} from "../name-mangler"; import {TypePlace, TypeScriptToLLVMTypeConverter} from "../util/typescript-to-llvm-type-converter"; import {ObjectReference} from "./object-reference"; import {ResolvedFunction} from "./resolved-function"; export interface FunctionProperties { linkage: llvm.LinkageTypes; readonly: boolean; readnone: boolean; alwaysInline: boolean; noInline: boolean; noUnwind: boolean; visibility: llvm.VisibilityTypes; } /** * Factory for creating the declarations of llvm functions */ export class FunctionFactory { /** * Creates a new instance that uses the given name mangler * @param nameMangler the name mangler to use * @param typeConverter the type converter used to convert the return and argument types to llvm types */ constructor(private nameMangler: NameMangler, private typeConverter: TypeScriptToLLVMTypeConverter) { } /** * Creates the declaration (and if needed the definition) for the given resolved function called with the specified number of arguments * @param resolvedFunction the function to call (specific function, not overload) * @param numberOfArguments the number of arguments passed to the function (to know where optional arguments are unset) * @param context the code generation context * @param properties properties of the function to create, e.g. is the function readonly, what is the linkage * @return {Function} the existing function instance or the newly declared function */ getOrCreate(resolvedFunction: ResolvedFunction, numberOfArguments: number, context: CodeGenerationContext, properties?: Partial<FunctionProperties>): llvm.Function { return this.getOrCreateStaticOrInstanceFunction(resolvedFunction, numberOfArguments, context, this.getInitializedProperties(properties)); } /** * Creates the declaration (and if needed the definition) for the given resolved function called with the specified number of arguments. * The declared function is a instance method that needs to be called with the object instance as first argument * @param objectReference the object to which the method belongs * @param resolvedFunction the resolved function (not overloaded) * @param numberOfArguments the number of arguments passed to the function * @param context the code generation context * @param properties properties of the function to create, e.g. is the function readonly, what is the linkage * @return {Function} the existing or newly declared function */ getOrCreateInstanceMethod(objectReference: ObjectReference, resolvedFunction: ResolvedFunction, numberOfArguments: number, context: CodeGenerationContext, properties?: Partial<FunctionProperties>) { assert(resolvedFunction.instanceMethod && resolvedFunction.classType, "Resolved function needs to be an instance method"); return this.getOrCreateStaticOrInstanceFunction( resolvedFunction, numberOfArguments, context, this.getInitializedProperties(properties), objectReference ); } private getInitializedProperties(properties?: Partial<FunctionProperties>): FunctionProperties { return Object.assign({}, this.getDefaultFunctionProperties(), properties); } protected getDefaultFunctionProperties(): FunctionProperties { return { linkage: llvm.LinkageTypes.LinkOnceODRLinkage, readonly: false, readnone: false, alwaysInline: false, noInline: false, noUnwind: false, visibility: llvm.VisibilityTypes.Default }; } private getOrCreateStaticOrInstanceFunction(resolvedFunction: ResolvedFunction, numberOfArguments: number, context: CodeGenerationContext, properties: FunctionProperties, objectReference?: ObjectReference) { const mangledName = this.getMangledFunctionName(resolvedFunction, numberOfArguments); let fn = context.module.getFunction(mangledName); if (!fn) { fn = this.createFunction(mangledName, resolvedFunction, numberOfArguments, context, properties, objectReference); } return fn; } protected createFunction(mangledName: string, resolvedFunction: ResolvedFunction, numberOfArguments: number, context: CodeGenerationContext, properties: FunctionProperties, objectReference?: ObjectReference) { const llvmArgumentTypes = this.toLlvmArgumentTypes(resolvedFunction, numberOfArguments, context, objectReference); const functionType = llvm.FunctionType.get(this.typeConverter.convert(resolvedFunction.returnType, TypePlace.RETURN_VALUE), llvmArgumentTypes, false); const fn = llvm.Function.create(functionType, properties.linkage, mangledName, context.module); fn.visibility = properties.visibility; for (const attribute of this.getFunctionAttributes(properties)) { fn.addFnAttr(attribute); } this.attributeParameters(fn, resolvedFunction, context, objectReference); if (resolvedFunction.returnType.flags & ts.TypeFlags.Object) { const classReference = context.resolveClass(resolvedFunction.returnType)!; // If object can be undefined, or null fn.addDereferenceableAttr(0, classReference.getTypeStoreSize(resolvedFunction.returnType as ts.ObjectType, context)); } if (resolvedFunction.returnType.flags & ts.TypeFlags.BooleanLike) { fn.addAttribute(0, llvm.Attribute.AttrKind.ZExt); } return fn; } private getFunctionAttributes(properties: FunctionProperties) { const attributes = []; if (properties.noUnwind) { attributes.push(llvm.Attribute.AttrKind.NoUnwind); } if (properties.alwaysInline) { attributes.push(llvm.Attribute.AttrKind.AlwaysInline); } if (properties.noInline) { attributes.push(llvm.Attribute.AttrKind.NoInline); } if (properties.readonly) { attributes.push(llvm.Attribute.AttrKind.ReadOnly); } if (properties.readnone) { attributes.push(llvm.Attribute.AttrKind.ReadNone); } return attributes; } private attributeParameters(fn: llvm.Function, resolvedFunction: ResolvedFunction, context: CodeGenerationContext, object?: ObjectReference) { const parameters = fn.getArguments(); let argumentOffset = 0; if (object) { const self = parameters[0]; self.addAttr(llvm.Attribute.AttrKind.ReadOnly); self.addDereferenceableAttr(object.getTypeStoreSize(context)); argumentOffset = 1; } for (let i = argumentOffset; i < parameters.length; ++i) { const parameter = parameters[i]; const parameterDefinition = resolvedFunction.parameters[i - argumentOffset]; if (parameterDefinition.variadic) { break; } if (parameterDefinition.type.flags & ts.TypeFlags.BooleanLike) { parameter.addAttr(llvm.Attribute.AttrKind.ZExt); } if (parameterDefinition.type.flags & ts.TypeFlags.Object) { const classReference = context.resolveClass(parameterDefinition.type as ts.ObjectType); if (classReference) { parameter.addDereferenceableAttr(classReference.getTypeStoreSize(parameterDefinition.type as ts.ObjectType, context)); } } } } private getMangledFunctionName(resolvedFunction: ResolvedFunction, numberOfArguments: number) { const usedParameters: Parameter[] = []; for (let i = 0; i < resolvedFunction.parameters.length; ++i) { const parameter = resolvedFunction.parameters[i]; if (parameter.optional && !parameter.initializer && numberOfArguments <= i) { break; // Optional parameter that is not set. Therefore, this parameter is not actually used } usedParameters.push(parameter); } return this.mangleFunctionName(resolvedFunction, usedParameters); } protected mangleFunctionName(resolvedFunction: ResolvedFunction, usedParameters: Parameter[]) { if (resolvedFunction.classType) { return this.nameMangler.mangleMethodName( resolvedFunction.classType, resolvedFunction.functionName!, usedParameters, resolvedFunction.sourceFile ); } return this.nameMangler.mangleFunctionName(resolvedFunction.functionName, usedParameters, resolvedFunction.sourceFile); } private toLlvmArgumentTypes(resolvedFunction: ResolvedFunction, numberOfArguments: number, context: CodeGenerationContext, objectReference?: ObjectReference) { const argumentTypes = objectReference ? [this.typeConverter.convert(objectReference.type, TypePlace.THIS)] : []; for (let i = 0; i < resolvedFunction.parameters.length; ++i) { const parameter = resolvedFunction.parameters[i]; if (parameter.variadic) { const elementType = (parameter.type as ts.GenericType).typeArguments[0]; argumentTypes.push(this.typeConverter.convert(elementType, TypePlace.PARAMETER).getPointerTo(), llvm.Type.getInt32Ty(context.llvmContext)); break; } else if (parameter.optional && !parameter.initializer && numberOfArguments <= i) { // optional argument that is not set, skip break; } else { argumentTypes.push(this.typeConverter.convert(parameter.type, TypePlace.PARAMETER)); } } return argumentTypes; } }
the_stack
import { getFlags } from "./server"; import "@testing-library/jest-dom/extend-expect"; import * as fetchMock from "fetch-mock-jest"; import { configure, _resetConfig } from "./config"; import { GetServerSidePropsContext, GetStaticPropsContext } from "next"; import { nanoid } from "nanoid"; jest.mock("nanoid", () => { return { nanoid: jest.fn() }; }); beforeEach(() => { _resetConfig(); fetchMock.reset(); }); describe("when called without configure", () => { it("should throw", async () => { expect(() => getFlags({ context: {} as any })).toThrow( Error("@happykit/flags: Missing configuration. Call configure() first.") ); }); }); describe("server-side rendering (pure + hybrid)", () => { describe("when traits are passed in", () => { it("forwards the passed in traits", async () => { configure({ envKey: "flags_pub_000000" }); fetchMock.post( { url: "https://happykit.dev/api/flags/flags_pub_000000", body: { traits: { teamMember: true }, user: null, visitorKey: "V1StGXR8_Z5jdHi6B-myT", }, }, { headers: { "content-type": "application/json" }, body: { flags: { meal: "large" }, visitor: { key: "V1StGXR8_Z5jdHi6B-myT" }, }, } ); const context = { req: { headers: { cookie: "hkvk=V1StGXR8_Z5jdHi6B-myT" }, socket: { remoteAddress: "128.242.245.116" }, }, res: { setHeader: jest.fn() as any }, } as Partial<GetServerSidePropsContext>; expect(await getFlags({ context, traits: { teamMember: true } })).toEqual( { flags: { meal: "large" }, data: { flags: { meal: "large" }, visitor: { key: "V1StGXR8_Z5jdHi6B-myT" }, }, error: null, initialFlagState: { input: { endpoint: "https://happykit.dev/api/flags", envKey: "flags_pub_000000", requestBody: { traits: { teamMember: true }, user: null, visitorKey: "V1StGXR8_Z5jdHi6B-myT", }, }, outcome: { data: { flags: { meal: "large" }, visitor: { key: "V1StGXR8_Z5jdHi6B-myT" }, }, }, }, } ); // refresh of cookie expect(context.res!.setHeader).toHaveBeenCalledWith( "Set-Cookie", "hkvk=V1StGXR8_Z5jdHi6B-myT; Path=/; Max-Age=15552000; SameSite=Lax" ); }); }); describe("when user is passed in", () => { it("forwards the passed in user", async () => { configure({ envKey: "flags_pub_000000" }); fetchMock.post( { url: "https://happykit.dev/api/flags/flags_pub_000000", body: { traits: null, user: { key: "random-user-key", name: "joe" }, visitorKey: "V1StGXR8_Z5jdHi6B-myT", }, }, { headers: { "content-type": "application/json" }, body: { flags: { meal: "large" }, visitor: { key: "V1StGXR8_Z5jdHi6B-myT" }, }, } ); const context = { req: { headers: { cookie: "hkvk=V1StGXR8_Z5jdHi6B-myT" }, socket: { remoteAddress: "128.242.245.116" }, }, res: { setHeader: jest.fn() as any }, } as Partial<GetServerSidePropsContext>; expect( await getFlags({ context, user: { key: "random-user-key", name: "joe" }, }) ).toEqual({ flags: { meal: "large" }, data: { flags: { meal: "large" }, visitor: { key: "V1StGXR8_Z5jdHi6B-myT" }, }, error: null, initialFlagState: { input: { endpoint: "https://happykit.dev/api/flags", envKey: "flags_pub_000000", requestBody: { traits: null, user: { key: "random-user-key", name: "joe" }, visitorKey: "V1StGXR8_Z5jdHi6B-myT", }, }, outcome: { data: { flags: { meal: "large" }, visitor: { key: "V1StGXR8_Z5jdHi6B-myT" }, }, }, }, }); expect(context.res!.setHeader).toHaveBeenCalledWith( "Set-Cookie", "hkvk=V1StGXR8_Z5jdHi6B-myT; Path=/; Max-Age=15552000; SameSite=Lax" ); }); }); describe("when no cookie exists on initial request", () => { it("generates and sets the hkvk cookie", async () => { configure({ envKey: "flags_pub_000000" }); // @ts-ignore nanoid.mockReturnValueOnce("V1StGXR8_Z5jdHi6B-myT"); fetchMock.post( { url: "https://happykit.dev/api/flags/flags_pub_000000", body: { traits: null, user: null, // nanoid is mocked to return "V1StGXR8_Z5jdHi6B-myT", // so the generated id is always this one visitorKey: "V1StGXR8_Z5jdHi6B-myT", }, }, { headers: { "content-type": "application/json" }, body: { flags: { meal: "large" }, visitor: { key: "V1StGXR8_Z5jdHi6B-myT" }, }, } ); const context = { req: { headers: { cookie: "foo=bar" }, socket: { remoteAddress: "128.242.245.116" }, }, res: { setHeader: jest.fn() as any }, } as Partial<GetServerSidePropsContext>; expect(await getFlags({ context })).toEqual({ flags: { meal: "large" }, data: { flags: { meal: "large" }, visitor: { key: "V1StGXR8_Z5jdHi6B-myT" }, }, error: null, initialFlagState: { input: { endpoint: "https://happykit.dev/api/flags", envKey: "flags_pub_000000", requestBody: { traits: null, user: null, visitorKey: "V1StGXR8_Z5jdHi6B-myT", }, }, outcome: { data: { flags: { meal: "large" }, visitor: { key: "V1StGXR8_Z5jdHi6B-myT" }, }, }, }, }); expect(context.res!.setHeader).toHaveBeenCalledWith( "Set-Cookie", "hkvk=V1StGXR8_Z5jdHi6B-myT; Path=/; Max-Age=15552000; SameSite=Lax" ); }); }); describe("when loading times out", () => { it("aborts the request", async () => { configure({ envKey: "flags_pub_000000", serverLoadingTimeout: 50 }); const routeMock = fetchMock.post( { url: "https://happykit.dev/api/flags/flags_pub_000000", body: { traits: null, user: null, visitorKey: "V1StGXR8_Z5jdHi6B-myT", }, }, { // Not used as request times out headers: { "content-type": "application/json" }, body: { flags: { meal: "large" }, visitor: { key: "V1StGXR8_Z5jdHi6B-myT" }, }, }, // This delay is longer than the serverLoadingTimeout, so the request // times out { delay: 250 } ); const context = { req: { headers: { cookie: "hkvk=V1StGXR8_Z5jdHi6B-myT" }, socket: { remoteAddress: "128.242.245.116" }, }, res: { setHeader: jest.fn() as any }, } as Partial<GetServerSidePropsContext>; expect(await getFlags({ context })).toEqual({ flags: {}, data: null, error: "request-timed-out", initialFlagState: { input: { endpoint: "https://happykit.dev/api/flags", envKey: "flags_pub_000000", requestBody: { visitorKey: "V1StGXR8_Z5jdHi6B-myT", user: null, traits: null, }, }, outcome: { error: "request-timed-out" }, }, }); // This doesn't seem to work // // The intention is to not leave any open handles as the fetch mock // doesn't seem to support aborting a request and will leave it open. await routeMock.flush(true); }); }); }); describe("static site generation (pure + hybrid)", () => { it("should set static to true", async () => { configure({ envKey: "flags_pub_000000" }); fetchMock.post( { url: "https://happykit.dev/api/flags/flags_pub_000000", body: { traits: null, user: null, visitorKey: null, }, }, { headers: { "content-type": "application/json" }, body: { flags: { meal: "large" }, visitor: null }, } ); expect(await getFlags({ context: {} as GetStaticPropsContext })).toEqual({ flags: { meal: "large" }, data: { flags: { meal: "large" }, visitor: null, }, error: null, initialFlagState: { input: { endpoint: "https://happykit.dev/api/flags", envKey: "flags_pub_000000", requestBody: { traits: null, user: null, visitorKey: null, }, }, outcome: { data: { flags: { meal: "large" }, visitor: null, }, }, }, }); }); describe("when traits are passed in", () => { it("forwards given traits", async () => { configure({ envKey: "flags_pub_000000" }); fetchMock.post( { url: "https://happykit.dev/api/flags/flags_pub_000000", body: { traits: { friendly: true }, user: null, visitorKey: null, }, }, { headers: { "content-type": "application/json" }, body: { flags: { meal: "large" }, visitor: null }, } ); expect( await getFlags({ context: {} as GetStaticPropsContext, traits: { friendly: true }, }) ).toEqual({ flags: { meal: "large" }, data: { flags: { meal: "large" }, visitor: null, }, error: null, initialFlagState: { input: { endpoint: "https://happykit.dev/api/flags", envKey: "flags_pub_000000", requestBody: { traits: { friendly: true }, user: null, visitorKey: null, }, }, outcome: { data: { flags: { meal: "large" }, visitor: null, }, }, }, }); }); }); describe("when user is passed in", () => { it("forwards a given user", async () => { configure({ envKey: "flags_pub_000000" }); fetchMock.post( { url: "https://happykit.dev/api/flags/flags_pub_000000", body: { traits: null, user: { key: "random-user-key", name: "joe" }, visitorKey: null, }, }, { headers: { "content-type": "application/json" }, body: { flags: { meal: "large" }, visitor: null }, } ); expect( await getFlags({ context: {} as GetStaticPropsContext, user: { key: "random-user-key", name: "joe" }, }) ).toEqual({ flags: { meal: "large" }, data: { flags: { meal: "large" }, visitor: null, }, error: null, initialFlagState: { input: { endpoint: "https://happykit.dev/api/flags", envKey: "flags_pub_000000", requestBody: { traits: null, user: { key: "random-user-key", name: "joe" }, visitorKey: null, }, }, outcome: { data: { flags: { meal: "large" }, visitor: null, }, }, }, }); }); }); describe("when loading times out", () => { it("aborts the request", async () => { configure({ envKey: "flags_pub_000000", staticLoadingTimeout: 75 }); const routeMock = fetchMock.post( { url: "https://happykit.dev/api/flags/flags_pub_000000", body: { traits: null, user: null, visitorKey: null, }, }, { // Not used as request times out headers: { "content-type": "application/json" }, body: { flags: { meal: "large" }, visitor: null }, }, // This delay is longer than the serverLoadingTimeout, so the request // times out { delay: 250 } ); expect(await getFlags({ context: {} as GetStaticPropsContext })).toEqual({ flags: {}, data: null, error: "request-timed-out", initialFlagState: { input: { endpoint: "https://happykit.dev/api/flags", envKey: "flags_pub_000000", requestBody: { visitorKey: null, user: null, traits: null, }, }, outcome: { error: "request-timed-out" }, }, }); // This doesn't seem to work // // The intention is to not leave any open handles as the fetch mock // doesn't seem to support aborting a request and will leave it open. await routeMock.flush(true); }); }); });
the_stack
'use strict'; import {EVCb, NluMap, NluMapItem} from "./index"; //core import * as util from 'util'; import * as cp from 'child_process'; import * as fs from 'fs'; //npm import chalk from 'chalk'; import async = require('async'); //project import log from './logging'; import {determineIfReinstallIsNeeded, flattenDeep, getDevKeys, getPath} from "./utils"; import * as path from "path"; interface BinFieldObject { [key: string]: string } /////////////////////////////////////////////////////////////////////////////////////////// export const runNPMLink = (map: NluMap, opts: any, cb: EVCb<null>) => { const keys = Object.keys(map); if (keys.length < 1) { return process.nextTick(cb, 'NLU could not find any dependencies on the filesystem;' + ' perhaps broaden your search using searchRoots.'); } if (opts.dry_run) { log.warning('given the --treeify option passed at the command line, npm-link-up will only print out the dependency tree and exit.'); log.veryGood('the following is a complete list of recursively related dependencies:\n'); log.veryGood(util.inspect(Object.keys(map))); return process.nextTick(cb); } if (opts.verbosity > 2) { log.info('Dependency map:'); } Object.keys(map).forEach(function (k) { if (opts.verbosity > 2) { log.info('Info for project:', chalk.bold(k)); console.log(chalk.green.bold(util.inspect(map[k]))); console.log(); } }); const isAllLinked = function () { //Object.values might not be available on all Node.js versions. return Object.keys(map).every(k => map[k].isLinked); }; const getCountOfUnlinkedDeps = (dep: NluMapItem) => { return dep.deps.filter(d => { if (!map[d]) { log.warning(`there is no dependency named '${d}' in the map.`); return false; } return !map[d].isLinked; }).length; }; const findNextDep = function () { // not anymore: this routine finds the next dep, that has no deps or no unlinked dependencies // this routine finds the next dep with the fewest number of unlinked dependencies let dep; let count = null; for (let dir of Object.keys(map)) { let d = map[dir]; if (!d.isLinked) { if (!count) { dep = d; count = dep.deps.length; } else if (getCountOfUnlinkedDeps(d) < count) { dep = d; count = dep.deps.length; } } } if (!dep) { log.error( 'Internal implementation error => no dep found, but there should be at least one yet-to-be-linked dep.' ); return process.exit(1); } return dep; }; const getNPMLinkList = (dep: NluMapItem): Array<string> => { if (opts.umbrella && dep.isMainProject) { return []; } const deps = dep.deps.map(getPath(map, dep, opts)); // map from package name to the desired package path const isAccessible = (path: string) => { const searchRoots = dep.searchRoots; const matched = searchRoots.some(r => path.startsWith(r)); if (!matched) { log.error('The following dep', path, 'is not accessible for project at path:', dep.path) } return matched; }; return deps.filter(Boolean).filter(d => { if (!map[d]) { log.warning('Map for key => "' + d + '" is not defined.'); return false; } return map[d] && map[d].isLinked && isAccessible(map[d].path); }) .map((d: string) => { const {path, name, bin} = map[d]; if (dep.installedSet.has(name)) { throw new Error('Already installed a package with name: ' + name + ', into dep: ' + util.inspect(dep)); } dep.installedSet.add(name); if (dep.linkedSet[path]) { throw new Error(`Already linked ${path} to dep: ` + util.inspect(dep)); } dep.linkedSet[path] = map[d]; if (path !== d) { throw new Error('The "path" field and the map entry should be the same.'); } // return ` npm link ${d} -f `; return ` mkdir -p "node_modules/${name}" && rm -rf "node_modules/${name}" && mkdir -p "node_modules/${name}" && rm -rf "node_modules/${name}" && ln -sf "${path}" "node_modules/${name}" ${getBinMap(bin, path, name)} `; }); }; const getBinMap = (bin: string | BinFieldObject, path: string, name: string) => { if (!bin) { return ''; } if (typeof bin === 'string') { return ` && mkdir -p "node_modules/.bin" && ln -sf "${path}/${bin}" "node_modules/.bin/${name}" ` } const keys = Object.keys(bin); if (keys.length < 1) { return ''; } return ` && ` + keys.map(k => { return ` mkdir -p "node_modules/.bin" && ln -sf "${path}/${bin[k]}" "node_modules/.bin/${k}" ` }) .join(' && '); }; const getCommandListOfLinked = (dep: NluMapItem) => { const name = dep.name; const path = dep.path; const bin = map[path] && map[path].bin; if (!path) { log.error(`missing "path" field for dependency with name "${name}"`); return process.exit(1); } if (!bin) { log.warn(`missing "bin" field for dependency with name "${name}"`); // return process.exit(1); } if (dep.bin !== bin) { throw new Error('"bin" fields do not match => ' + util.inspect(dep)); } const isAccessible = (dep: NluMapItem) => { const searchRoots = dep.searchRoots; return searchRoots.some(r => path.startsWith(r)); }; return Object.keys(map).filter(k => { return map[k].isLinked && map[k].deps.includes(name) && isAccessible(map[k]); }) .map(k => { const p = `${map[k].path}`; if (map[k].installedSet.has(name)) { throw new Error('Already installed a package with name: ' + name + ', into dep: ' + util.inspect(map[k])); } map[k].installedSet.add(name); if (map[k].linkedSet[path]) { throw new Error(`Already linked ${path} to dep: ` + util.inspect(map[k])); } map[k].linkedSet[path] = dep; if (p !== k) { throw new Error(`Paths should be the same: [1] '${p}', [2] '${k}'.`); } return ` cd "${p}" && mkdir -p "node_modules/${name}" && rm -rf "node_modules/${name}" && mkdir -p "node_modules/${name}" && rm -rf "node_modules/${name}" && ln -sf "${path}" "node_modules/${name}" ${getBinMap(bin, path, name)} `; }); }; const getInstallCommand = (dep: NluMapItem) => { if (opts.umbrella && dep.isMainProject === true) { return; } if (opts.no_install) { return; } if (dep.runInstall || opts.install_all || (dep.isMainProject && opts.install_main)) { const installProd = opts.production ? ' --production ' : ''; return ` && rm -rf node_modules && npm install --cache-min 999999 --loglevel=warn ${installProd}`; } }; const getLinkToItselfCommand = (dep: NluMapItem) => { if (opts.umbrella && dep.isMainProject) { return; } if (opts.no_link) { return; } if (opts.self_link_all || dep.linkToItself === true) { return ` && mkdir -p "node_modules/${dep.name}" ` + ` && rm -rf "node_modules/${dep.name}" && mkdir -p "node_modules/${dep.name}" ` + ` && rm -rf "node_modules/${dep.name}" ` + ` && ln -sf "${dep.path}" "node_modules/${dep.name}" `; } }; const getGlobalLinkCommand = (dep: NluMapItem) => { if (opts.umbrella && dep.isMainProject) { return; } if (opts.no_link) { return; } if (opts.link_all || (dep.isMainProject && opts.link_main)) { const installProd = opts.production ? ' --production ' : ''; return ` && mkdir -p "node_modules/.bin" && npm link --cache-min 999999 -f ${installProd} `; } }; async.until(isAllLinked, (cb: EVCb<any>) => { if (opts.verbosity > 2) { log.info(`Searching for next dep to run.`); } const dep = findNextDep(); if (opts.verbosity > 1) { log.info(`Processing dep with name => '${chalk.bold(dep.name)}'.`); } const nm = path.resolve(dep.path + '/node_modules'); determineIfReinstallIsNeeded(nm, dep, getDevKeys(dep.package), opts, (err, val) => { if (err) { log.warn(`Error generated from determining if npm (re)install was is necessary for package: ${dep.name} =>`, err); } if (val === true) { dep.runInstall = true; } const deps = getNPMLinkList(dep); const links = deps.length > 0 ? ' && ' + deps.join(' && ') : ''; const script = [ `cd "${dep.path}"`, getInstallCommand(dep), getGlobalLinkCommand(dep), links, getLinkToItselfCommand(dep) ] .filter(Boolean) .join(' '); if (opts.verbosity > 2) { log.info(`First-pass script is => "${chalk.blueBright.bold(script)}"`); } const k = cp.spawn('bash', [], { env: Object.assign({}, process.env, { NPM_LINK_UP: 'yes' }) }); k.stdin.end(script); k.stdout.setEncoding('utf8'); k.stderr.setEncoding('utf8'); k.stderr.pipe(process.stderr); if (opts.verbosity > 2) { k.stdout.pipe(process.stdout); } let stderr = ''; k.stderr.on('data', function (d) { stderr += d; }); k.once('error', cb); k.once('exit', code => { if (code > 0 && /ERR/i.test(stderr)) { log.error(`Dep with name "${dep.name}" is done, but with an error.`); return cb({code, dep, error: stderr}); } dep.isLinked = map[dep.path].isLinked = true; const linkPreviouslyUnlinked = function (cb: EVCb<any>) { const cmds = getCommandListOfLinked(dep); if (!cmds.length) { return process.nextTick(cb); } const cmd = cmds.join(' && '); if (opts.verbosity > 2) { log.info(`Running this command for "${chalk.bold(dep.name)}" => '${chalk.blueBright(cmd)}'.`); } const k = cp.spawn('bash', [], { env: Object.assign({}, process.env, { NPM_LINK_UP: 'yes' }) }); k.stdin.write(cmd); k.stdout.setEncoding('utf8'); k.stderr.setEncoding('utf8'); k.stderr.pipe(process.stderr, {end: false}); if (opts.verbosity > 2) { k.stdout.pipe(process.stdout, {end: false}); } k.stdin.end(); k.once('exit', cb); }; linkPreviouslyUnlinked((err: any) => { if (err) { log.error(`Dep with name "${dep.name}" is done, but with an error => `, err.message || err); } else if (opts.verbosity > 1) { log.veryGood(`Dep with name '${chalk.bold(dep.name)}' is done.`); } cb(err, { code: code, dep: dep, error: stderr }); }); }); }); }, cb); };
the_stack
import { ReflectedValue } from "./ReflectedValue"; import { ReflectedValueType } from "@as-pect/assembly/assembly/internal/ReflectedValueType"; import chalk from "chalk"; class StringifyContext { public level: number = 0; public impliedTypeInfo: boolean = false; public seen: WeakSet<ReflectedValue> = new WeakSet<ReflectedValue>(); public keywordFormatter: (prop: string) => string = chalk.yellow; public stringFormatter: (prop: string) => string = chalk.cyan; public classNameFormatter: (prop: string) => string = chalk.green; public numberFormatter: (prop: string) => string = chalk.white; public indent: number = 0; public maxPropertyCount: number = 50; public maxLineLength: number = 80; public maxExpandLevel: number = 3; public tab: number = 4; } export type StringifyReflectedValueProps = { keywordFormatter: (prop: string) => string; stringFormatter: (prop: string) => string; classNameFormatter: (prop: string) => string; numberFormatter: (prop: string) => string; indent: number; tab: number; maxPropertyCount: number; maxLineLength: number; maxExpandLevel: number; }; export function stringifyReflectedValue( reflectedValue: ReflectedValue, props: Partial<StringifyReflectedValueProps>, ): string { const context = new StringifyContext(); /* istanbul ignore next */ if (props.keywordFormatter) context.keywordFormatter = props.keywordFormatter; /* istanbul ignore next */ if (props.stringFormatter) context.stringFormatter = props.stringFormatter; /* istanbul ignore next */ if (props.classNameFormatter) context.classNameFormatter = props.classNameFormatter; /* istanbul ignore next */ if (props.numberFormatter) context.numberFormatter = props.numberFormatter; /* istanbul ignore next */ if (props.maxExpandLevel) context.maxExpandLevel = props.maxExpandLevel; /* istanbul ignore next */ if (typeof props.indent === "number") context.indent = props.indent; /* istanbul ignore next */ if (typeof props.tab === "number") context.tab = props.tab; /* istanbul ignore next */ if (typeof props.maxPropertyCount === "number") context.maxPropertyCount = props.maxPropertyCount; /* istanbul ignore next */ if (typeof props.maxLineLength === "number") context.maxLineLength = props.maxLineLength; return formatters[ formatterIndexFor(reflectedValue.type, ReflectedValueFormatType.Expanded) ](reflectedValue, context); } type ReflectedNameTypeFormatter = ( reflectedValue: ReflectedValue, ctx: StringifyContext, ) => string; const enum ReflectedValueFormatType { Expanded = 0, Inline = 1, Key = 2, Value = 3, } const formatters: ReflectedNameTypeFormatter[] = []; /* istanbul ignore next */ const emptyFormatter = () => ""; for (let i = 0; i < 14 * 4; i++) formatters.push(emptyFormatter); const formatterIndexFor = ( valueType: ReflectedValueType, type: ReflectedValueFormatType, ) => valueType * 4 + type; const falsyFormatter = (reflectedValue: ReflectedValue) => `${reflectedValue.negated ? "Not " : ""}Falsy`; formatters[ formatterIndexFor(ReflectedValueType.Falsy, ReflectedValueFormatType.Expanded) ] = falsyFormatter; const truthyFormatter = (reflectedValue: ReflectedValue) => `${reflectedValue.negated ? "Not " : ""}Truthy`; formatters[ formatterIndexFor( ReflectedValueType.Truthy, ReflectedValueFormatType.Expanded, ) ] = truthyFormatter; const finiteFormatter = (reflectedValue: ReflectedValue) => `${reflectedValue.negated ? "Not " : ""}Finite`; formatters[ formatterIndexFor( ReflectedValueType.Finite, ReflectedValueFormatType.Expanded, ) ] = finiteFormatter; function displayBooleanNoSpacing( reflectedValue: ReflectedValue, ctx: StringifyContext, ): string { return ctx.keywordFormatter(reflectedValue.value === 1 ? "true" : "false"); } function displayBooleanWithSpacing( reflectedValue: ReflectedValue, ctx: StringifyContext, ): string { return ( " ".repeat(ctx.indent + ctx.tab * ctx.level) + ctx.keywordFormatter(reflectedValue.value === 1 ? "true" : "false") ); } // Booleans formatters[ formatterIndexFor( ReflectedValueType.Boolean, ReflectedValueFormatType.Expanded, ) ] = displayBooleanWithSpacing; formatters[ formatterIndexFor(ReflectedValueType.Boolean, ReflectedValueFormatType.Inline) ] = displayBooleanNoSpacing; formatters[ formatterIndexFor(ReflectedValueType.Boolean, ReflectedValueFormatType.Key) ] = displayBooleanWithSpacing; formatters[ formatterIndexFor(ReflectedValueType.Boolean, ReflectedValueFormatType.Value) ] = displayBooleanNoSpacing; function displayClassNoSpacing( reflectedValue: ReflectedValue, ctx: StringifyContext, ): string { return ctx.classNameFormatter(`[${reflectedValue.typeName}]`); } function displayNumberWithSpacing( reflectedValue: ReflectedValue, ctx: StringifyContext, ): string { let numericString = reflectedValue.value.toString(); if ( reflectedValue.type === ReflectedValueType.Float && !/\.[0-9]/.test(numericString) ) { numericString += ".0"; } if ( ctx.impliedTypeInfo || reflectedValue.typeName === "i32" || reflectedValue.typeName === "f64" ) { return ( " ".repeat(ctx.indent + ctx.level * ctx.tab) + ctx.numberFormatter(numericString) ); } return ( " ".repeat(ctx.indent + ctx.level * ctx.tab) + `${ctx.numberFormatter(numericString)} ${ctx.keywordFormatter( "as", )} ${ctx.classNameFormatter(reflectedValue.typeName!)}` ); } function displayNumberNoSpacing( reflectedValue: ReflectedValue, ctx: StringifyContext, ): string { let numericString = reflectedValue.value.toString(); if ( reflectedValue.type === ReflectedValueType.Float && !/\.[0-9]/.test(numericString) ) { numericString += ".0"; } if ( ctx.impliedTypeInfo || reflectedValue.typeName === "i32" || reflectedValue.typeName === "f64" ) { return ctx.numberFormatter(numericString); } return `${ctx.numberFormatter(numericString)} ${ctx.classNameFormatter( `as ${reflectedValue.typeName}`, )}`; } // Floats formatters[ formatterIndexFor(ReflectedValueType.Float, ReflectedValueFormatType.Expanded) ] = displayNumberWithSpacing; formatters[ formatterIndexFor(ReflectedValueType.Float, ReflectedValueFormatType.Inline) ] = displayNumberNoSpacing; formatters[ formatterIndexFor(ReflectedValueType.Float, ReflectedValueFormatType.Key) ] = displayNumberWithSpacing; formatters[ formatterIndexFor(ReflectedValueType.Float, ReflectedValueFormatType.Value) ] = displayNumberNoSpacing; // Integers formatters[ formatterIndexFor( ReflectedValueType.Integer, ReflectedValueFormatType.Expanded, ) ] = displayNumberWithSpacing; formatters[ formatterIndexFor(ReflectedValueType.Integer, ReflectedValueFormatType.Inline) ] = displayNumberNoSpacing; formatters[ formatterIndexFor(ReflectedValueType.Integer, ReflectedValueFormatType.Key) ] = displayNumberWithSpacing; formatters[ formatterIndexFor(ReflectedValueType.Integer, ReflectedValueFormatType.Value) ] = displayNumberNoSpacing; function displayStringNoSpacing( reflectedValue: ReflectedValue, ctx: StringifyContext, ): string { return ctx.stringFormatter( `"${reflectedValue.value.toString().replace(/"/g, '\\"')}"`, ); } function displayStringWithSpacing( hostValue: ReflectedValue, ctx: StringifyContext, ): string { return ( " ".repeat(ctx.indent + ctx.level * ctx.tab) + ctx.stringFormatter(`"${hostValue.value.toString().replace(/"/g, '\\"')}"`) ); } function displayNoQuoteStringWithSpacing( hostValue: ReflectedValue, ctx: StringifyContext, ): string { return ( " ".repeat(ctx.indent + ctx.level * ctx.tab) + ctx.stringFormatter(`${hostValue.value.toString().replace(/"/g, '\\"')}`) ); } // Strings formatters[ formatterIndexFor( ReflectedValueType.String, ReflectedValueFormatType.Expanded, ) ] = displayStringWithSpacing; formatters[ formatterIndexFor(ReflectedValueType.String, ReflectedValueFormatType.Inline) ] = displayStringNoSpacing; formatters[ formatterIndexFor(ReflectedValueType.String, ReflectedValueFormatType.Key) ] = displayNoQuoteStringWithSpacing; formatters[ formatterIndexFor(ReflectedValueType.String, ReflectedValueFormatType.Value) ] = displayStringNoSpacing; function displayFunctionExpanded( hostValue: ReflectedValue, ctx: StringifyContext, ): string { return ( " ".repeat(ctx.indent + ctx.level * ctx.tab) + ctx.classNameFormatter( `[Function ${hostValue.pointer}: ${hostValue.value.toString()}]`, ) ); } const displayFuncNoNameNoPointer = (_: ReflectedValue, ctx: StringifyContext) => ctx.classNameFormatter("[Function]"); // Functions formatters[ formatterIndexFor( ReflectedValueType.Function, ReflectedValueFormatType.Expanded, ) ] = displayFunctionExpanded; formatters[ formatterIndexFor( ReflectedValueType.Function, ReflectedValueFormatType.Inline, ) ] = displayFuncNoNameNoPointer; formatters[ formatterIndexFor(ReflectedValueType.Function, ReflectedValueFormatType.Key) ] = displayFunctionExpanded; formatters[ formatterIndexFor(ReflectedValueType.Function, ReflectedValueFormatType.Value) ] = displayFunctionExpanded; function displayClassExpanded( hostValue: ReflectedValue, ctx: StringifyContext, ): string { const spacing = " ".repeat(ctx.level * ctx.tab + ctx.indent); if (ctx.seen.has(hostValue)) return spacing + ctx.classNameFormatter("[Circular Reference]"); const previousImpliedTypeInfo = ctx.impliedTypeInfo; ctx.impliedTypeInfo = false; if (hostValue.isNull) { if (previousImpliedTypeInfo) { return `${spacing}null`; } else { return `${spacing}${ctx.classNameFormatter( `<${hostValue.typeName}>`, )}null`; } } ctx.seen.add(hostValue); let body = "\n"; ctx.level += 1; const length = hostValue.keys!.length; const displayCount = Math.min(length, ctx.maxPropertyCount); for (let i = 0; i < displayCount; i++) { const key = hostValue.keys![i]; const keyString = formatters[ formatterIndexFor(key.type, ReflectedValueFormatType.Key) ](key, ctx); const value = hostValue.values![i]; const valueString = ctx.level < ctx.maxExpandLevel ? // render expanded value, but trim the whitespace on the left side formatters[ formatterIndexFor(value.type, ReflectedValueFormatType.Expanded) ](value, ctx).trimLeft() : // render value formatters[ formatterIndexFor(value.type, ReflectedValueFormatType.Inline) ](value, ctx).trimLeft(); if (i === displayCount - 1) { // remove last trailing comma body += `${keyString}: ${valueString}\n`; } else { body += `${keyString}: ${valueString},\n`; } } if (length > ctx.maxPropertyCount) body += `${spacing}... +${length - ctx.maxPropertyCount} properties`; ctx.level -= 1; ctx.impliedTypeInfo = previousImpliedTypeInfo; ctx.seen.delete(hostValue); if (previousImpliedTypeInfo) { return `${spacing}{${body}${spacing}}`; } else { return `${spacing}${ctx.classNameFormatter( hostValue.typeName!, )} {${body}${spacing}}`; } } function displayClassWithSpacing( hostValue: ReflectedValue, ctx: StringifyContext, ): string { return `${" ".repeat( ctx.level * ctx.tab + ctx.indent, )}${ctx.classNameFormatter(`[${hostValue.typeName}]`)}`; } // Classes formatters[ formatterIndexFor(ReflectedValueType.Class, ReflectedValueFormatType.Expanded) ] = displayClassExpanded; formatters[ formatterIndexFor(ReflectedValueType.Class, ReflectedValueFormatType.Inline) ] = displayClassNoSpacing; formatters[ formatterIndexFor(ReflectedValueType.Class, ReflectedValueFormatType.Key) ] = displayClassWithSpacing; formatters[ formatterIndexFor(ReflectedValueType.Class, ReflectedValueFormatType.Value) ] = displayClassExpanded; function displayArrayExpanded( hostValue: ReflectedValue, ctx: StringifyContext, ): string { const spacing = " ".repeat(ctx.level * ctx.tab + ctx.indent); if (ctx.seen.has(hostValue)) return spacing + ctx.classNameFormatter("[Circular Reference]"); ctx.seen.add(hostValue); const previousImpliedTypeInfo = ctx.impliedTypeInfo; ctx.impliedTypeInfo = true; if ( ctx.level < ctx.maxExpandLevel && hostValue.type === ReflectedValueType.Array ) { // expanded only for arrays let body = "\n"; ctx.level += 1; const length = Math.min(hostValue.values!.length, ctx.maxPropertyCount); for (let i = 0; i < length && i < ctx.maxPropertyCount; i++) { const value = hostValue.values![i]; // render expanded value, but trim the whitespace on the left side const valueString = formatters[ formatterIndexFor(value.type, ReflectedValueFormatType.Expanded) ](value, ctx); if (i === length - 1) { // remove trailing comma body += `${valueString}\n`; } else { body += `${valueString},\n`; } } if (length >= ctx.maxPropertyCount) body += `${spacing}... +${length - ctx.maxPropertyCount} values`; ctx.level -= 1; ctx.impliedTypeInfo = previousImpliedTypeInfo; ctx.seen.delete(hostValue); if (previousImpliedTypeInfo) return `${spacing}[${body}${spacing}]`; return `${spacing}${ctx.classNameFormatter( `${hostValue.typeName}`, )} [${body}${spacing}]`; } else { // inline let body = spacing; if (!previousImpliedTypeInfo) body += ctx.classNameFormatter(hostValue.typeName!) + " "; body += "["; let i = 0; let length = hostValue.values!.length; const count = Math.min(length, ctx.maxPropertyCount); for (; i < count; i++) { let value = hostValue.values![i]; const resultStart = i === 0 ? " " : ", "; const result = resultStart + formatters[ formatterIndexFor(value.type, ReflectedValueFormatType.Inline) ](value, ctx).trimLeft(); if (body.length + result.length > ctx.maxLineLength) { break; } body += result; } if (length - i > 0) body += `... +${length - i} items`; body += " ]"; ctx.impliedTypeInfo = previousImpliedTypeInfo; ctx.seen.delete(hostValue); // render value return body; } } // Array formatters[ formatterIndexFor(ReflectedValueType.Array, ReflectedValueFormatType.Expanded) ] = displayArrayExpanded; formatters[ formatterIndexFor(ReflectedValueType.Array, ReflectedValueFormatType.Inline) ] = displayArrayExpanded; formatters[ formatterIndexFor(ReflectedValueType.Array, ReflectedValueFormatType.Key) ] = displayClassWithSpacing; formatters[ formatterIndexFor(ReflectedValueType.Array, ReflectedValueFormatType.Value) ] = displayArrayExpanded; // ArrayBuffer formatters[ formatterIndexFor( ReflectedValueType.ArrayBuffer, ReflectedValueFormatType.Expanded, ) ] = displayArrayExpanded; formatters[ formatterIndexFor( ReflectedValueType.ArrayBuffer, ReflectedValueFormatType.Inline, ) ] = displayArrayExpanded; formatters[ formatterIndexFor( ReflectedValueType.ArrayBuffer, ReflectedValueFormatType.Key, ) ] = displayClassWithSpacing; formatters[ formatterIndexFor( ReflectedValueType.ArrayBuffer, ReflectedValueFormatType.Value, ) ] = displayArrayExpanded; // TypedArray formatters[ formatterIndexFor( ReflectedValueType.TypedArray, ReflectedValueFormatType.Expanded, ) ] = displayArrayExpanded; formatters[ formatterIndexFor( ReflectedValueType.TypedArray, ReflectedValueFormatType.Inline, ) ] = displayArrayExpanded; formatters[ formatterIndexFor(ReflectedValueType.TypedArray, ReflectedValueFormatType.Key) ] = displayClassWithSpacing; formatters[ formatterIndexFor( ReflectedValueType.TypedArray, ReflectedValueFormatType.Value, ) ] = displayArrayExpanded; // Map formatters[ formatterIndexFor(ReflectedValueType.Map, ReflectedValueFormatType.Expanded) ] = displayClassExpanded; formatters[ formatterIndexFor(ReflectedValueType.Map, ReflectedValueFormatType.Inline) ] = displayClassNoSpacing; formatters[ formatterIndexFor(ReflectedValueType.Map, ReflectedValueFormatType.Key) ] = displayClassWithSpacing; formatters[ formatterIndexFor(ReflectedValueType.Map, ReflectedValueFormatType.Value) ] = displayClassExpanded;
the_stack
import { Configuration, configurationValue, } from "@atomist/automation-client/lib/configuration"; import { automationClientInstance } from "@atomist/automation-client/lib/globals"; import { AutomationContextAware, HandlerContext, } from "@atomist/automation-client/lib/HandlerContext"; import { logger } from "@atomist/automation-client/lib/util/logger"; import { doWithRetry } from "@atomist/automation-client/lib/util/retry"; import * as k8s from "@kubernetes/client-node"; import * as cluster from "cluster"; import * as fs from "fs-extra"; import * as stringify from "json-stringify-safe"; import * as _ from "lodash"; import * as os from "os"; import { goalData, sdmGoalTimeout, } from "../../../api-helper/goal/sdmGoal"; import { ExecuteGoalResult } from "../../../api/goal/ExecuteGoalResult"; import { GoalInvocation } from "../../../api/goal/GoalInvocation"; import { SdmGoalEvent } from "../../../api/goal/SdmGoalEvent"; import { GoalScheduler } from "../../../api/goal/support/GoalScheduler"; import { ServiceRegistrationGoalDataKey } from "../../../api/registration/ServiceRegistration"; import { runningInK8s } from "../../../core/goal/container/util"; import { toArray } from "../../../core/util/misc/array"; import { loadKubeClusterConfig, loadKubeConfig, } from "../kubernetes/config"; import { k8sErrMsg } from "../support/error"; import { K8sNamespaceFile } from "../support/namespace"; import { K8sServiceRegistrationType, K8sServiceSpec, } from "./service"; /** * Options to configure the Kubernetes goal scheduling support. */ export interface KubernetesGoalSchedulerOptions { /** * Set to `true` to run all goals as Kubernetes jobs if the * `ATOMIST_GOAL_SCHEDULER` environment variable is set to * "kubernetes". */ isolateAll?: boolean; /** * Pod spec to use as basis for job spec. This pod spec is deeply * merged with the running SDM pod spec, if available, with this * pod spec taking preference. If the running SDM pod spec is not * available and this is not provided, an error is thrown during * initialization. */ podSpec?: k8s.V1PodSpec; } /** * Return the configured Kubernetes job time-to-live, * `sdm.k8s.job.ttl` or, if that is not available, twice the value * returned by [[sdmGoalTimeout]]. */ export function k8sJobTtl(cfg?: Configuration): number { return cfg?.sdm?.k8s?.job?.ttl || configurationValue<number>("sdm.k8s.job.ttl", 2 * sdmGoalTimeout(cfg)); } /** * GoalScheduler implementation that schedules SDM goals as Kubernetes * jobs. */ export class KubernetesGoalScheduler implements GoalScheduler { public podSpec: k8s.V1PodSpec; constructor(private readonly options: KubernetesGoalSchedulerOptions = { isolateAll: false }) { } public async supports(gi: GoalInvocation): Promise<boolean> { return !process.env.ATOMIST_ISOLATED_GOAL && ( // Goal is marked as isolated and SDM is configured to use k8s jobs (gi.goal.definition.isolated && isConfiguredInEnv("kubernetes")) || // Force all goals to run isolated via env var isConfiguredInEnv("kubernetes-all") || // Force all goals to run isolated via explicit option (this.options.isolateAll && isConfiguredInEnv("kubernetes")) || // Force all goals to run isolated via explicit configuration _.get(gi.configuration, "sdm.k8s.isolateAll", false) === true ); } public async schedule(gi: GoalInvocation): Promise<ExecuteGoalResult> { const { goalEvent } = gi; const podNs = await readNamespace(); const kc = loadKubeConfig(); const batch = kc.makeApiClient(k8s.BatchV1Api); const defaultJobSpec = createJobSpec(_.cloneDeep(this.podSpec), podNs, gi); const jobSpec = await this.beforeCreation(gi, defaultJobSpec); const jobDesc = `k8s job '${jobSpec.metadata.namespace}:${jobSpec.metadata.name}' for goal '${goalEvent.uniqueName}'`; gi.progressLog.write(`/--`); gi.progressLog.write( `Scheduling k8s job '${jobSpec.metadata.namespace}:${jobSpec.metadata.name}' for goal '${goalEvent.name} (${goalEvent.uniqueName})'`); gi.progressLog.write("\\--"); try { // Check if this job was previously launched await batch.readNamespacedJob(jobSpec.metadata.name, jobSpec.metadata.namespace); logger.debug(`${jobDesc} already exists. Deleting...`); try { await batch.deleteNamespacedJob(jobSpec.metadata.name, jobSpec.metadata.namespace, undefined, undefined, undefined, undefined, undefined, { propagationPolicy: "Foreground" }); logger.debug(`${jobDesc} deleted`); } catch (e) { logger.error(`Failed to delete ${jobDesc}: ${stringify(e.body)}`); return { code: 1, message: `Failed to delete ${jobDesc}: ${k8sErrMsg(e)}`, }; } } catch (e) { // This is ok to ignore as it just means the job doesn't exist } try { logger.debug(`Job spec for ${jobDesc}: ${JSON.stringify(jobSpec)}`); // Previous deletion might not have completed; hence the retry here const jobResult = (await doWithRetry<{ body: k8s.V1Job }>( () => batch.createNamespacedJob(jobSpec.metadata.namespace, jobSpec), `Scheduling ${jobDesc}`)).body; await this.afterCreation(gi, jobResult); logger.info(`Scheduled ${jobDesc} with result: ${stringify(jobResult.status)}`); logger.log("silly", stringify(jobResult)); } catch (e) { logger.error(`Failed to schedule ${jobDesc}: ${stringify(e.body)}`); return { code: 1, message: `Failed to schedule ${jobDesc}: ${k8sErrMsg(e)}`, }; } await gi.progressLog.flush(); return { code: 0, message: `Scheduled ${jobDesc}`, }; } /** * Extension point for sub classes to modify the provided jobSpec * before the Job gets created in k8s. It should return the * modified jobSpec. * @param gi goal invocation * @param jobSpec Default job spec * @return desired job spec */ protected async beforeCreation(gi: GoalInvocation, jobSpec: k8s.V1Job): Promise<k8s.V1Job> { return jobSpec; } /** * Extension point for sub classes to modify k8s resources after the job has been created. * The provided jobSpec contains the result of the job creation API call. * @param gi * @param jobSpec */ protected async afterCreation(gi: GoalInvocation, jobSpec: k8s.V1Job): Promise<void> { return; } /** * If running in Kubernetes, read current pod spec. Populate * `this.podSpec` with a merge of `this.options.podSpec` and the * current pod spec. If neither is available, throw an error. */ public async initialize(configuration: Configuration): Promise<void> { const podName = process.env.ATOMIST_POD_NAME || os.hostname(); const podNs = await readNamespace(); let parentPodSpec: k8s.V1PodSpec; if (runningInK8s()) { try { const kc = loadKubeClusterConfig(); const core = kc.makeApiClient(k8s.CoreV1Api); parentPodSpec = (await core.readNamespacedPod(podName, podNs)).body.spec; } catch (e) { logger.error(`Failed to obtain parent pod spec from k8s: ${k8sErrMsg(e)}`); if (!this.options.podSpec) { throw new Error(`Failed to obtain parent pod spec from k8s: ${k8sErrMsg(e)}`); } } } else if (!this.options.podSpec) { throw new Error(`Not running in Kubernetes and no pod spec provided`); } this.podSpec = _.merge({}, this.options.podSpec, parentPodSpec); if (configuration.cluster.enabled === false || cluster.isMaster) { const cleanupInterval = configuration.sdm.k8s?.job?.cleanupInterval || 1000 * 60 * 1; setInterval(async () => { try { await this.cleanUp(configuration); logger.debug("Finished cleaning scheduled goal Kubernetes jobs"); } catch (e) { logger.warn(`Failed cleaning scheduled goal Kubernetes jobs: ${e.message}`); } }, cleanupInterval).unref(); } } /** * Extension point to allow for custom clean up logic. */ protected async cleanUp(configuration: Configuration): Promise<void> { await cleanupJobs(configuration); } } /** * Delete Kubernetes jobs created by this SDM that have either * * - exceeded their time-to-live, as returned by [[k8sJobTtl]] * - have pod whose first container has exited, indicating the goal has * timed out or some other error has occured */ async function cleanupJobs(configuration: Configuration): Promise<void> { const selector = `atomist.com/creator=${sanitizeName(configuration.name)}`; const jobs = await listJobs(selector); if (jobs.length < 1) { logger.debug(`No scheduled goal Kubernetes jobs found for label selector '${selector}'`); return; } const pods = await listPods(selector); const zombiePods = pods.filter(zombiePodFilter); const ttl = k8sJobTtl(configuration); const killJobs = jobs.filter(killJobFilter(zombiePods, ttl)); if (killJobs.length < 1) { logger.debug(`No scheduled goal Kubernetes jobs were older than TTL '${ttl}' or zombies`); } else { logger.debug("Deleting scheduled goal Kubernetes jobs: " + killJobs.map(j => `${j.metadata.namespace}/${j.metadata.name}`).join(",")); } for (const delJob of killJobs) { const job = { name: delJob.metadata.name, namespace: delJob.metadata.namespace }; await deleteJob(job); await deletePods(job); } } /** * Return true for pods whose first container has terminated but at * least one other container has not. */ export function zombiePodFilter(pod: k8s.V1Pod): boolean { if (!pod.status?.containerStatuses || pod.status.containerStatuses.length < 1) { return false; } const watcher = pod.status.containerStatuses[0]; const rest = pod.status.containerStatuses.slice(1); return !!watcher.state?.terminated && rest.some(p => !p.state?.terminated); } /** * Return true for jobs that have exceeded the TTL or whose child is * in the provided list of pods. Return false otherwise. */ export function killJobFilter(pods: k8s.V1Pod[], ttl: number): (j: k8s.V1Job) => boolean { return (job: k8s.V1Job): boolean => { const now = Date.now(); if (!job.status?.startTime) { return false; } const jobAge = now - job.status.startTime.getTime(); if (jobAge > ttl) { return true; } if (pods.some(p => p.metadata?.ownerReferences?.some(o => o.kind === "Job" && o.name === job.metadata.name))) { return true; } return false; }; } /** Unique name for goal to use in k8s job spec. */ function k8sJobGoalName(goalEvent: SdmGoalEvent): string { return goalEvent.uniqueName.split("#")[0].toLowerCase(); } /** Unique name for job to use in k8s job spec. */ export function k8sJobName(podSpec: k8s.V1PodSpec, goalEvent: SdmGoalEvent): string { const goalName = k8sJobGoalName(goalEvent); return `${podSpec.containers[0].name}-job-${goalEvent.goalSetId.slice(0, 7)}-${goalName}` .slice(0, 63).replace(/[^a-z0-9]*$/, ""); } /** * Kubernetes container spec environment variables that specify an SDM * running in single-goal mode. */ export function k8sJobEnv(podSpec: k8s.V1PodSpec, goalEvent: SdmGoalEvent, context: HandlerContext): k8s.V1EnvVar[] { const goalName = k8sJobGoalName(goalEvent); const jobName = k8sJobName(podSpec, goalEvent); const envVars: k8s.V1EnvVar[] = [ { name: "ATOMIST_JOB_NAME", value: jobName, }, { name: "ATOMIST_REGISTRATION_NAME", value: `${automationClientInstance().configuration.name}-job-${goalEvent.goalSetId.slice(0, 7)}-${goalName}`, }, { name: "ATOMIST_GOAL_TEAM", value: context.workspaceId, }, { name: "ATOMIST_GOAL_TEAM_NAME", value: (context as any as AutomationContextAware).context.workspaceName, }, { name: "ATOMIST_GOAL_ID", value: (goalEvent as any).id, }, { name: "ATOMIST_GOAL_SET_ID", value: goalEvent.goalSetId, }, { name: "ATOMIST_GOAL_UNIQUE_NAME", value: goalEvent.uniqueName, }, { name: "ATOMIST_CORRELATION_ID", value: context.correlationId, }, { name: "ATOMIST_ISOLATED_GOAL", value: "true", }, ]; return envVars; } /** * Create a jobSpec by modifying the provided podSpec * @param podSpec * @param podNs * @param gi */ export function createJobSpec(podSpec: k8s.V1PodSpec, podNs: string, gi: GoalInvocation): k8s.V1Job { const { goalEvent, context } = gi; const jobSpec = createJobSpecWithAffinity(podSpec, gi); jobSpec.metadata.name = k8sJobName(podSpec, goalEvent); jobSpec.metadata.namespace = podNs; jobSpec.spec.backoffLimit = 0; jobSpec.spec.template.spec.restartPolicy = "Never"; jobSpec.spec.template.spec.containers[0].name = jobSpec.metadata.name; jobSpec.spec.template.spec.containers[0].env.push(...k8sJobEnv(podSpec, goalEvent, context)); delete jobSpec.spec.template.spec.containers[0].livenessProbe; delete jobSpec.spec.template.spec.containers[0].readinessProbe; rewriteCachePath(jobSpec, context.workspaceId); // Add additional specs from registered services to the job spec if (_.get(gi.configuration, "sdm.k8s.service.enabled", true)) { if (!!goalEvent.data) { let data: any; try { data = goalData(goalEvent); } catch (e) { logger.warn(`Failed to parse goal data on '${goalEvent.uniqueName}'`); data = {}; } if (!!data[ServiceRegistrationGoalDataKey]) { _.forEach(data[ServiceRegistrationGoalDataKey], (v, k) => { logger.debug(`Service with name '${k}' and type '${v.type}' found for goal '${goalEvent.uniqueName}'`); if (v.type === K8sServiceRegistrationType.K8sService) { const spec = v.spec as K8sServiceSpec; if (!!spec.container) { const c = toArray<k8s.V1Container>(spec.container as any); jobSpec.spec.template.spec.containers.push(...c); } if (!!spec.initContainer) { const ic = toArray<k8s.V1Container>(spec.initContainer as any); jobSpec.spec.template.spec.initContainers = [ ...(jobSpec.spec.template.spec.initContainers || []), ...ic, ]; } if (!!spec.volume) { const vo = toArray<k8s.V1Volume>(spec.volume as any); jobSpec.spec.template.spec.volumes = [ ...(jobSpec.spec.template.spec.volumes || []), ...vo, ]; } if (!!spec.volumeMount) { const vm = toArray<k8s.V1VolumeMount>(spec.volumeMount as any); [...jobSpec.spec.template.spec.containers, ...jobSpec.spec.template.spec.initContainers].forEach(c => { c.volumeMounts = [ ...(c.volumeMounts || []), ...vm, ]; }); } if (!!spec.imagePullSecret) { const ips = toArray<k8s.V1LocalObjectReference>(spec.imagePullSecret as any); jobSpec.spec.template.spec.imagePullSecrets = [ ...(jobSpec.spec.template.spec.imagePullSecrets || []), ...ips, ]; } } }); } } } return jobSpec; } /** * Create a k8s Job spec with affinity to jobs for the same goal set * @param goalSetId */ function createJobSpecWithAffinity(podSpec: k8s.V1PodSpec, gi: GoalInvocation): k8s.V1Job { const { goalEvent, configuration, context } = gi; _.defaultsDeep(podSpec.affinity, { podAffinity: { preferredDuringSchedulingIgnoredDuringExecution: [ { weight: 100, podAffinityTerm: { labelSelector: { matchExpressions: [ { key: "atomist.com/goal-set-id", operator: "In", values: [ goalEvent.goalSetId, ], }, ], }, topologyKey: "kubernetes.io/hostname", }, }, ], }, }); // Clean up podSpec // See https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.13/#pod-v1-core note on nodeName delete podSpec.nodeName; const labels = { "atomist.com/goal-set-id": goalEvent.goalSetId, "atomist.com/goal-id": (goalEvent as any).id, "atomist.com/creator": sanitizeName(configuration.name), "atomist.com/workspace-id": context.workspaceId, }; const detail = { sdm: { name: configuration.name, version: configuration.version, }, goal: { goalId: (goalEvent as any).id, goalSetId: goalEvent.goalSetId, uniqueName: goalEvent.uniqueName, }, }; const annotations = { "atomist.com/sdm": JSON.stringify(detail), }; return { kind: "Job", apiVersion: "batch/v1", metadata: { labels, annotations, }, spec: { template: { metadata: { labels, }, spec: podSpec, }, }, } as any; } /** * Rewrite the volume host path to include the workspace id to prevent cross workspace content ending * up in the same directory. * @param jobSpec * @param workspaceId */ function rewriteCachePath(jobSpec: k8s.V1Job, workspaceId: string): void { const cachePath = configurationValue("sdm.cache.path", "/opt/data"); const containers: k8s.V1Container[] = _.get(jobSpec, "spec.template.spec.containers", []); const cacheVolumeNames: string[] = []; containers.forEach(c => { cacheVolumeNames.push(...c.volumeMounts.filter(vm => vm.mountPath === cachePath).map(cm => cm.name)); }); _.uniq(cacheVolumeNames).forEach(vn => { const volume: k8s.V1Volume = _.get(jobSpec, "spec.template.spec.volumes", []).find(v => v.name === vn); if (!!volume && !!volume.hostPath && !!volume.hostPath.path) { const path = volume.hostPath.path; if (!path.endsWith(workspaceId) || !path.endsWith(`${workspaceId}/`)) { if (path.endsWith("/")) { volume.hostPath.path = `${path}${workspaceId}`; } else { volume.hostPath.path = `${path}/${workspaceId}`; } } } }); } /** * Checks if one of the provided values is configured in ATOMIST_GOAL_SCHEDULER or - * for backwards compatibility reasons - ATOMIST_GOAL_LAUNCHER. * @param values */ export function isConfiguredInEnv(...values: string[]): boolean { const value = process.env.ATOMIST_GOAL_SCHEDULER || process.env.ATOMIST_GOAL_LAUNCHER; if (!!value) { try { const json = JSON.parse(value); if (Array.isArray(json)) { return json.some(v => values.includes(v)); } else { return values.includes(json); } } catch (e) { if (typeof value === "string") { return values.includes(value); } } } return false; } /** * Strip out any characters that aren't allowed a k8s label value * @param name */ export function sanitizeName(name: string): string { return name.replace(/@/g, "").replace(/\//g, "."); } /** * Read the namespace from the following sources in order. It returns * the first truthy value found. * * 1. ATOMIST_POD_NAMESPACE environment variable * 2. ATOMIST_DEPLOYMENT_NAMESPACE environment variable * 3. Contents of [[K8sNamespaceFile]] * 4. "default" * * service account files. Falls back to the default namespace if no * other configuration can be found. */ export async function readNamespace(): Promise<string> { let podNs = process.env.ATOMIST_POD_NAMESPACE || process.env.ATOMIST_DEPLOYMENT_NAMESPACE; if (!!podNs) { return podNs; } if (await fs.pathExists(K8sNamespaceFile)) { podNs = (await fs.readFile(K8sNamespaceFile)).toString().trim(); } if (!!podNs) { return podNs; } return "default"; } /** * List Kubernetes jobs matching the provided label selector. Jobs * are listed across all namespaces if * `configuration.sdm.k8s.job.singleNamespace` is not set to `false`. * If that configuration value is not set or set to `true`, jobs are * listed from the namespace provide by [[readNamespace]]. * * @param labelSelector * @return array of Kubernetes jobs matching the label selector */ export async function listJobs(labelSelector?: string): Promise<k8s.V1Job[]> { const kc = loadKubeConfig(); const batch = kc.makeApiClient(k8s.BatchV1Api); const jobs: k8s.V1Job[] = []; let continu: string | undefined; try { if (configurationValue<boolean>("sdm.k8s.job.singleNamespace", true)) { const podNs = await readNamespace(); do { const listJobResponse = await batch.listNamespacedJob(podNs, undefined, undefined, continu, undefined, labelSelector); jobs.push(...listJobResponse.body.items); continu = listJobResponse.body.metadata?._continue; } while (continu); } else { do { const listJobResponse = await batch.listJobForAllNamespaces(undefined, continu, undefined, labelSelector); jobs.push(...listJobResponse.body.items); continu = listJobResponse.body.metadata?._continue; } while (continu); } } catch (e) { e.message = `Failed to list scheduled goal Kubernetes jobs: ${k8sErrMsg(e)}`; throw e; } return jobs; } /** * Delete the provided job. Failures are ignored. */ export async function deleteJob(job: { name: string, namespace: string }): Promise<void> { try { const kc = loadKubeConfig(); const batch = kc.makeApiClient(k8s.BatchV1Api); await batch.readNamespacedJob(job.name, job.namespace); try { await batch.deleteNamespacedJob(job.name, job.namespace, undefined, undefined, undefined, undefined, undefined, { propagationPolicy: "Foreground" }); } catch (e) { logger.warn(`Failed to delete k8s jobs '${job.namespace}:${job.name}': ${k8sErrMsg(e)}`); } } catch (e) { // This is ok to ignore because the job doesn't exist any more } } /** * List Kubernetes pods matching the provided label selector. Jobs * are listed in a the current namespace or cluster-wide depending on * evn configuration * * @param labelSelector */ export async function listPods(labelSelector?: string): Promise<k8s.V1Pod[]> { const kc = loadKubeConfig(); const core = kc.makeApiClient(k8s.CoreV1Api); const pods: k8s.V1Pod[] = []; let continu: string | undefined; try { if (configurationValue<boolean>("sdm.k8s.job.singleNamespace", true)) { const podNs = await readNamespace(); do { const listResponse = await core.listNamespacedPod(podNs, undefined, undefined, continu, undefined, labelSelector); pods.push(...listResponse.body.items); continu = listResponse.body.metadata?._continue; } while (continu); } else { do { const listResponse = await core.listPodForAllNamespaces(undefined, continu, undefined, labelSelector); pods.push(...listResponse.body.items); continu = listResponse.body.metadata?._continue; } while (continu); } } catch (e) { e.message = `Failed to list scheduled goal Kubernetes pods: ${k8sErrMsg(e)}`; throw e; } return pods; } /** * Delete the provided pods. Failures are ignored. */ export async function deletePods(job: { name: string, namespace: string }): Promise<void> { try { const kc = loadKubeConfig(); const core = kc.makeApiClient(k8s.CoreV1Api); const selector = `job-name=${job.name}`; const pods = await core.listNamespacedPod(job.namespace, undefined, undefined, undefined, undefined, selector); if (pods.body && pods.body.items) { for (const pod of pods.body.items) { try { await core.deleteNamespacedPod(pod.metadata.name, pod.metadata.namespace, undefined, undefined, undefined, undefined, undefined, { propagationPolicy: "Foreground" }); } catch (e) { // Probably ok because pod might be gone already logger.debug(`Failed to delete k8s pod '${pod.metadata.namespace}:${pod.metadata.name}': ${k8sErrMsg(e)}`); } } } } catch (e) { logger.warn(`Failed to list pods for k8s job '${job.namespace}:${job.name}': ${k8sErrMsg(e)}`); } }
the_stack
import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Utils, PathRegion, Helpable, SPARQList, BedAnnotation, WigAnnotation, PackAnnotation, PathRegionWithPrevLen } from './Utils'; import * as d3 from 'd3'; import TubeMap from './SequenceTubeMap'; import Wrapper from './Manual'; import AutosizeInput from 'react-input-autosize'; enum HaploidColorful { Reference, Variant, Green } enum GeneColor { Colorful, Green } const greys_old = [ // '#d9d9d9', '#bdbdbd', '#737373', '#252525', '#969696', '#525252' // '#000000' ].reverse(); const greys = [ // '#d9d9d9', // '#bdbdbd', // '#737373', '#252525', // '#969696', '#525252', '#000000' ]; // .reverse(); const greysWhite = ['#d9d9d9']; const white = ['#ffffff']; const plainColors = [ '#1f77b4', '#ff7f0e', // '#2ca02c', // Without Green '#d62728', '#9467bd', '#8c564b', '#e377c2', // '#7f7f7f', // Without grey '#bcbd22', '#17becf' ]; // d3 category10 const lightColors = [ '#ABCCE3', '#FFCFA5', // '#B0DBB0', '#F0AEAE', '#D7C6E6', '#C6ABA5', '#F4CCE8', // '#CFCFCF', // Without grey '#E6E6AC', '#A8E7ED' ]; // d3 category10 // const greenDarkColors = ['#238b45', '#b2e2e2'].reverse(); // const greenLightColors = ['#66c2a4', '#edf8fb'].reverse(); const greens = [ '#e5f5e0', '#c7e9c0', '#a1dd9b', '#74c476', '#41ab5d', '#238b45', '#006d2c', '#00441b' ]; const greenDarkColors = greens.slice(4, 8); // .filter((a, i) => i % 2 === 1); const greenLightColors = greens.slice(0, 4); // .filter((a, i) => i % 2 === 0); export interface GraphWrapperProps { width: number; height: number; chroms: any; pos: PathRegion[]; nodesUpdate: (reg: number[]) => void; annotationsUpdate: (annotations: any[]) => void; annotationsClean: () => void; subPathAnnotation: boolean; bigbedAnnotation?: boolean; toggleSubPathAnnotation: () => void; uuid: string; sequentialId: number; reference: string; features: any; } export interface GraphWrapperState { pos: PathRegion; graph: any; exon: any; gam: any; loading: boolean; initialize: boolean; sequentialId: number; // sequentialIdProp: number; annotations?: any; showGeneInfo: any[]; subPathAnnotation: boolean; steps: number; pathNameDict: any; colorOption: [HaploidColorful, GeneColor]; nodeCoverages?: {[key: number]: number[]}; metaNodeCoverages?: {min: number, max: number}[]; } class GraphWrapper extends React.Component<GraphWrapperProps, GraphWrapperState> implements Helpable { private maximumRange: number; private tubemap: any; constructor(props: GraphWrapperProps) { super(props); this.maximumRange = 1000 * 1000 * 1.5; this.help = this.help.bind(this); this.changeSubPathAnnotation = this.changeSubPathAnnotation.bind(this); this.selectNodeId = this.selectNodeId.bind(this); this.doNotUseCache = this.doNotUseCache.bind(this); this.reload = this.reload.bind(this); this.stepsUpdate = this.stepsUpdate.bind(this); this.forceCache = this.forceCache.bind(this); this.toggleAnnotationColor = this.toggleAnnotationColor.bind(this); this.toggleGam = this.toggleGam.bind(this); this.selectUniqueColor = this.selectUniqueColor.bind(this); this.state = { graph: '', gam: true, exon: [], loading: false, initialize: false, sequentialId: 0, pos: props.pos[0], subPathAnnotation: props.subPathAnnotation, showGeneInfo: [], steps: 3, pathNameDict: {}, colorOption: [HaploidColorful.Variant, GeneColor.Green] }; } help() { // prettier-ignore return ( <div> <h3>SequenceTubeMap</h3> <a href="https://github.com/vgteam/sequenceTubeMap"> {'https://github.com/vgteam/sequenceTubeMap'} </a> <p>Designs are modified to represent variations on human genome.</p> <p>Wide and dark paths mean the reference chromosome.</p> <p>Wide and light paths mean structural variations or haplotypes.</p> <p> Thin paths means annotations, i.e. genes. Dark regions are exon and otherwise are intron. </p> <p>The selected path moves upper when you double-click the path.</p> </div> ); } link() { return 'sequencetubemap'; } toggleGam(next: boolean) { if (next === true) { this.reload(); } } toggleAnnotationColor() { if (this.state.colorOption[1] === GeneColor.Green) { this.setState({ colorOption: [HaploidColorful.Variant, GeneColor.Colorful], sequentialId: this.state.sequentialId + 1 }); } else { this.setState({ colorOption: [HaploidColorful.Variant, GeneColor.Green], sequentialId: this.state.sequentialId + 1 }); } } uniqueTrackId(name: string) { const dict = this.state.pathNameDict; if (name in dict) { return dict[name]; } const lastitem = Object.keys(dict).length; dict[name] = lastitem; return lastitem; } uniqueTrackIdWithType(name: string, type: string) { const allDict = this.state.pathNameDict; if (!(type in allDict)) { allDict[type] = {}; } const dict = allDict[type]; if (name in dict) { return dict[name]; } const lastitem = Object.keys(dict).length; dict[name] = lastitem; this.setState({ pathNameDict: allDict }); return lastitem; } selectUniqueColor( name: string, type?: string, colorOption: [HaploidColorful, GeneColor] = this.state.colorOption ) { const sameColor = (color: string) => { return { haplotype_color: color, exon_color: color }; }; const differenceColor = (haplotypeColor: string, exonColor: string) => { return { haplotype_color: haplotypeColor, exon_color: exonColor }; }; switch (type) { case 'reference': case 'variation': if (colorOption[0] === HaploidColorful.Reference) { if (Utils.strToColor(name, this.props.chroms) !== '') { // When reference return differenceColor( Utils.strToColor(name, this.props.chroms), greysWhite[ this.uniqueTrackIdWithType(name, type) % greysWhite.length ] ); } else { // When Variants: return differenceColor( greys[this.uniqueTrackIdWithType(name, type) % greys.length], greysWhite[ this.uniqueTrackIdWithType(name, type) % greysWhite.length ] ); } } else if (colorOption[0] === HaploidColorful.Green) { return { haplotype_color: greenDarkColors[ this.uniqueTrackIdWithType(name, type) % greenDarkColors.length ], exon_color: greenLightColors[ this.uniqueTrackIdWithType(name, type) % greenLightColors.length ] }; } else { // Set reference as grayscale, variations as colorful. if (type === 'reference') { return differenceColor( greys[this.uniqueTrackIdWithType(name, type) % greys.length], greysWhite[ this.uniqueTrackIdWithType(name, type) % greysWhite.length ] ); } else { // When Variants: return { haplotype_color: plainColors[ this.uniqueTrackIdWithType(name, 'plain') % plainColors.length ], exon_color: plainColors[ this.uniqueTrackIdWithType(name, 'plain') % plainColors.length ] }; } } case 'gene': if (colorOption[1] === GeneColor.Colorful) { return { haplotype_color: plainColors[ this.uniqueTrackIdWithType(name, 'plain') % plainColors.length ], exon_color: lightColors[ this.uniqueTrackIdWithType(name, 'plain') % lightColors.length ], white_color: white[ this.uniqueTrackIdWithType(name, type) % white.length ] }; } else { // Gene colors are unified in green. return { haplotype_color: greenDarkColors[ this.uniqueTrackIdWithType(name, type) % greenDarkColors.length ], exon_color: greenLightColors[ this.uniqueTrackIdWithType(name, type) % greenLightColors.length ], white_color: white[ this.uniqueTrackIdWithType(name, type) % white.length ], hideLegend: true }; } default: // Other annotations. return { haplotype_color: greys[this.uniqueTrackIdWithType(name, type) % greys.length], exon_color: white[ this.uniqueTrackIdWithType(name, type) % white.length ], hideLegend: true }; } } stepsUpdate(stepInput: string) { let step = Number(stepInput); if (step < 0) { step = 0; } else if (step > 10) { step = 10; } this.setState({ steps: step }); } componentDidMount() { this.setState({ initialize: true }); this.fetchGraph(this.props.pos[0], this.props.uuid, true); } componentWillReceiveProps(props: GraphWrapperProps) { // console.log(props) if ( this.state.initialize && this.props.sequentialId !== props.sequentialId ) { this.fetchGraph(props.pos[0], props.uuid, true); } } doNotUseCache() { this.fetchGraph(this.props.pos[0], this.props.uuid, false); } reload() { this.fetchGraph(this.props.pos[0], this.props.uuid, true); } forceCache(pos: PathRegion) { const uuidQuery = this.props.uuid !== '' ? '&uuid=' + this.props.uuid : ''; [ pos.scaleUp().toQuery(), pos .scaleDown() .scaleDown() .toQuery(), pos .scaleUp() .scaleLeft() .toQuery(), pos .scaleRight() .scaleRight() .toQuery() ].forEach(newPos => { fetch( '/api/v2/graph?raw=true&cache=true' + '&steps=' + this.state.steps + '&path=' + newPos + uuidQuery ); }); pos.scaleLeft(); } fetchGraph(pos: PathRegion, uuid: string, cache: boolean) { this.setState({ pos: pos }); const _this = this; if (pos.diff() < this.maximumRange) { this.setState({ loading: true }); this.tubemap.fadeout(); const uuidQuery = this.props.uuid !== '' ? '&uuid=' + this.props.uuid : ''; fetch( '/api/v2/graph?raw=true&cache=' + cache + '&gam=' + this.state.gam + '&steps=' + this.state.steps + '&path=' + pos.toQuery() + uuidQuery ) .then(function(response: Response) { return response.json(); }) .then(function(graph: any) { if (Object.keys(graph).length !== 0) { var pathItem = undefined; pathItem = graph.path.find(a => a.name === pos.path); var pathRemaining = graph.path .filter(a => a.name !== pathItem.name) .sort((a, b) => b.name.length - a.name.length); var mapping = pathItem.mapping.map(a => a.position.node_id); var path = [pathItem]; var genes = []; pathRemaining.forEach(a => { if ( a.mapping.some(b => mapping.indexOf(b.position.node_id) !== -1) ) { path.push(a); mapping = mapping.concat( a.mapping.map(c => c.position.node_id) ); } }); const referencePath = path.filter( a => a.indexOfFirstBase !== undefined ); let pathAsAllExon = []; let allIsoforms = []; path.filter(a => a.indexOfFirstBase === undefined).forEach(i => { const diff = i.mapping.map((a, idx) => { if (idx >= 1) { return a.rank - i.mapping[idx - 1].rank; } else { return 1; } }); let traversedNodeLength = 0; let currentNodeLength = 0; let allInverse = true; let currentPathExon = []; diff.forEach((a, idx) => { if (i.mapping[idx].position.is_reverse !== true) { allInverse = false; } if (a !== 1) { currentPathExon.push({ track: i.name, start: traversedNodeLength, end: currentNodeLength - 1, type: 'exon', name: i.name }); traversedNodeLength = currentNodeLength; } currentNodeLength = currentNodeLength + Number( graph.node.find( a => a.id === i.mapping[idx].position.node_id ).sequence.length ); }); if ( i.mapping[i.mapping.length - 1].position.is_reverse === false ) { // Confirm whether last one is inverted or not. allInverse = false; } currentPathExon.push({ track: i.name, start: traversedNodeLength, end: currentNodeLength - 1, type: 'exon', name: i.name }); if (allInverse) { currentPathExon = currentPathExon.map(a => { let tmp = currentNodeLength - 1 - a.start; a.start = currentNodeLength - 1 - a.end; a.end = tmp; return a; }); } pathAsAllExon = pathAsAllExon.concat(currentPathExon); }); path = path.map(i => { i.type = i.indexOfFirstBase !== undefined ? 'reference' : 'variation'; i.freq = i.indexOfFirstBase !== undefined ? 100 : 8; return i; }); if (referencePath.length === 0) { let pathPos = _this.props.pos[0].withPrevLen(); // const pos = new PathRegion(i.name, i.indexOfFirstBase, stop); const url: string = BedAnnotation.buildBedAnnotationRequest( pathPos, ); fetch(url, { headers: { Accept: 'application/json' } }) .then(function(response: Response) { return response.json(); }) .then(function(res: any) { const annotations = BedAnnotation.convertToAnnotation( res, pathPos ); _this.props.annotationsUpdate(annotations.isoform); _this.setState({ loading: false, graph: graph, sequentialId: _this.state.sequentialId + 1, }); }) .catch(function(err: any) { // handle error console.error(err); }); } referencePath.forEach(i => { const diff = i.mapping.map((a, idx) => { if (idx >= 1) { return a.rank - i.mapping[idx - 1].rank; } else { return 1; } }); let lastIndex = 0; let traversedNodeLength = 0; let paths: PathRegionWithPrevLen[] = []; diff.forEach((a, idx) => { if (a !== 1) { paths.push( new PathRegionWithPrevLen( i.name, i.mapping[lastIndex].position.coordinate, i.mapping[idx - 1].position.coordinate + Number( graph.node.find( a => a.id === i.mapping[idx - 1].position.node_id ).sequence.length ), traversedNodeLength, lastIndex, idx ) ); let distance = i.mapping[idx - 1].position.coordinate + Number( graph.node.find( a => a.id === i.mapping[idx - 1].position.node_id ).sequence.length ) - i.mapping[lastIndex].position.coordinate; pathAsAllExon.push({ track: i.name, start: traversedNodeLength, end: distance + traversedNodeLength - 1, type: 'exon', name: i.name }); traversedNodeLength += distance; lastIndex = idx; } }); paths.push( new PathRegionWithPrevLen( i.name, i.mapping[lastIndex].position.coordinate, i.mapping[i.mapping.length - 1].position.coordinate + Number( graph.node.find( a => a.id === i.mapping[i.mapping.length - 1].position.node_id ).sequence.length ), traversedNodeLength, lastIndex, i.mapping.length ) ); let distance = i.mapping[i.mapping.length - 1].position.coordinate + Number( graph.node.find( a => a.id === i.mapping[i.mapping.length - 1].position.node_id ).sequence.length ) - i.mapping[lastIndex].position.coordinate; pathAsAllExon.push({ track: i.name, start: traversedNodeLength, end: distance + traversedNodeLength - 1, type: 'exon', name: i.name }); let nodeCoverages: { [key: string]: number[]; } = {}; let nodeIds = i.mapping.map(pos => { return new PathRegionWithPrevLen( i.name, pos.position.coordinate, pos.position.coordinate + Number( graph.node.find( a => a.id === pos.position.node_id ).sequence.length ), 0, pos.position.node_id, i.mapping.length ); }); // console.log(nodeIds) const url: string = WigAnnotation.buildAnnotationRequests(nodeIds); fetch(url, { headers: { Accept: 'application/json' } }) .then(function(response: Response) { return response.json(); }) .then(function(res: any) { const wigs = WigAnnotation.convertToAnnotations( res, nodeIds ); // Convert from array of nodes to nodes of array. const metaNodeCoverages = wigs.map((wig, index) => { // console.log(values, min, max); Object.keys(wig.values).map(function(key: string) { if (nodeCoverages[key] === undefined) { nodeCoverages[key] = new Array(wigs.length); } nodeCoverages[key][index] = wig.values[key]; // In original value }); return {min: wig.min, max: wig.max}; }); _this.setState({ loading: false, sequentialId: _this.state.sequentialId + 1, nodeCoverages, metaNodeCoverages }); }).catch(function(err: any) { // handle error console.error(err); }); const pack_url: string = PackAnnotation.buildAnnotationRequests(nodeIds); fetch(pack_url, { headers: { Accept: 'application/json' } }) .then(function(response: Response) { return response.json(); }) .then(function(res: any) { // Convert from array of nodes to nodes of array. const metaNodeCoverages = res.map((wig, index) => { // console.log(values, min, max); Object.keys(wig['values']).map(function(key: string) { let array = wig['values'][key].values; if (nodeCoverages[key] === undefined) { nodeCoverages[key] = new Array(res.length); } nodeCoverages[key][index] = array; // In original value }); return {min: wig.min, max: wig.max}; }); _this.setState({ loading: false, sequentialId: _this.state.sequentialId + 1, nodeCoverages, metaNodeCoverages }); }).catch(function(err: any) { // handle error // console.error(err); }); if (_this.props.bigbedAnnotation === true) { paths .filter(a => !(a.start === 0 && a.stop !== a.stop)) // isNaN .forEach(pathPos => { // const pos = new PathRegion(i.name, i.indexOfFirstBase, stop); const url: string = BedAnnotation.buildBedAnnotationRequest( pathPos, ); fetch(url, { headers: { Accept: 'application/json' } }) .then(function(response: Response) { return response.json(); }) .then(function(res: any) { const annotations = BedAnnotation.convertToAnnotation( res, pathPos ); const i_mapping = i.mapping.slice( pathPos.startIndex, pathPos.stopIndex ); const convertIsoformToPath = (isoform: any) => { // console.log(isoform, i.mapping); let startNodeIndex = i_mapping.findIndex( a => a.position.coordinate >= isoform.mrna_start ); let endNodeIndex = i_mapping.findIndex( a => a.position.coordinate > isoform.mrna_end ); // console.log(endNodeIndex, startNodeIndex) if (startNodeIndex >= 1) { startNodeIndex = startNodeIndex - 1; } if (endNodeIndex === -1) { endNodeIndex = i_mapping.length; } let newMapping = i_mapping.slice( startNodeIndex, endNodeIndex ); // console.log(newMapping) if (newMapping.length > 1) { newMapping = JSON.parse(JSON.stringify(newMapping)); // Deep copy newMapping[0].position.offset = isoform.mrna_start - newMapping[0].position.coordinate; newMapping[newMapping.length - 1].position.offset = isoform.mrna_end - (newMapping[newMapping.length - 1].position .coordinate + Number( graph.node.find( a => a.id === newMapping[newMapping.length - 1].position .node_id ).sequence.length )); // FIXME() untested const newPath = { name: isoform.name + ' (' + isoform.track + ')', mapping: newMapping, freq: 2, type: 'bed', full_length: isoform.mrna_end - isoform.mrna_start, start: isoform.mrna_start - newMapping[0].position.coordinate, end: isoform.mrna_end - isoform.mrna_start + (newMapping[newMapping.length - 1].position .coordinate + Number( graph.node.find( a => a.id === newMapping[newMapping.length - 1].position .node_id ).sequence.length)) }; // console.log(newPath) return newPath; } else { return null; } }; // console.log(annotations); if ( annotations.isoform.length > 0 && _this.props.subPathAnnotation ) { let additionalPath = annotations.isoform .map(a => convertIsoformToPath(a)) .filter(a => a); let exons = additionalPath .map(a => { // let b = a.mapping[0].position.offset; return {start: a.start, end: a.start + a.full_length, track: a.name, name: a.name, type: 'exon'}; }) .filter(a => a); // console.log(exons); /*additionalPath = Utils.arrayUniqueByName( additionalPath );*/ /*.filter( (a, index, self) => a !== null && self.findIndex(b => b.name === a.name) === index );*/ // console.log("path:", additionalPath); let hash = {}; genes.forEach(a => (hash[a.name] = 1)); additionalPath.forEach(a => { if (!(a.name in hash)) { genes.push(a); } }); // path = path.concat(additionalPath); let colouredIsoform = annotations.isoform.map(a => { a['color'] = _this.selectUniqueColor( a.name + ' (' + a.track + ')', 'bed', [_this.state.colorOption[0], GeneColor.Colorful] ).haplotype_color; return a; }); allIsoforms = colouredIsoform; graph.genes = genes; // console.log("path:",graph.path); _this.props.annotationsUpdate(annotations.isoform); _this.setState({ loading: false, graph: graph, exon: _this.state.exon.concat(exons), sequentialId: _this.state.sequentialId + 1, annotations: colouredIsoform // annotations.isoform }); } }) .catch(function(err: any) { // handle error console.error(err); }); }); } paths .filter(a => !(a.start === 0 && a.stop !== a.stop)) // isNaN .forEach(pathPos => { const url: string = SPARQList.buildSparqlistRequest( pathPos, _this.props.reference ); fetch(url, { headers: { Accept: 'application/json' } }) .then(function(response: Response) { return response.json(); }) .then(function(res: any) { const annotations = SPARQList.convertToAnnotationFromSparqlist( res, pathPos ); const i_mapping = i.mapping.slice( pathPos.startIndex, pathPos.stopIndex ); const convertIsoformToPath = (isoform: any) => { let startNodeIndex = i_mapping.findIndex( a => a.position.coordinate >= isoform.mrna_start ); let endNodeIndex = i_mapping.findIndex( a => a.position.coordinate > isoform.mrna_end ); if (startNodeIndex >= 1) { startNodeIndex = startNodeIndex - 1; } if (endNodeIndex === -1) { endNodeIndex = i_mapping.length; } let newMapping = i_mapping.slice( startNodeIndex, endNodeIndex ); if (newMapping.length > 1) { newMapping = JSON.parse(JSON.stringify(newMapping)); // Deep copy newMapping[0].position.offset = isoform.mrna_start - newMapping[0].position.coordinate; newMapping[newMapping.length - 1].position.offset = isoform.mrna_end - (newMapping[newMapping.length - 1].position .coordinate + Number( graph.node.find( a => a.id === newMapping[newMapping.length - 1].position .node_id ).sequence.length )); const newPath = { name: isoform.name + ' (' + isoform.track + ')', mapping: newMapping, freq: 2, type: 'gene', feature: 'gene', full_length: isoform.mrna_end - isoform.mrna_start }; return newPath; } else { return null; } }; if ( annotations.isoform.length > 0 && _this.props.subPathAnnotation ) { let additionalPath = annotations.isoform .map(a => convertIsoformToPath(a)) .filter(a => a); let exons = annotations.exon .map(a => { var offset = additionalPath.filter( b => b.name === a.track )[0].mapping[0].position.offset; // console.log(offset); if (offset < 0) offset = 0; a.start += offset; a.end += offset; return a; }) .filter(a => a); let margin_exons = additionalPath .map(a => { if ( a.mapping[a.mapping.length - 1].position.offset < 0 ) {return [ {start: 0, end: a.mapping[0].position.offset, track: a.name, name: a.name, type: 'margin'}, { start: a.full_length + a.mapping[0].position.offset, end: a.full_length + a.mapping[0].position.offset - a.mapping[a.mapping.length - 1].position.offset, track: a.name, name: a.name, type: 'margin' }, ]; } else {return [ {start: 0, end: a.mapping[0].position.offset, track: a.name, name: a.name, type: 'margin'} ]; } }); let flatten_exons = [].concat(...margin_exons); exons = exons.concat(flatten_exons); let hash = {}; genes.forEach(a => (hash[a.name] = 1)); additionalPath.forEach(a => { if (!(a.name in hash)) { genes.push(a); } }); let colouredIsoform = annotations.isoform.map(a => { a['color'] = _this.selectUniqueColor( a.name + ' (' + a.track + ')', 'gene', [_this.state.colorOption[0], GeneColor.Colorful] ).haplotype_color; return a; }); graph.genes = genes; _this.props.annotationsUpdate(annotations.isoform); _this.setState({ loading: false, graph: graph, exon: _this.state.exon.concat(exons), sequentialId: _this.state.sequentialId + 1, annotations: colouredIsoform }); } }) .catch(function(err: any) { // handle error console.error(err); }); }); }); graph.path = path; graph.genes = []; // console.log(graph.path); _this.props.annotationsClean(); _this.setState({ loading: false, graph: graph, exon: pathAsAllExon, annotations: [], sequentialId: _this.state.sequentialId + 1 }); } }) .catch(function(err: any) { // handle error _this.tubemap.fadein(); console.error(err); }); } } changeSubPathAnnotation() { this.props.toggleSubPathAnnotation(); this.fetchGraph(this.props.pos[0], this.props.uuid, true); } selectNodeId(id: number) { const paths = this.state.graph.path .filter(a => a.mapping.some(b => b.position.node_id === Number(id))) .map(a => a.name); const annotations = this.state.annotations.filter(a => paths.some(b => b === a.track) ); this.setState({ showGeneInfo: annotations }); } render() { return ( <div> <TubeMap ref={tubemap => (this.tubemap = tubemap)} width={this.props.width} graph={this.state.graph} gam={this.state.gam} pos={this.props.pos} sequentialId={this.state.sequentialId} exon={this.state.exon} subPathAnnotation={this.props.subPathAnnotation} changeSubPathAnnotation={this.changeSubPathAnnotation} selectNodeId={this.selectNodeId} selectUniqueColor={this.selectUniqueColor} changeGam={this.toggleGam} nodeCoverages={this.state.nodeCoverages} metaNodeCoverages={this.state.metaNodeCoverages} /> <div id="wrapperContents" style={{ display: 'flex' }} className="form-group"> <input title="Reload using cache" type="button" className="btn btn-primary" onClick={this.reload} value="Reload" /> <input title="Discard cache on the server and reload" type="button" className="btn btn-secondary" onClick={this.doNotUseCache} value="Discard cache" /> <input type="button" className="btn btn-secondary" onClick={this.toggleAnnotationColor} value="Toggle gene" /> <label>Context steps:</label> <input type="text" name="uuid" className="form-control" title="expand the context of the subgraph this many steps" value={this.state.steps} onChange={e => this.stepsUpdate(e.target.value)} /> </div> </div> ); } } export default GraphWrapper;
the_stack
import { getClient } from "azure-devops-extension-api"; import { TeamContext } from "azure-devops-extension-api/Core"; import { CapacityPatch, TeamMemberCapacity, TeamSettingsDaysOff, TeamSettingsDaysOffPatch, TeamSettingsIteration, WorkRestClient, TeamMemberCapacityIdentityRef } from "azure-devops-extension-api/work"; import { ObservableValue, ObservableArray } from "azure-devops-ui/Core/Observable"; import { EventInput } from "@fullcalendar/core"; import { EventSourceError } from "@fullcalendar/core/structs/event-source"; import { generateColor } from "./Color"; import { ICalendarEvent, IEventIcon, IEventCategory } from "./Contracts"; import { formatDate, getDatesInRange, shiftToUTC, shiftToLocal } from "./TimeLib"; export const DaysOffId = "daysOff"; export const Everyone = "Everyone"; export const IterationId = "iteration"; export class VSOCapacityEventSource { private capacityMap: { [iterationId: string]: { [memberId: string]: TeamMemberCapacityIdentityRef } } = {}; private capacitySummaryData: ObservableArray<IEventCategory> = new ObservableArray<IEventCategory>([]); private capacityUrl: ObservableValue<string> = new ObservableValue(""); private groupedEventMap: { [dateString: string]: ICalendarEvent } = {}; private hostUrl: string = ""; private iterations: TeamSettingsIteration[] = []; private iterationSummaryData: ObservableArray<IEventCategory> = new ObservableArray<IEventCategory>([]); private iterationUrl: ObservableValue<string> = new ObservableValue(""); private teamContext: TeamContext = { projectId: "", teamId: "", project: "", team: "" }; private teamDayOffMap: { [iterationId: string]: TeamSettingsDaysOff } = {}; private workClient: WorkRestClient = getClient(WorkRestClient, {}); /** * Add new day off for a member or a team */ public addEvent = (iterationId: string, startDate: Date, endDate: Date, memberName: string, memberId: string) => { const isTeam = memberName === Everyone; startDate = shiftToUTC(startDate); endDate = shiftToUTC(endDate); if (isTeam) { const teamDaysOff = this.teamDayOffMap[iterationId]; // delete from cached copy delete this.teamDayOffMap[iterationId]; const teamDaysOffPatch: TeamSettingsDaysOffPatch = { daysOff: teamDaysOff.daysOff }; teamDaysOffPatch.daysOff.push({ end: endDate, start: startDate }); return this.workClient.updateTeamDaysOff(teamDaysOffPatch, this.teamContext, iterationId); } else { const capacity = this.capacityMap[iterationId] && this.capacityMap[iterationId][memberId] ? this.capacityMap[iterationId][memberId] : { activities: [ { capacityPerDay: 0, name: "" } ], daysOff: [] }; // delete from cached copy delete this.capacityMap[iterationId]; const capacityPatch: CapacityPatch = { activities: capacity.activities, daysOff: capacity.daysOff }; capacityPatch.daysOff.push({ start: startDate, end: endDate }); return this.workClient.updateCapacityWithIdentityRef(capacityPatch, this.teamContext, iterationId, memberId); } }; /** *Delete day off for a member or a team */ public deleteEvent = (event: ICalendarEvent, iterationId: string) => { const isTeam = event.member!.displayName === Everyone; const startDate = shiftToUTC(new Date(event.startDate)); if (isTeam) { const teamDaysOff = this.teamDayOffMap[iterationId]; delete this.teamDayOffMap[iterationId]; var i; for (i = 0; i < teamDaysOff.daysOff.length; i++) { if (teamDaysOff.daysOff[i].start.valueOf() === startDate.valueOf()) { teamDaysOff.daysOff.splice(i, 1); break; } } const teamDaysOffPatch: TeamSettingsDaysOffPatch = { daysOff: teamDaysOff.daysOff }; return this.workClient.updateTeamDaysOff(teamDaysOffPatch, this.teamContext, iterationId); } else { const capacity = this.capacityMap[iterationId][event.member!.id]; delete this.capacityMap[iterationId]; var i; for (i = 0; i < capacity.daysOff.length; i++) { if (capacity.daysOff[i].start.valueOf() === startDate.valueOf()) { capacity.daysOff.splice(i, 1); break; } } const capacityPatch: CapacityPatch = { activities: capacity.activities, daysOff: capacity.daysOff }; return this.workClient.updateCapacityWithIdentityRef(capacityPatch, this.teamContext, iterationId, event.member!.id); } }; public getCapacitySummaryData = (): ObservableArray<IEventCategory> => { return this.capacitySummaryData; }; public getCapacityUrl = (): ObservableValue<string> => { return this.capacityUrl; }; public getEvents = ( arg: { start: Date; end: Date; timeZone: string; }, successCallback: (events: EventInput[]) => void, failureCallback: (error: EventSourceError) => void ): void | PromiseLike<EventInput[]> => { const capacityPromises: PromiseLike<TeamMemberCapacity[]>[] = []; const teamDaysOffPromises: PromiseLike<TeamSettingsDaysOff>[] = []; const renderedEvents: EventInput[] = []; const capacityCatagoryMap: { [id: string]: IEventCategory } = {}; const currentIterations: IEventCategory[] = []; this.groupedEventMap = {}; this.fetchIterations().then(iterations => { if (!iterations) { iterations = []; } this.iterations = iterations; // convert end date to inclusive end date const calendarStart = arg.start; const calendarEnd = new Date(arg.end); calendarEnd.setDate(arg.end.getDate() - 1); for (const iteration of iterations) { let loadIterationData = false; if (iteration.attributes.startDate && iteration.attributes.finishDate) { const iterationStart = shiftToLocal(iteration.attributes.startDate); const iterationEnd = shiftToLocal(iteration.attributes.finishDate); const exclusiveIterationEndDate = new Date(iterationEnd); exclusiveIterationEndDate.setDate(iterationEnd.getDate() + 1); if ( (calendarStart <= iterationStart && iterationStart <= calendarEnd) || (calendarStart <= iterationEnd && iterationEnd <= calendarEnd) || (iterationStart <= calendarStart && iterationEnd >= calendarEnd) ) { loadIterationData = true; const now = new Date(); let color; if (iteration.attributes.startDate <= now && now <= iteration.attributes.finishDate) { color = generateColor("currentIteration"); } else { color = generateColor("otherIteration"); } renderedEvents.push({ allDay: true, backgroundColor: color, end: exclusiveIterationEndDate, id: IterationId + iteration.name, rendering: "background", start: iterationStart, textColor: "#FFFFFF", title: iteration.name }); currentIterations.push({ color: color, eventCount: 1, subTitle: formatDate(iterationStart, "MONTH-DD") + " - " + formatDate(iterationEnd, "MONTH-DD"), title: iteration.name }); } } else { loadIterationData = true; } if (loadIterationData) { const teamsDayOffPromise = this.fetchTeamDaysOff(iteration.id); teamDaysOffPromises.push(teamsDayOffPromise); teamsDayOffPromise.then((teamDaysOff: TeamSettingsDaysOff) => { this.processTeamDaysOff(teamDaysOff, iteration.id, capacityCatagoryMap, calendarStart, calendarEnd); }); const capacityPromise = this.fetchCapacities(iteration.id); capacityPromises.push(capacityPromise); capacityPromise.then((capacities: TeamMemberCapacityIdentityRef[]) => { this.processCapacity(capacities, iteration.id, capacityCatagoryMap, calendarStart, calendarEnd); }); } } Promise.all(teamDaysOffPromises).then(() => { Promise.all(capacityPromises).then(() => { Object.keys(this.groupedEventMap).forEach(id => { const event = this.groupedEventMap[id]; // skip events with date strings we can't parse. const start = new Date(event.startDate); const end = new Date(event.endDate); if ((calendarStart <= start && start <= calendarEnd) || (calendarStart <= end && end <= calendarEnd)) { renderedEvents.push({ allDay: true, color: "transparent", editable: false, end: end, id: event.id, start: start, title: "" }); } }); successCallback(renderedEvents); this.iterationSummaryData.value = currentIterations; this.capacitySummaryData.value = Object.keys(capacityCatagoryMap).map(key => { const catagory = capacityCatagoryMap[key]; if (catagory.eventCount > 1) { catagory.subTitle = catagory.eventCount + " days off"; } return catagory; }); }); }); }); }; public getGroupedEventForDate = (date: Date): ICalendarEvent => { const dateString = date.toISOString(); return this.groupedEventMap[dateString]; }; public getIterationForDate = (startDate: Date, endDate: Date): TeamSettingsIteration | undefined => { let iteration = undefined; startDate = shiftToUTC(startDate); endDate = shiftToUTC(endDate); this.iterations.forEach(item => { if ( item.attributes.startDate <= startDate && startDate <= item.attributes.finishDate && item.attributes.startDate <= endDate && endDate <= item.attributes.finishDate ) { iteration = item; } }); return iteration; }; public getIterationSummaryData = (): ObservableArray<IEventCategory> => { return this.iterationSummaryData; }; public getIterationUrl = (): ObservableValue<string> => { return this.iterationUrl; }; public initialize(projectId: string, projectName: string, teamId: string, teamName: string, hostUrl: string) { this.hostUrl = hostUrl; this.teamContext = { project: projectName, projectId: projectId, team: teamName, teamId: teamId }; this.teamDayOffMap = {}; this.capacityMap = {}; this.iterations = []; this.updateUrls(); } public updateEvent = (oldEvent: ICalendarEvent, iterationId: string, startDate: Date, endDate: Date) => { const isTeam = oldEvent.member!.displayName === Everyone; const orignalStartDate = shiftToUTC(new Date(oldEvent.startDate)); startDate = shiftToUTC(startDate); endDate = shiftToUTC(endDate); if (isTeam) { const teamDaysOff = this.teamDayOffMap[iterationId]; delete this.teamDayOffMap[iterationId]; var i; for (i = 0; i < teamDaysOff.daysOff.length; i++) { if (teamDaysOff.daysOff[i].start.valueOf() === orignalStartDate.valueOf()) { teamDaysOff.daysOff[i].start = startDate; teamDaysOff.daysOff[i].end = endDate; break; } } const teamDaysOffPatch: TeamSettingsDaysOffPatch = { daysOff: teamDaysOff.daysOff }; return this.workClient.updateTeamDaysOff(teamDaysOffPatch, this.teamContext, iterationId); } else { const capacity = this.capacityMap[iterationId][oldEvent.member!.id]; delete this.capacityMap[iterationId]; var i; for (i = 0; i < capacity.daysOff.length; i++) { if (capacity.daysOff[i].start.valueOf() === orignalStartDate.valueOf()) { capacity.daysOff[i].start = startDate; capacity.daysOff[i].end = endDate; break; } } const capacityPatch: CapacityPatch = { activities: capacity.activities, daysOff: capacity.daysOff }; return this.workClient.updateCapacityWithIdentityRef(capacityPatch, this.teamContext, iterationId, oldEvent.member!.id); } }; private buildTeamImageUrl(id: string): string { return this.hostUrl + "_api/_common/IdentityImage?id=" + id; } private fetchCapacities = (iterationId: string): Promise<TeamMemberCapacityIdentityRef[]> => { // fetch capacities only if not in cache if (this.capacityMap[iterationId]) { const capacities = []; for (var key in this.capacityMap[iterationId]) { capacities.push(this.capacityMap[iterationId][key]); } return Promise.resolve(capacities); } return this.workClient.getCapacitiesWithIdentityRef(this.teamContext, iterationId); }; private fetchIterations = (): Promise<TeamSettingsIteration[]> => { // fetch iterations only if not in cache if (this.iterations.length > 0) { return Promise.resolve(this.iterations); } return this.workClient.getTeamIterations(this.teamContext); }; private fetchTeamDaysOff = (iterationId: string): Promise<TeamSettingsDaysOff> => { // fetch team day off only if not in cache if (this.teamDayOffMap[iterationId]) { return Promise.resolve(this.teamDayOffMap[iterationId]); } return this.workClient.getTeamDaysOff(this.teamContext, iterationId); }; private processCapacity = ( capacities: TeamMemberCapacityIdentityRef[], iterationId: string, capacityCatagoryMap: { [id: string]: IEventCategory }, calendarStart: Date, calendarEnd: Date ) => { if (capacities && capacities.length) { for (const capacity of capacities) { if (this.capacityMap[iterationId]) { this.capacityMap[iterationId][capacity.teamMember.id] = capacity; } else { const temp: { [memberId: string]: TeamMemberCapacityIdentityRef } = {}; temp[capacity.teamMember.id] = capacity; this.capacityMap[iterationId] = temp; } for (const daysOffRange of capacity.daysOff) { const start = shiftToLocal(daysOffRange.start); const end = shiftToLocal(daysOffRange.end); const title = capacity.teamMember.displayName + " Day Off"; const event: ICalendarEvent = { category: title, endDate: end.toISOString(), iterationId: iterationId, member: capacity.teamMember, startDate: start.toISOString(), title: title }; const icon: IEventIcon = { linkedEvent: event, src: capacity.teamMember.imageUrl }; // add personal day off event to calendar day off events const dates = getDatesInRange(start, end); for (const dateObj of dates) { if (calendarStart <= dateObj && dateObj <= calendarEnd) { if (capacityCatagoryMap[capacity.teamMember.id]) { capacityCatagoryMap[capacity.teamMember.id].eventCount++; } else { capacityCatagoryMap[capacity.teamMember.id] = { eventCount: 1, imageUrl: capacity.teamMember.imageUrl, subTitle: formatDate(dateObj, "MM-DD-YYYY"), title: capacity.teamMember.displayName }; } const date = dateObj.toISOString(); if (!this.groupedEventMap[date]) { const regroupedEvent: ICalendarEvent = { category: "Grouped Event", endDate: date, icons: [], id: DaysOffId + "." + date, member: event.member, startDate: date, title: "Grouped Event" }; this.groupedEventMap[date] = regroupedEvent; } this.groupedEventMap[date].icons!.push(icon); } } } } } }; private processTeamDaysOff = ( teamDaysOff: TeamSettingsDaysOff, iterationId: string, capacityCatagoryMap: { [id: string]: IEventCategory }, calendarStart: Date, calendarEnd: Date ) => { if (teamDaysOff && teamDaysOff.daysOff) { this.teamDayOffMap[iterationId] = teamDaysOff; for (const daysOffRange of teamDaysOff.daysOff) { const teamImage = this.buildTeamImageUrl(this.teamContext.teamId); const start = shiftToLocal(daysOffRange.start); const end = shiftToLocal(daysOffRange.end); const event: ICalendarEvent = { category: this.teamContext.team, endDate: end.toISOString(), iterationId: iterationId, member: { displayName: Everyone, id: this.teamContext.teamId }, startDate: start.toISOString(), title: "Team Day Off" }; const icon: IEventIcon = { linkedEvent: event, src: teamImage }; // add personal day off event to calendar day off events const dates = getDatesInRange(start, end); for (const dateObj of dates) { if (calendarStart <= dateObj && dateObj <= calendarEnd) { if (capacityCatagoryMap[this.teamContext.team]) { capacityCatagoryMap[this.teamContext.team].eventCount++; } else { capacityCatagoryMap[this.teamContext.team] = { eventCount: 1, imageUrl: teamImage, subTitle: formatDate(dateObj, "MM-DD-YYYY"), title: this.teamContext.team }; } const date = dateObj.toISOString(); if (!this.groupedEventMap[date]) { const regroupedEvent: ICalendarEvent = { category: "Grouped Event", endDate: date, icons: [], id: DaysOffId + "." + date, member: event.member, startDate: date, title: "Grouped Event" }; this.groupedEventMap[date] = regroupedEvent; } this.groupedEventMap[date].icons!.push(icon); } } } } }; private updateUrls = () => { this.iterationUrl.value = this.hostUrl + this.teamContext.project + "/" + this.teamContext.team + "/_admin/_iterations"; this.workClient.getTeamIterations(this.teamContext, "current").then( iterations => { if (iterations.length > 0) { const iterationPath = iterations[0].path.substr(iterations[0].path.indexOf("\\") + 1); this.capacityUrl.value = this.hostUrl + this.teamContext.project + "/" + this.teamContext.team + "/_backlogs/capacity/" + iterationPath; } else { this.capacityUrl.value = this.hostUrl + this.teamContext.project + "/" + this.teamContext.team + "/_admin/_iterations"; } }, error => { this.capacityUrl.value = this.hostUrl + this.teamContext.project + "/" + this.teamContext.team + "/_admin/_iterations"; } ); }; }
the_stack
import { round, IEventListener, similar } from '../internal'; import { toolbar } from './annotations'; import Column, { widthChanged, labelChanged, metaDataChanged, dirty, dirtyHeader, dirtyValues, rendererTypeChanged, groupRendererChanged, summaryRendererChanged, visibilityChanged, dirtyCaches, } from './Column'; import type CompositeColumn from './CompositeColumn'; import type { addColumn, filterChanged, moveColumn, removeColumn } from './CompositeColumn'; import CompositeNumberColumn, { ICompositeNumberDesc } from './CompositeNumberColumn'; import type { IDataRow, IFlatColumn, IMultiLevelColumn, ITypeFactory } from './interfaces'; import { integrateDefaults } from './internal'; /** * factory for creating a description creating a stacked column * @param label * @returns {{type: string, label: string}} */ export function createStackDesc(label = 'Weighted Sum', showNestedSummaries = true): IStackColumnColumnDesc { return { type: 'stack', label, showNestedSummaries }; } /** * emitted when the collapse property changes * @asMemberOf StackColumn * @event */ export declare function collapseChanged(previous: boolean, current: boolean): void; /** * emitted when the weights change * @asMemberOf StackColumn * @event */ export declare function weightsChanged(previous: number[], current: number[]): void; /** * emitted when the ratios between the children changes * @asMemberOf StackColumn * @event */ export declare function nestedChildRatio(previous: number[], current: number[]): void; export declare type IStackColumnColumnDesc = ICompositeNumberDesc & { /** * show nested summaries * @default true */ showNestedSummaries?: boolean; }; /** * implementation of the stacked column */ @toolbar('editWeights', 'compress', 'expand') export default class StackColumn extends CompositeNumberColumn implements IMultiLevelColumn { static readonly EVENT_COLLAPSE_CHANGED = 'collapseChanged'; static readonly EVENT_WEIGHTS_CHANGED = 'weightsChanged'; static readonly EVENT_MULTI_LEVEL_CHANGED = 'nestedChildRatio'; static readonly COLLAPSED_RENDERER = 'number'; private readonly adaptChange: (old: number, newValue: number) => void; /** * whether this stack column is collapsed i.e. just looks like an ordinary number column * @type {boolean} * @private */ private collapsed = false; constructor(id: string, desc: IStackColumnColumnDesc) { super( id, integrateDefaults(desc, { renderer: 'stack', groupRenderer: 'stack', summaryRenderer: 'stack', }) ); // eslint-disable-next-line @typescript-eslint/no-this-alias const that = this; this.adaptChange = function (this: { source: Column }, oldValue, newValue) { that.adaptWidthChange(this.source, oldValue, newValue); }; } get label() { const l = super.getMetaData().label; const c = this._children; if (l !== 'Weighted Sum' || c.length === 0) { return l; } const weights = this.getWeights(); return c.map((c, i) => `${c.label} (${round(100 * weights[i], 1)}%)`).join(' + '); } protected createEventList() { return super .createEventList() .concat([ StackColumn.EVENT_COLLAPSE_CHANGED, StackColumn.EVENT_WEIGHTS_CHANGED, StackColumn.EVENT_MULTI_LEVEL_CHANGED, ]); } on(type: typeof StackColumn.EVENT_COLLAPSE_CHANGED, listener: typeof collapseChanged | null): this; on(type: typeof StackColumn.EVENT_WEIGHTS_CHANGED, listener: typeof weightsChanged | null): this; on(type: typeof StackColumn.EVENT_MULTI_LEVEL_CHANGED, listener: typeof nestedChildRatio | null): this; on(type: typeof CompositeColumn.EVENT_FILTER_CHANGED, listener: typeof filterChanged | null): this; on(type: typeof CompositeColumn.EVENT_ADD_COLUMN, listener: typeof addColumn | null): this; on(type: typeof CompositeColumn.EVENT_MOVE_COLUMN, listener: typeof moveColumn | null): this; on(type: typeof CompositeColumn.EVENT_REMOVE_COLUMN, listener: typeof removeColumn | null): this; on(type: typeof Column.EVENT_WIDTH_CHANGED, listener: typeof widthChanged | null): this; on(type: typeof Column.EVENT_LABEL_CHANGED, listener: typeof labelChanged | null): this; on(type: typeof Column.EVENT_METADATA_CHANGED, listener: typeof metaDataChanged | null): this; on(type: typeof Column.EVENT_DIRTY, listener: typeof dirty | null): this; on(type: typeof Column.EVENT_DIRTY_HEADER, listener: typeof dirtyHeader | null): this; on(type: typeof Column.EVENT_DIRTY_VALUES, listener: typeof dirtyValues | null): this; on(type: typeof Column.EVENT_DIRTY_CACHES, listener: typeof dirtyCaches | null): this; on(type: typeof Column.EVENT_RENDERER_TYPE_CHANGED, listener: typeof rendererTypeChanged | null): this; on(type: typeof Column.EVENT_GROUP_RENDERER_TYPE_CHANGED, listener: typeof groupRendererChanged | null): this; on(type: typeof Column.EVENT_SUMMARY_RENDERER_TYPE_CHANGED, listener: typeof summaryRendererChanged | null): this; on(type: typeof Column.EVENT_VISIBILITY_CHANGED, listener: typeof visibilityChanged | null): this; on(type: string | string[], listener: IEventListener | null): this; // required for correct typings in *.d.ts on(type: string | string[], listener: IEventListener | null): this { return super.on(type, listener); } setCollapsed(value: boolean) { if (this.collapsed === value) { return; } this.fire( [StackColumn.EVENT_COLLAPSE_CHANGED, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY], this.collapsed, (this.collapsed = value) ); } getCollapsed() { return this.collapsed; } isShowNestedSummaries() { return (this.desc as IStackColumnColumnDesc).showNestedSummaries !== false; } get canJustAddNumbers() { return true; } flatten(r: IFlatColumn[], offset: number, levelsToGo = 0, padding = 0) { let self = null; const children = levelsToGo <= Column.FLAT_ALL_COLUMNS ? this._children : this._children.filter((c) => c.isVisible()); //no more levels or just this one if (levelsToGo === 0 || levelsToGo <= Column.FLAT_ALL_COLUMNS) { let w = this.getWidth(); if (!this.collapsed) { w += (children.length - 1) * padding; } r.push((self = { col: this, offset, width: w })); if (levelsToGo === 0) { return w; } } //push children let acc = offset; children.forEach((c) => { acc += c.flatten(r, acc, levelsToGo - 1, padding) + padding; }); if (self) { //nesting my even increase my width self.width = acc - offset - padding; } return acc - offset - padding; } dump(toDescRef: (desc: any) => any) { const r = super.dump(toDescRef); r.collapsed = this.collapsed; return r; } restore(dump: any, factory: ITypeFactory) { this.collapsed = dump.collapsed === true; super.restore(dump, factory); } /** * inserts a column at a the given position */ insert(col: Column, index: number, weight = NaN) { if (!Number.isNaN(weight)) { col.setWidth((weight / (1 - weight)) * this.getWidth()); } col.on(`${Column.EVENT_WIDTH_CHANGED}.stack`, this.adaptChange); //increase my width super.setWidth(this.length === 0 ? col.getWidth() : this.getWidth() + col.getWidth()); return super.insert(col, index); } push(col: Column, weight = NaN) { return this.insert(col, this.length, weight); } insertAfter(col: Column, ref: Column, weight = NaN) { const i = this.indexOf(ref); if (i < 0) { return null; } return this.insert(col, i + 1, weight); } /** * adapts weights according to an own width change * @param col * @param oldValue * @param newValue */ private adaptWidthChange(col: Column, oldValue: number, newValue: number) { if (similar(oldValue, newValue, 0.5)) { return; } const bak = this.getWeights(); const full = this.getWidth(), change = (newValue - oldValue) / full; const oldWeight = oldValue / full; const factor = (1 - oldWeight - change) / (1 - oldWeight); const widths = this._children.map((c) => { if (c === col) { //c.weight += change; return newValue; } const guess = c.getWidth() * factor; const w = Number.isNaN(guess) || guess < 1 ? 0 : guess; c.setWidthImpl(w); return w; }); //adapt width if needed super.setWidth(widths.reduce((a, b) => a + b, 0)); this.fire( [ StackColumn.EVENT_WEIGHTS_CHANGED, StackColumn.EVENT_MULTI_LEVEL_CHANGED, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY_CACHES, Column.EVENT_DIRTY, ], bak, this.getWeights() ); } getWeights() { const w = this.getWidth(); return this._children.map((d) => d.getWidth() / w); } setWeights(weights: number[]) { const bak = this.getWeights(); const delta = weights.length - this.length; let s: number; if (delta < 0) { s = weights.reduce((p, a) => p + a, 0); if (s <= 1) { for (let i = 0; i < -delta; ++i) { weights.push((1 - s) * (1 / -delta)); } } else if (s <= 100) { for (let i = 0; i < -delta; ++i) { weights.push((100 - s) * (1 / -delta)); } } } weights = weights.slice(0, this.length); s = weights.reduce((p, a) => p + a, 0) / this.getWidth(); weights = weights.map((d) => d / s); this._children.forEach((c, i) => { c.setWidthImpl(weights[i]); }); this.fire( [ StackColumn.EVENT_WEIGHTS_CHANGED, StackColumn.EVENT_MULTI_LEVEL_CHANGED, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY_CACHES, Column.EVENT_DIRTY, ], bak, weights ); } removeImpl(child: Column, index: number) { child.on(`${Column.EVENT_WIDTH_CHANGED}.stack`, null); super.setWidth(this.length === 0 ? 100 : this.getWidth() - child.getWidth()); return super.removeImpl(child, index); } setWidth(value: number) { const factor = value / this.getWidth(); this._children.forEach((child) => { //disable since we change it child.setWidthImpl(child.getWidth() * factor); }); super.setWidth(value); } protected compute(row: IDataRow) { const w = this.getWidth(); // missing value for the stack column if at least one child value is missing if (this._children.some((d) => d.getValue(row) === null)) { return null; } return this._children.reduce((acc, d) => acc + d.getValue(row) * (d.getWidth() / w), 0); } getRenderer() { if (this.getCollapsed() && this.isLoaded()) { return StackColumn.COLLAPSED_RENDERER; } return super.getRenderer(); } getExportValue(row: IDataRow, format: 'text' | 'json'): any { if (format === 'json') { return { value: this.getRawNumber(row), children: this.children.map((d) => d.getExportValue(row, format)), }; } return super.getExportValue(row, format); } }
the_stack
import { JupyterFrontEnd, JupyterFrontEndPlugin } from '@jupyterlab/application'; import { FileEditor, IEditorTracker } from '@jupyterlab/fileeditor'; import { INotebookTracker } from '@jupyterlab/notebook'; import { LabIcon } from '@jupyterlab/ui-components'; import { ICommandPalette, InputDialog, ReactWidget } from '@jupyterlab/apputils'; import { Menu } from '@lumino/widgets'; import { ReadonlyPartialJSONObject } from '@lumino/coreutils'; import { ISettingRegistry } from '@jupyterlab/settingregistry'; import { IStatusBar, TextItem } from '@jupyterlab/statusbar'; import { Cell } from '@jupyterlab/cells'; import { CodeMirrorEditor, ICodeMirror } from '@jupyterlab/codemirror'; import { ITranslator, nullTranslator, TranslationBundle } from '@jupyterlab/translation'; import CodeMirror from 'codemirror'; import { requestAPI } from './handler'; import '../style/index.css'; import spellcheckSvg from '../style/icons/ic-baseline-spellcheck.svg'; export const spellcheckIcon = new LabIcon({ name: 'spellcheck:spellcheck', svgstr: spellcheckSvg }); declare function require(name: string): any; // eslint-disable-next-line @typescript-eslint/no-var-requires const Typo = require('typo-js'); const enum CommandIDs { applySuggestion = 'spellchecker:apply-suggestion', ignoreWord = 'spellchecker:ignore', toggle = 'spellchecker:toggle-check-spelling', updateSuggestions = 'spellchecker:update-suggestions', chooseLanguage = 'spellchecker:choose-language' } interface IWord { line: number; start: number; end: number; text: string; } interface IContext { editor: CodeMirror.Editor; position: CodeMirror.Position; } /** * Dictionary data defined by a pair of Hunspell .aff and .dic files. * More than one dictionary may exist for a given language. */ interface IDictionary extends ReadonlyPartialJSONObject { /** * Identifier of the dictionary consisting of the filename without the .aff/.dic suffix * and path information if needed to distinguish from other dictionaries. */ id: string; /** * BCP 47 code identifier. * Absent for online dictionaries. */ code?: string; /** * Display name, usually in the form "Language (Region)". */ name: string; /** * Path to the .aff file. */ aff: string; /** * Path to the .dic file. */ dic: string; /** * Indicated whether the dictionary is online. */ isOnline: boolean; } interface ILanguageManagerResponse { version: string; dictionaries: Omit<IDictionary, 'isOnline'>[]; } class LanguageManager { protected serverDictionaries: IDictionary[]; protected onlineDictionaries: IDictionary[]; public ready: Promise<any>; /** * initialise the manager * mainly reading the definitions from the external extension */ constructor(settingsRegistry: ISettingRegistry) { const loadSettings = settingsRegistry.load(extension.id).then(settings => { this.updateSettings(settings); settings.changed.connect(() => { this.updateSettings(settings); }); }); this.ready = Promise.all([ this.fetchServerDictionariesList(), loadSettings ]).then(() => { console.debug('LanguageManager is ready'); }); } protected updateSettings(settings: ISettingRegistry.ISettings) { if (settings) { this.onlineDictionaries = ( settings.get('onlineDictionaries').composite as Omit< IDictionary, 'isOnline' | 'code' >[] ).map(dictionary => { return { ...dictionary, isOnline: true } as IDictionary; }); } } /** * Read the list of languages from the server extension */ protected fetchServerDictionariesList(): Promise<void> { return requestAPI<ILanguageManagerResponse>('language_manager').then( values => { console.debug('Dictionaries fetched from server'); this.serverDictionaries = values.dictionaries.map(dictionary => { return { ...dictionary, isOnline: false } as IDictionary; }); } ); } get dictionaries(): IDictionary[] { return [...this.serverDictionaries, ...this.onlineDictionaries]; } /** * get an array of languages, put "language" in front of the list * the list is alphabetically sorted */ getChoices(language: IDictionary | undefined) { const options = language ? [language, ...this.dictionaries.filter(l => l.id !== language.id)] : this.dictionaries; return options.sort((a, b) => a.name.localeCompare(b.name)); } /** * select the language by the identifier */ getLanguageByIdentifier(identifier: string): IDictionary | undefined { const exactMatch = this.dictionaries.find(l => l.id === identifier); if (exactMatch) { return exactMatch; } // approximate matches support transition from the 0.5 version (and older) // that used incorrect codes as language identifiers const approximateMatch = this.dictionaries.find( l => l.id.toLowerCase() === identifier.replace('-', '_').toLowerCase() ); if (approximateMatch) { console.warn( `Language identifier ${identifier} has a non-exact match, please update it to ${approximateMatch.id}` ); return approximateMatch; } } } class StatusWidget extends ReactWidget { language_source: () => string; constructor(source: () => string) { super(); this.language_source = source; } protected render() { return TextItem({ source: this.language_source() }); } } /** * SpellChecker */ class SpellChecker { dictionary: any; suggestions_menu: Menu; status_widget: StatusWidget; status_msg: string; // Default Options check_spelling = true; language: IDictionary | undefined; language_manager: LanguageManager; rx_word_char = /[^-[\]{}():/!;&@$£%§<>"*+=?.,~\\^|_`#±\s\t]/; rx_non_word_char = /[-[\]{}():/!;&@$£%§<>"*+=?.,~\\^|_`#±\s\t]/; ignored_tokens: Set<string> = new Set(); settings: ISettingRegistry.ISettings; accepted_types: string[]; private _trans: TranslationBundle; readonly TEXT_SUGGESTIONS_AVAILABLE: string; readonly TEXT_NO_SUGGESTIONS: string; readonly PALETTE_CATEGORY: string; constructor( protected app: JupyterFrontEnd, protected tracker: INotebookTracker, protected editor_tracker: IEditorTracker, protected setting_registry: ISettingRegistry, protected code_mirror: ICodeMirror, translator: ITranslator, protected palette?: ICommandPalette | null, protected status_bar?: IStatusBar | null ) { // use the language_manager this.language_manager = new LanguageManager(setting_registry); this._trans = translator.load('jupyterlab-spellchecker'); this.status_msg = this._trans.__('Dictionary not loaded'); this.TEXT_SUGGESTIONS_AVAILABLE = this._trans.__('Adjust spelling to'); this.TEXT_NO_SUGGESTIONS = this._trans.__('No spellcheck suggestions'); this.PALETTE_CATEGORY = this._trans.__('Spell Checker'); // read the settings this.setup_settings(); // setup the static content of the spellchecker UI this.setup_button(); this.setup_suggestions(); this.setup_language_picker(); this.setup_ignore_action(); this.tracker.activeCellChanged.connect(() => { if (this.tracker.activeCell) { this.setup_cell_editor(this.tracker.activeCell); } }); // setup newly open editors this.editor_tracker.widgetAdded.connect((sender, widget) => this.setup_file_editor(widget.content, true) ); // refresh already open editors when activated (because the MIME type might have changed) this.editor_tracker.currentChanged.connect((sender, widget) => { if (widget !== null) { this.setup_file_editor(widget.content, false); } }); } // move the load_dictionary into the setup routine, because then // we know that the values are set correctly! setup_settings() { Promise.all([ this.setting_registry.load(extension.id), this.app.restored, this.language_manager.ready ]) .then(([settings]) => { this.update_settings(settings); settings.changed.connect(() => { this.update_settings(settings); }); }) .catch((reason: Error) => { console.error(reason.message); }); } protected _set_theme(name: string) { document.body.setAttribute('data-jp-spellchecker-theme', name); } update_settings(settings: ISettingRegistry.ISettings) { this.settings = settings; const tokens = settings.get('ignore').composite as Array<string>; this.ignored_tokens = new Set(tokens); this.accepted_types = settings.get('mimeTypes').composite as Array<string>; const theme = settings.get('theme').composite as string; this._set_theme(theme); // read the saved language setting const language_id = settings.get('language').composite as string; const user_language = this.language_manager.getLanguageByIdentifier(language_id); if (user_language === undefined) { console.warn('The language ' + language_id + ' is not supported!'); } else { this.language = user_language; // load the dictionary this.load_dictionary().catch(console.warn); } this.refresh_state(); } setup_file_editor(file_editor: FileEditor, setup_signal = false): void { if ( this.accepted_types && this.accepted_types.indexOf(file_editor.model.mimeType) !== -1 ) { const editor = this.extract_editor(file_editor); this.setup_overlay(editor); } if (setup_signal) { file_editor.model.mimeTypeChanged.connect((model, args) => { // putting at the end of execution queue to allow the CodeMirror mode to be updated setTimeout(() => this.setup_file_editor(file_editor), 0); }); } } setup_cell_editor(cell: Cell): void { if (cell !== null && cell.model.type === 'markdown') { const editor = this.extract_editor(cell); this.setup_overlay(editor); } } extract_editor(cell_or_editor: Cell | FileEditor): CodeMirror.Editor { const editor_temp = cell_or_editor.editor as CodeMirrorEditor; return editor_temp.editor; } setup_overlay(editor: CodeMirror.Editor, retry = true): void { const current_mode = editor.getOption('mode') as string; if (current_mode === 'null') { if (retry) { // putting at the end of execution queue to allow the CodeMirror mode to be updated setTimeout(() => this.setup_overlay(editor, false), 0); } return; } if (this.check_spelling) { editor.setOption('mode', this.define_mode(current_mode)); } else { const original_mode = current_mode.match(/^spellcheck_/) ? current_mode.substr(11) : current_mode; editor.setOption('mode', original_mode); } } toggle_spellcheck() { this.check_spelling = !this.check_spelling; console.log('Spell checking is currently: ', this.check_spelling); } setup_button() { this.app.commands.addCommand(CommandIDs.toggle, { label: this._trans.__('Toggle spellchecker'), execute: () => { this.toggle_spellcheck(); } }); if (this.palette) { this.palette.addItem({ command: CommandIDs.toggle, category: this.PALETTE_CATEGORY }); } } get_contextmenu_context(): IContext | null { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const event = this.app._contextMenuEvent as MouseEvent; const target = event.target as HTMLElement; const code_mirror_wrapper: any = target.closest('.CodeMirror'); if (code_mirror_wrapper === null) { return null; } const code_mirror = code_mirror_wrapper.CodeMirror as CodeMirror.Editor; const position = code_mirror.coordsChar({ left: event.clientX, top: event.clientY }); return { editor: code_mirror, position: position }; } /** * This is different from token as implemented in CodeMirror * and needed because Markdown does not tokenize words * (each letter outside of markdown features is a separate token!) */ get_current_word(context: IContext): IWord { const { editor, position } = context; const line = editor.getDoc().getLine(position.line); let start = position.ch; while (start > 0 && line[start].match(this.rx_word_char)) { start--; } let end = position.ch; while (end < line.length && line[end].match(this.rx_word_char)) { end++; } return { line: position.line, start: start, end: end, text: line.substring(start, end) }; } setup_suggestions() { this.suggestions_menu = new Menu({ commands: this.app.commands }); this.suggestions_menu.title.label = this.TEXT_SUGGESTIONS_AVAILABLE; this.suggestions_menu.title.icon = spellcheckIcon.bindprops({ stylesheet: 'menuItem' }); // this command is not meant to be show - it is just menu trigger detection hack this.app.commands.addCommand(CommandIDs.updateSuggestions, { execute: args => { // no-op }, isVisible: args => { this.prepare_suggestions(); return false; } }); this.app.contextMenu.addItem({ selector: '.cm-spell-error', command: CommandIDs.updateSuggestions }); // end of the menu trigger detection hack this.app.contextMenu.addItem({ selector: '.cm-spell-error', submenu: this.suggestions_menu, type: 'submenu' }); this.app.commands.addCommand(CommandIDs.applySuggestion, { execute: args => { this.apply_suggestion(args['name'] as string); }, label: args => args['name'] as string }); } setup_ignore_action() { this.app.commands.addCommand(CommandIDs.ignoreWord, { execute: () => { this.ignore(); }, label: this._trans.__('Ignore') }); this.app.contextMenu.addItem({ selector: '.cm-spell-error', command: CommandIDs.ignoreWord }); } ignore() { const context = this.get_contextmenu_context(); if (context === null) { console.log( 'Could not ignore the word as the context was no longer available' ); } else { const word = this.get_current_word(context); this.settings .set('ignore', [ word.text.trim(), ...(this.settings.get('ignore').composite as Array<string>) ]) .catch(console.warn); } } prepare_suggestions() { const context = this.get_contextmenu_context(); let suggestions: string[]; if (context === null) { // no context (e.g. the edit was applied and the token is no longer in DOM, // so we cannot find the parent editor suggestions = []; } else { const word = this.get_current_word(context); suggestions = this.dictionary.suggest(word.text); } this.suggestions_menu.clearItems(); if (suggestions.length) { for (const suggestion of suggestions) { this.suggestions_menu.addItem({ command: CommandIDs.applySuggestion, args: { name: suggestion } }); } this.suggestions_menu.title.label = this.TEXT_SUGGESTIONS_AVAILABLE; this.suggestions_menu.title.className = ''; this.suggestions_menu.setHidden(false); } else { this.suggestions_menu.title.className = 'lm-mod-disabled'; this.suggestions_menu.title.label = this.TEXT_NO_SUGGESTIONS; this.suggestions_menu.setHidden(true); } } apply_suggestion(replacement: string) { const context = this.get_contextmenu_context(); if (context === null) { console.warn( 'Applying suggestion failed (probably was already applied earlier)' ); return; } const word = this.get_current_word(context); context.editor.getDoc().replaceRange( replacement, { ch: word.start, line: word.line }, { ch: word.end, line: word.line } ); } load_dictionary() { const language = this.language; if (!language) { return new Promise((accept, reject) => reject('Cannot load dictionary: no language set') ); } this.status_msg = this._trans.__('Loading dictionary…'); this.status_widget.update(); return Promise.all([ fetch(language.aff).then(res => res.text()), fetch(language.dic).then(res => res.text()) ]).then(values => { this.dictionary = new Typo(language.name, values[0], values[1]); console.debug('Dictionary Loaded ', language.name, language.id); this.status_msg = language.name; // update the complete UI this.status_widget.update(); this.refresh_state(); }); } define_mode = (original_mode_spec: string) => { if (original_mode_spec.indexOf('spellcheck_') === 0) { return original_mode_spec; } const new_mode_spec = 'spellcheck_' + original_mode_spec; this.code_mirror.CodeMirror.defineMode(new_mode_spec, (config: any) => { const spellchecker_overlay = { name: new_mode_spec, token: (stream: any, state: any) => { if (stream.eatWhile(this.rx_word_char)) { const word = stream.current().replace(/(^')|('$)/g, ''); if ( word !== '' && !word.match(/^\d+$/) && this.dictionary !== undefined && !this.dictionary.check(word) && !this.ignored_tokens.has(word) ) { return 'spell-error'; } } stream.eatWhile(this.rx_non_word_char); return null; } }; return this.code_mirror.CodeMirror.overlayMode( this.code_mirror.CodeMirror.getMode(config, original_mode_spec), spellchecker_overlay, true ); }); return new_mode_spec; }; refresh_state() { // update the active cell (if any) if (this.tracker.activeCell !== null) { this.setup_cell_editor(this.tracker.activeCell); } // update the current file editor (if any) if (this.editor_tracker.currentWidget !== null) { this.setup_file_editor(this.editor_tracker.currentWidget.content); } } choose_language() { const choices = this.language_manager.getChoices(this.language); const choiceStrings = choices.map( // note: two dictionaries may exist for a language with the same name, // so we append the actual id of the dictionary in the square brackets. dictionary => dictionary.isOnline ? this._trans.__('%1 [%2] (online)', dictionary.name, dictionary.id) : this._trans.__('%1 [%2]', dictionary.name, dictionary.id) ); InputDialog.getItem({ title: this._trans.__('Choose spellchecker language'), items: choiceStrings }).then(value => { if (value.value !== null) { const index = choiceStrings.indexOf(value.value); const lang = this.language_manager.getLanguageByIdentifier( choices[index].id ); if (!lang) { console.error( 'Language could not be matched - please report this as an issue' ); return; } this.language = lang; // the setup routine will load the dictionary this.settings.set('language', this.language.id).catch(console.warn); } }); } setup_language_picker() { this.status_widget = new StatusWidget(() => this.status_msg); this.status_widget.node.onclick = () => { this.choose_language(); }; this.app.commands.addCommand(CommandIDs.chooseLanguage, { execute: args => this.choose_language(), label: this._trans.__('Choose spellchecker language') }); if (this.palette) { this.palette.addItem({ command: CommandIDs.chooseLanguage, category: this.PALETTE_CATEGORY }); } if (this.status_bar) { this.status_bar.registerStatusItem('spellchecker:choose-language', { align: 'right', item: this.status_widget }); } } } /** * Activate extension */ function activate( app: JupyterFrontEnd, tracker: INotebookTracker, editor_tracker: IEditorTracker, setting_registry: ISettingRegistry, code_mirror: ICodeMirror, translator: ITranslator | null, palette: ICommandPalette | null, status_bar: IStatusBar | null ): void { console.log('Attempting to load spellchecker'); const sp = new SpellChecker( app, tracker, editor_tracker, setting_registry, code_mirror, translator || nullTranslator, palette, status_bar ); console.log('Spellchecker Loaded ', sp); } /** * Initialization data for the jupyterlab_spellchecker extension. */ const extension: JupyterFrontEndPlugin<void> = { id: '@ijmbarr/jupyterlab_spellchecker:plugin', autoStart: true, requires: [INotebookTracker, IEditorTracker, ISettingRegistry, ICodeMirror], optional: [ITranslator, ICommandPalette, IStatusBar], activate: activate }; export default extension;
the_stack
import { HttpClient } from '@angular/common/http'; export enum AppBridgeHandler { HTTP, OPEN, OPEN_LIST, CLOSE, REFRESH, PIN, REGISTER, UPDATE, REQUEST_DATA, CALLBACK, PING } // record - an individual entity record // add/fast-add - the add page for a new record // custom - custom action that opens the url provided in data.url // preview - the preview slideout available only in Novo export type NovoApps = 'record' | 'add' | 'fast-add' | 'custom' | 'preview'; export type AlleyLinkColors = | 'purple' | 'green' | 'blue' | 'lead' | 'candidate' | 'contact' | 'company' | 'opportunity' | 'job' | 'billable-charge' | 'earn-code' | 'invoice-statement' | 'job-code' | 'payable-charge' | 'sales-tax-rate' | 'tax-rules' | 'submission' | 'placement' | 'navigation' | 'canvas' | 'neutral' | 'neutral-italic' | 'initial' | 'distributionList' | 'contract'; export interface IAppBridgeOpenEvent { type: NovoApps; entityType: string; entityId?: string; tab?: string; data?: any; passthrough?: string; } export type MosaicLists = | 'Candidate' | 'ClientContact' | 'ClientCorporation' | 'JobOrder' | 'JobSubmission' | 'JobPosting' | 'Placement' | 'Lead' | 'Opportunity'; export interface IAppBridgeOpenListEvent { type: MosaicLists; keywords: Array<string>; criteria: any; } export type NovoDataType = 'entitlements' | 'settings' | 'user'; export interface IAppBridgeRequestDataEvent { type: NovoDataType; } const HTTP_VERBS = { GET: 'get', POST: 'post', PUT: 'put', DELETE: 'delete', }; const MESSAGE_TYPES = { REGISTER: 'register', OPEN: 'open', OPEN_LIST: 'openList', CLOSE: 'close', REFRESH: 'refresh', PIN: 'pin', PING: 'ping', UPDATE: 'update', HTTP_GET: 'httpGET', HTTP_POST: 'httpPOST', HTTP_PUT: 'httpPUT', HTTP_DELETE: 'httpDELETE', CUSTOM_EVENT: 'customEvent', REQUEST_DATA: 'requestData', CALLBACK: 'callback', }; declare const postRobot: any; export class AppBridgeService { create(name: string) { return new AppBridge(name); } } export class DevAppBridgeService { constructor(private http: HttpClient) {} create(name: string) { return new DevAppBridge(name, this.http); } } export class AppBridge { public id: string = `${Date.now()}`; public traceName: string; public windowName: string; private _registeredFrames = []; private _handlers = {}; private _tracing: boolean = false; private _eventListeners: any = {}; // Type? constructor(traceName: string = 'AppBridge') { this.traceName = traceName; if (postRobot) { postRobot.CONFIG.LOG_LEVEL = 'error'; try { this._setupHandlers(); } catch (error) { // No op } } } set tracing(tracing: boolean) { this._tracing = tracing; } public handle(type: AppBridgeHandler, handler: Function) { this._handlers[type] = handler; } private _trace(eventType, event) { if (this._tracing) { console.log(`[${this.traceName || this.id}] "${eventType}"`, event); // tslint:disable-line } } protected _setupHandlers(): void { // Register postRobot.on(MESSAGE_TYPES.REGISTER, (event) => { this._trace(MESSAGE_TYPES.REGISTER, event); this._registeredFrames.push(event); return this.register(event.data).then(windowName => { return { windowName }; }); }); // Update postRobot.on(MESSAGE_TYPES.UPDATE, (event) => { this._trace(MESSAGE_TYPES.UPDATE, event); return this.update(event.data).then(success => { return { success }; }); }); // Open postRobot.on(MESSAGE_TYPES.OPEN, (event) => { this._trace(MESSAGE_TYPES.OPEN, event); return this.open(event.data).then(success => { return { success }; }); }); postRobot.on(MESSAGE_TYPES.OPEN_LIST, (event) => { this._trace(MESSAGE_TYPES.OPEN_LIST, event); return this.openList(event.data).then(success => { return { success }; }); }); // Close postRobot.on(MESSAGE_TYPES.CLOSE, (event) => { this._trace(MESSAGE_TYPES.CLOSE, event); const index = this._registeredFrames.findIndex(frame => frame.data.id === event.data.id); if (index !== -1) { this._registeredFrames.splice(index, 1); } return this.close(event.data).then(success => { return { success }; }); }); // Refresh postRobot.on(MESSAGE_TYPES.REFRESH, (event) => { this._trace(MESSAGE_TYPES.REFRESH, event); return this.refresh(event.data).then(success => { return { success }; }); }); // PIN postRobot.on(MESSAGE_TYPES.PIN, (event) => { this._trace(MESSAGE_TYPES.PIN, event); return this.pin(event.data).then(success => { return { success }; }); }); // PING postRobot.on(MESSAGE_TYPES.PING, (event) => { this._trace(MESSAGE_TYPES.PING, event); return this.httpGET('ping').then(result => { return { data: result.data, error: result.error }; }); }); // REQUEST_DATA postRobot.on(MESSAGE_TYPES.REQUEST_DATA, (event) => { this._trace(MESSAGE_TYPES.REQUEST_DATA, event); return this.requestData(event.data).then(result => { return { data: result.data, error: result.error }; }); }); // CALLBACKS postRobot.on(MESSAGE_TYPES.CALLBACK, (event) => { this._trace(MESSAGE_TYPES.CALLBACK, event); return this.callback(event.data).then(success => { return { success }; }); }); // HTTP-GET postRobot.on(MESSAGE_TYPES.HTTP_GET, (event) => { this._trace(MESSAGE_TYPES.HTTP_GET, event); return this.httpGET(event.data.relativeURL).then(result => { return { data: result.data, error: result.error }; }); }); // HTTP-POST postRobot.on(MESSAGE_TYPES.HTTP_POST, (event) => { this._trace(MESSAGE_TYPES.HTTP_POST, event); return this.httpPOST(event.data.relativeURL, event.data.data).then(result => { return { data: result.data, error: result.error }; }); }); // HTTP-PUT postRobot.on(MESSAGE_TYPES.HTTP_PUT, (event) => { this._trace(MESSAGE_TYPES.HTTP_PUT, event); return this.httpPUT(event.data.relativeURL, event.data.data).then((result) => { return { data: result.data, error: result.error }; }); }); // HTTP-DELETE postRobot.on(MESSAGE_TYPES.HTTP_DELETE, (event) => { this._trace(MESSAGE_TYPES.HTTP_DELETE, event); return this.httpDELETE(event.data.relativeURL).then(result => { return { data: result.data, error: result.error }; }); }); // Custom Events postRobot.on(MESSAGE_TYPES.CUSTOM_EVENT, (event) => { this._trace(MESSAGE_TYPES.CUSTOM_EVENT, event); if (this._eventListeners[event.data.event]) { this._eventListeners[event.data.event].forEach((listener) => { listener(event.data.data); }); } if (this._registeredFrames.length > 0) { this._registeredFrames.forEach(frame => { postRobot.send(frame.source, MESSAGE_TYPES.CUSTOM_EVENT, event.data); }); } }); } /** * Fires or responds to an open event * @param packet any - packet of data to send with the open event */ public open(packet: IAppBridgeOpenEvent): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { if (this._handlers[AppBridgeHandler.OPEN]) { this._handlers[AppBridgeHandler.OPEN](packet, (success: boolean) => { if (success) { resolve(true); } else { reject(false); } }); } else { Object.assign(packet, { id: this.id, windowName: this.windowName }); postRobot .sendToParent(MESSAGE_TYPES.OPEN, packet) .then((event) => { this._trace(`${MESSAGE_TYPES.OPEN} (callback)`, event); if (event.data) { resolve(true); } else { reject(false); } }) .catch((err) => { reject(false); }); } }); } /** * Fires or responds to an openList event * @param packet any - packet of data to send with the open event */ public openList(packet: Partial<IAppBridgeOpenListEvent>): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { if (this._handlers[AppBridgeHandler.OPEN_LIST]) { this._handlers[AppBridgeHandler.OPEN_LIST](packet, (success: boolean) => { if (success) { resolve(true); } else { reject(false); } }); } else { const openListPacket = {}; Object.assign(openListPacket, { type: 'List', entityType: packet.type, keywords: packet.keywords, criteria: packet.criteria }); postRobot .sendToParent(MESSAGE_TYPES.OPEN_LIST, packet) .then((event) => { this._trace(`${MESSAGE_TYPES.OPEN_LIST} (callback)`, event); if (event.data) { resolve(true); } else { reject(false); } }) .catch((err) => { reject(false); }); } }); } /** * Fires or responds to an close event * @param packet any - packet of data to send with the close event */ public update( packet: Partial<{ entityType: string; entityId: string; title: string; titleKey: string; color: AlleyLinkColors }>, ): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { if (this._handlers[AppBridgeHandler.UPDATE]) { this._handlers[AppBridgeHandler.UPDATE](packet, (success: boolean) => { if (success) { resolve(true); } else { reject(false); } }); } else { Object.assign(packet, { id: this.id, windowName: this.windowName }); postRobot .sendToParent(MESSAGE_TYPES.UPDATE, packet) .then((event) => { this._trace(`${MESSAGE_TYPES.UPDATE} (callback)`, event); if (event.data) { resolve(true); } else { reject(false); } }) .catch((err) => { reject(false); }); } }); } /** * Fires or responds to an close event */ public close(packet?: object): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { if (this._handlers[AppBridgeHandler.CLOSE]) { this._handlers[AppBridgeHandler.CLOSE](packet, (success: boolean) => { if (success) { resolve(true); } else { reject(false); } }); } else { if (packet) { console.info('[AppBridge] - close(packet) is deprecated! Please just use close()!'); // tslint:disable-line } const realPacket = { id: this.id, windowName: this.windowName }; postRobot .sendToParent(MESSAGE_TYPES.CLOSE, realPacket) .then((event) => { this._trace(`${MESSAGE_TYPES.CLOSE} (callback)`, event); if (event.data) { resolve(true); } else { reject(false); } }) .catch((err) => { reject(false); }); } }); } /** * Fires or responds to an close event */ public refresh(packet?: object): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { if (this._handlers[AppBridgeHandler.REFRESH]) { this._handlers[AppBridgeHandler.REFRESH](packet, (success: boolean) => { if (success) { resolve(true); } else { reject(false); } }); } else { if (packet) { console.info('[AppBridge] - refresh(packet) is deprecated! Please just use refresh()!'); // tslint:disable-line } const realPacket = { id: this.id, windowName: this.windowName }; postRobot .sendToParent(MESSAGE_TYPES.REFRESH, realPacket) .then((event) => { this._trace(`${MESSAGE_TYPES.REFRESH} (callback)`, event); if (event.data) { resolve(true); } else { reject(false); } }) .catch((err) => { reject(false); }); } }); } public ping(): Promise<boolean> { return new Promise<any>((resolve, reject) => { if (this._handlers[AppBridgeHandler.PING]) { this._handlers[AppBridgeHandler.PING]({}, (data: any, error: any) => { resolve({ data, error }); }); } else { postRobot.sendToParent(MESSAGE_TYPES.PING, {}).then((event: any) => { resolve({ data: event.data.data, error: event.data.error }); }).catch((err) => { reject(null); }); } }); } /** * Fires or responds to a pin event */ public pin(packet?: object): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { if (this._handlers[AppBridgeHandler.PIN]) { this._handlers[AppBridgeHandler.PIN](packet, (success: boolean) => { if (success) { resolve(true); } else { reject(false); } }); } else { if (packet) { console.info('[AppBridge] - pin(packet) is deprecated! Please just use pin()!'); // tslint:disable-line } const realPacket = { id: this.id, windowName: this.windowName }; postRobot .sendToParent(MESSAGE_TYPES.PIN, realPacket) .then((event) => { this._trace(`${MESSAGE_TYPES.PIN} (callback)`, event); if (event.data) { resolve(true); } else { reject(false); } }) .catch((err) => { reject(false); }); } }); } /** * Fires or responds to a requestData event * @param packet any - packet of data to send with the requestData event */ public requestData(packet: { type: string }): Promise<any> { return new Promise<any>((resolve, reject) => { if (this._handlers[AppBridgeHandler.REQUEST_DATA]) { this._handlers[AppBridgeHandler.REQUEST_DATA](packet, (data: any) => { if (data) { resolve({ data }); } else { reject(false); } }); } else { Object.assign(packet, { id: this.id, windowName: this.windowName }); postRobot .sendToParent(MESSAGE_TYPES.REQUEST_DATA, packet) .then((event) => { this._trace(`${MESSAGE_TYPES.REQUEST_DATA} (callback)`, event); if (event.data) { resolve({ data: event.data.data }); } else { reject(false); } }) .catch((err) => { reject(false); }); } }); } /** * Fires a generic callback command * @param packet string - key: string, generic: boolean */ public callback(packet: { key: string; generic: boolean; options: object }): Promise<any> { return new Promise<any>((resolve, reject) => { if (this._handlers[AppBridgeHandler.CALLBACK]) { this._handlers[AppBridgeHandler.CALLBACK](packet, (success: boolean) => { if (success) { resolve(true); } else { reject(false); } }); } else { Object.assign(packet, { id: this.id, windowName: this.windowName }); postRobot .sendToParent(MESSAGE_TYPES.CALLBACK, packet) .then((event) => { this._trace(`${MESSAGE_TYPES.CALLBACK} (callback)`, event); if (event.data) { resolve(true); } else { reject(false); } }) .catch((err) => { reject(false); }); } }); } /** * Fires or responds to an register event * @param packet any - packet of data to send with the event */ public register(packet: Partial<{ title: string; url: string; color: AlleyLinkColors }> = {}): Promise<string> { return new Promise<string>((resolve, reject) => { if (this._handlers[AppBridgeHandler.REGISTER]) { this._handlers[AppBridgeHandler.REGISTER](packet, (windowName: string) => { if (windowName) { resolve(windowName); } else { resolve(null); } }); } else { Object.assign(packet, { id: this.id }); postRobot .sendToParent(MESSAGE_TYPES.REGISTER, packet) .then((event) => { this._trace(`${MESSAGE_TYPES.REGISTER} (callback)`, event); if (event.data) { this.windowName = event.data.windowName; resolve(event.data.windowName); } else { resolve(null); } }) .catch((err) => { this._trace(`${MESSAGE_TYPES.REGISTER} - FAILED - (no parent)`, err); reject(err); }); } }); } /** * Fires or responds to an HTTP_GET event * @param packet any - packet of data to send with the event */ public httpGET(relativeURL: string, timeout: number = 10000): Promise<any> { return new Promise<any>((resolve, reject) => { if (this._handlers[AppBridgeHandler.HTTP]) { this._handlers[AppBridgeHandler.HTTP]({ verb: HTTP_VERBS.GET, relativeURL }, (data: any, error: any) => { resolve({ data, error }); }); } else { postRobot .sendToParent(MESSAGE_TYPES.HTTP_GET, { relativeURL }, { timeout }) .then((event: any) => { resolve({ data: event.data.data, error: event.data.error }); }) .catch((err) => { reject(null); }); } }); } /** * Fires or responds to an HTTP_POST event * @param packet any - packet of data to send with the event */ public httpPOST(relativeURL: string, postData: any, timeout: number = 10000): Promise<any> { return new Promise<any>((resolve, reject) => { if (this._handlers[AppBridgeHandler.HTTP]) { this._handlers[AppBridgeHandler.HTTP]({ verb: HTTP_VERBS.POST, relativeURL, data: postData }, (data: any, error: any) => { resolve({ data, error }); }); } else { postRobot .sendToParent(MESSAGE_TYPES.HTTP_POST, { relativeURL, data: postData }, { timeout }) .then((event: any) => { resolve({ data: event.data.data, error: event.data.error }); }) .catch((err) => { reject(null); }); } }); } /** * Fires or responds to an HTTP_PUT event * @param packet any - packet of data to send with the event */ public httpPUT(relativeURL: string, putData: any, timeout: number = 10000): Promise<any> { return new Promise<any>((resolve, reject) => { if (this._handlers[AppBridgeHandler.HTTP]) { this._handlers[AppBridgeHandler.HTTP]({ verb: HTTP_VERBS.PUT, relativeURL, data: putData }, (data: any, error: any) => { resolve({ data, error }); }); } else { postRobot .sendToParent(MESSAGE_TYPES.HTTP_PUT, { relativeURL, data: putData }, { timeout }) .then((event: any) => { resolve({ data: event.data.data, error: event.data.error }); }) .catch((err) => { reject(null); }); } }); } /** * Fires or responds to an HTTP_DELETE event * @param packet any - packet of data to send with the event */ public httpDELETE(relativeURL: string, timeout: number = 10000): Promise<any> { return new Promise<any>((resolve, reject) => { if (this._handlers[AppBridgeHandler.HTTP]) { this._handlers[AppBridgeHandler.HTTP]({ verb: HTTP_VERBS.DELETE, relativeURL }, (data: any, error: any) => { resolve({ data, error }); }); } else { postRobot .sendToParent(MESSAGE_TYPES.HTTP_DELETE, { relativeURL }, { timeout }) .then((event: any) => { resolve({ data: event.data.data, error: event.data.error }); }) .catch((err) => { reject(null); }); } }); } /** * Fires a custom event to anywhere in the application * @param event string - event name to fire * @param data any - data to be sent along with the event */ public fireEvent(event: string, data: any): Promise<any> { return new Promise<any>((resolve, reject) => { postRobot .sendToParent(MESSAGE_TYPES.CUSTOM_EVENT, { event, data }) .then((e: any) => { resolve(e); }) .catch((err) => { reject(null); }); }); } /** * Fires a custom event to all registered frames * @param event string - event name to fire * @param data any - data to be sent along with the event */ public fireEventToChildren(event: string, data: any): void { if (this._registeredFrames.length > 0) { this._registeredFrames.forEach(frame => { postRobot.send(frame.source, MESSAGE_TYPES.CUSTOM_EVENT, { event: event, eventType: event, data, }); }); } } /** * Fires a custom event to specified frames * @param source Window - specific iframe contentWindow * @param event string - event name to fire * @param data any - data to be sent along with the event */ public fireEventToChild(source: Window | HTMLIFrameElement, event: string, data: any): void { if (source instanceof HTMLIFrameElement) { source = source.contentWindow; } postRobot.send(source, MESSAGE_TYPES.CUSTOM_EVENT, { event, data }); } /** * Adds an event listener to a custom event * @param event string - event name to listen to * @param callback function - callback to be fired when an event is caught */ public addEventListener(event: string, callback: Function): void { if (!this._eventListeners[event]) { this._eventListeners[event] = []; } this._eventListeners[event].push(callback); } } export class DevAppBridge extends AppBridge { private baseURL: string; constructor(traceName: string = 'DevAppBridge', private http: HttpClient) { super(traceName); const cookie = this.getCookie('UlEncodedIdentity'); if (cookie && cookie.length) { const identity = JSON.parse(decodeURIComponent(cookie)); const endpoints = identity.sessions.reduce((obj, session) => { obj[session.name] = session.value.endpoint; return obj; }, {}); this.baseURL = endpoints.rest; } } protected _setupHandlers(): void {} /** * Fires or responds to an HTTP_GET event * @param packet any - packet of data to send with the event */ public httpGET(relativeURL: string): Promise<any> { return this.http.get(`${this.baseURL}/${relativeURL}`, { withCredentials: true }).toPromise(); } /** * Fires or responds to an HTTP_POST event * @param packet any - packet of data to send with the event */ public httpPOST(relativeURL: string, postData: any): Promise<any> { return this.http.post(`${this.baseURL}/${relativeURL}`, postData, { withCredentials: true }).toPromise(); } /** * Fires or responds to an HTTP_PUT event * @param packet any - packet of data to send with the event */ public httpPUT(relativeURL: string, putData: any): Promise<any> { return this.http.put(`${this.baseURL}/${relativeURL}`, putData, { withCredentials: true }).toPromise(); } /** * Fires or responds to an HTTP_DELETE event * @param packet any - packet of data to send with the event */ public httpDELETE(relativeURL: string): Promise<any> { return this.http.delete(`${this.baseURL}/${relativeURL}`, { withCredentials: true }).toPromise(); } private getCookie(cname: string): any { if (document) { const name = `${cname}=`; const ca = document.cookie.split(';'); for (let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1); } if (c.indexOf(name) === 0) { return c.substring(name.length, c.length); } } } return false; } }
the_stack
import {ATTRIBUTE_TYPE, ScalarType, SimpleOperator} from '@typedorm/common'; import {nestedKeyAccessRegex} from '../../helpers/constants'; const lastCharSpaceMatcher = /\s$/; export enum MERGE_STRATEGY { AND = 'AND', OR = 'OR', } export abstract class BaseExpressionInput { expression: string; protected _names?: {[key: string]: any}; protected _values?: {[key: string]: any}; constructor() { this.expression = ''; } set names(value: any) { this._names = { ...this.names, ...value, }; } get names() { return this._names ?? {}; } set values(value: any) { this._values = { ...this.values, ...value, }; } get values() { return this._values ?? {}; } protected abstract getExpNameKey(key: string): string; protected abstract getExpValueKey(key: string): string; protected appendToExpression(segment: string) { if (!segment) { return; } if (this.expression.length === 0) { this.expression += segment; return; } if (!this.hasSpaceInLastChar(this.expression)) { this.expression += ' '; // append empty space if does not exist } this.expression += segment; } protected addExpressionName(name: string) { // when trying to access nested prop i.e profile.name, replace . with appropriate expression safe string const nestedKeys = name.split('.'); const topKey = nestedKeys.shift(); if (!topKey) { throw new Error('Expression attribute name can not be empty'); } const topLevelPropKey = this.innerAddExpressionName(topKey); return nestedKeys.reduce( (acc, keySeg) => { let {prefix} = acc; // make sure that prefix does not contain any nested value reference prefix = prefix.replace(nestedKeyAccessRegex, ''); const currentSegPropKey = this.innerAddExpressionName( `${prefix}_${keySeg}`, keySeg ); acc.prefix += `_${keySeg}`; acc.encoded += `.${currentSegPropKey}`; return acc; }, {prefix: topKey, encoded: topLevelPropKey} ).encoded; } private innerAddExpressionName(nameKey: string, nameValue?: string) { // match any nested list item reference, and update it to be valid expression // i.e key such as addresses[0] will be name #addresses with expression #addresses[0] let match = ''; nameKey = nameKey.replace(nestedKeyAccessRegex, substr => { match = substr; return ''; }); nameValue = nameValue?.replace(match, ''); const expressionPrefixedName = this.getExpNameKey(nameKey); if (this.names[expressionPrefixedName]) { throw new Error( `There is already an expression name with key ${expressionPrefixedName}.` ); } this.names = { ...this.names, [expressionPrefixedName]: nameValue ?? nameKey, }; return expressionPrefixedName + match; } protected addExpressionValue(name: string, value: any) { const expressionSafeName = name.replace(/\./g, '_'); return this.innerAddExpressionValue(expressionSafeName, value); } private innerAddExpressionValue(name: string, value: any) { // remove any nested list item reference, it will be handled by names matcher // i.e key such as addresses[0] name = name.replace(nestedKeyAccessRegex, ''); const expressionPrefixedValue = this.getExpValueKey(name); if (this.values[expressionPrefixedValue]) { throw new Error( `There is already an expression value with key ${expressionPrefixedValue}.` ); } this.values = { ...this.values, [expressionPrefixedValue]: value, }; return expressionPrefixedValue; } merge( condition: BaseExpressionInput, strategy: MERGE_STRATEGY = MERGE_STRATEGY.AND ): this { const {expression, names, values} = condition; // if merging condition does not have anything to merge return if (!expression) { return this; } // if base condition does not have any expression replace if (!this.expression) { this.expression += expression; this.names = names; this.values = values; return this; } if (strategy === MERGE_STRATEGY.OR) { this.or().appendToExpression(`(${expression})`); } else { this.and().appendToExpression(`(${expression})`); } Object.keys(names).forEach(nameKey => { if (this.names[nameKey]) { throw new Error( `Failed to merge expression attribute names, there are multiple attributes names with key "${nameKey}"` ); } }); Object.keys(values).forEach(valueKey => { if (this.names[valueKey]) { throw new Error( `Failed to merge expression attribute values, there are multiple attributes values with key "${valueKey}"` ); } }); this.names = {...this.names, ...names}; this.values = {...this.values, ...values}; return this; } mergeMany<T extends BaseExpressionInput>( inputs: T[], strategy: MERGE_STRATEGY ) { // check if base expression has any value if (this.expression) { this.expression = `(${this.expression})`; this.appendToExpression(strategy); } inputs.forEach((input, index) => { this.appendToExpression(`(${input.expression})`); if (index !== inputs.length - 1) { this.appendToExpression(strategy); } Object.keys(input.names).forEach(nameKey => { if (this.names[nameKey]) { throw new Error( `Failed to merge expression attribute names, there are multiple attributes names with key "${nameKey}"` ); } }); Object.keys(input.values).forEach(valueKey => { if (this.names[valueKey]) { throw new Error( `Failed to merge expression attribute values, there are multiple attributes values with key "${valueKey}"` ); } }); this.names = {...this.names, ...input.names}; this.values = {...this.values, ...input.values}; }); return this; } /** Use merge instead * @deprecated */ and(): this { this.expression = `(${this.expression})`; this.appendToExpression('AND'); return this; } not<T extends BaseExpressionInput>(condition?: T): this { if (condition) { this.expression = `NOT (${condition.expression})`; this.names = condition.names; this.values = condition.values; return this; } else { if (!this.expression) { return this; } this.expression = `NOT (${this.expression})`; return this; } } /** * Use merge instead * @deprecated */ or(): this { this.expression = `(${this.expression})`; this.appendToExpression('OR'); return this; } beginsWith(key: string, substring: ScalarType): this { const attrExpName = this.addExpressionName(key); const attrExpValue = this.addExpressionValue(key, substring); this.appendToExpression(`begins_with(${attrExpName}, ${attrExpValue})`); return this; } contains(key: string, value: ScalarType): this { const attrExpName = this.addExpressionName(key); const attrExpValue = this.addExpressionValue(key, value); this.appendToExpression(`contains(${attrExpName}, ${attrExpValue})`); return this; } attributeType(key: string, type: ATTRIBUTE_TYPE): this { const attrExpName = this.addExpressionName(key); const attrExpValue = this.addExpressionValue(key, type); this.appendToExpression(`attribute_type(${attrExpName}, ${attrExpValue})`); return this; } attributeExists(attr: string): this { const attrName = this.addExpressionName(attr); this.appendToExpression(`attribute_exists(${attrName})`); return this; } attributeNotExists(attr: string): this { const attrName = this.addExpressionName(attr); this.appendToExpression(`attribute_not_exists(${attrName})`); return this; } equals(key: string, value: ScalarType): this { return this.addBaseOperator('EQ', key, value); } lessThan(key: string, value: ScalarType): this { return this.addBaseOperator('LT', key, value); } lessThanAndEqualTo(key: string, value: ScalarType): this { return this.addBaseOperator('LE', key, value); } greaterThan(key: string, value: ScalarType): this { return this.addBaseOperator('GT', key, value); } greaterThanAndEqualTo(key: string, value: ScalarType): this { return this.addBaseOperator('GE', key, value); } notEquals(key: string, value: ScalarType): this { return this.addBaseOperator('NE', key, value); } between(key: string, value: [ScalarType, ScalarType]): this { if (value.length !== 2) { throw new Error( 'Incorrect query value for BETWEEN operator, it requires array containing two values.' ); } const [startIncluding, endIncluding] = value; const attrExpName = this.addExpressionName(key); const attrExpValueStart = this.addExpressionValue( `${key}_start`, startIncluding ); const attrExpValueEnd = this.addExpressionValue(`${key}_end`, endIncluding); this.appendToExpression( `${attrExpName} BETWEEN ${attrExpValueStart} AND ${attrExpValueEnd}` ); return this; } in(key: string, values: ScalarType[]): this { if (values.length < 1) { throw new Error( 'Incorrect value for IN operator, it requires array containing at lease one SCALAR type value.' ); } const attrExpName = this.addExpressionName(key); const attrExpValue = values.reduce((acc, value, index) => { const attrExpValueStart = this.addExpressionValue( `${key}_${index}`, value ); acc += attrExpValueStart; if (index !== values.length - 1) { // if not last index append separator followed by space acc += ', '; } return acc; }, ''); this.appendToExpression(`${attrExpName} IN (${attrExpValue})`); return this; } size(key: string): this { const attrExpName = this.getExpNameKey(key); this.expression = this.expression.replace( attrExpName, `size(${attrExpName})` ); return this; } protected addBaseOperator( operator: SimpleOperator, key: string, value: any ): this { const attrExpName = this.addExpressionName(key); const attrExpValue = this.addExpressionValue(key, value); this.appendToExpression( `${attrExpName} ${this.getSymbolForOperator(operator)} ${attrExpValue}` ); return this; } protected getSymbolForOperator(operator: SimpleOperator): string { const symbolMap = { EQ: '=', LE: '<=', LT: '<', GE: '>=', GT: '>', NE: '<>', }; return symbolMap[operator]; } private hasSpaceInLastChar(match: string) { return lastCharSpaceMatcher.test(match); } }
the_stack
import { OnInit } from '@angular/core'; import { Component, AfterViewInit } from '@angular/core'; import { ScriptLoaderService } from '../../../../_services/script-loader.service'; import { Ajax } from '../../../../shared/ajax/ajax.service'; declare let toastr: any; declare let $: any; declare let swal: any; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.scss'], }) export class ProductCompponent implements AfterViewInit, OnInit { formData: any = { name: '', labels: [], envs: [], }; bInAdd: Boolean = false; dataList: any[] = []; datatable: any = null; label: String = ''; envList: any[] = []; master: Boolean = false; constructor(private _script: ScriptLoaderService, private ajax: Ajax) { } ngOnInit(): void { } async initEnvList() { let result = await this.ajax.get('/xhr/env'); result = result.map(item => { item.checked = false; return item; }); this.envList = result; console.log(this.envList); } dataTableInit() { var options = { data: { type: 'remote', source: { read: { url: '/xhr/project', method: 'GET', params: {}, map: function(raw) { // sample data mapping var dataSet = raw; if (typeof raw.data !== 'undefined') { dataSet = raw.data; } return dataSet; }, }, }, pageSize: 10, saveState: { cookie: true, webstorage: true, }, serverPaging: false, serverFiltering: false, serverSorting: false, autoColumns: false, }, layout: { theme: 'default', class: 'm-datatable--brand', scroll: true, height: null, footer: false, header: true, smoothScroll: { scrollbarShown: true, }, spinner: { overlayColor: '#000000', opacity: 0, type: 'loader', state: 'brand', message: true, }, icons: { sort: { asc: 'la la-arrow-up', desc: 'la la-arrow-down' }, pagination: { next: 'la la-angle-right', prev: 'la la-angle-left', first: 'la la-angle-double-left', last: 'la la-angle-double-right', more: 'la la-ellipsis-h', }, rowDetail: { expand: 'fa fa-caret-down', collapse: 'fa fa-caret-right', }, }, }, sortable: true, pagination: true, search: { // enable trigger search by keyup enter onEnter: false, // input text for search input: $('#generalSearch'), // search delay in milliseconds delay: 200, }, rows: { callback: function() { }, // auto hide columns, if rows overflow. work on non locked columns autoHide: false, }, // columns definition columns: [ // { // field: 'id', // title: 'id', // width: 80, // textAlign: 'center', // overflow: 'visible', // template: '{{id}}', // }, { field: 'name', title: '项目名称', sortable: 'asc', filterable: false, width: 400, responsive: { visible: 'lg' }, template: '{{name}}', }, { field: 'envs', title: '部署环境', sortable: 'asc', filterable: false, width: 400, responsive: { visible: 'lg' }, template: function(row) { let envs = ''; envs = row.envs.reduce((total, item) => { return ( total + `<span class="m-badge m-badge--warning m-badge--wide" style="margin-right: 15px;"> ${item.name} </span>` ); }, envs); return envs; }, }, { field: 'labels', title: '配置版本', sortable: 'asc', filterable: false, width: 400, responsive: { visible: 'lg' }, template: function(row) { let envs = ''; envs = row.labels.reduce((total, item) => { return ( total + `<span class="m-badge m-badge--brand m-badge--wide" style="margin-right: 15px;"> ${item.name} </span>` ); }, envs); return envs; }, }, { field: 'envParams', title: '操作', sortable: false, width: 100, overflow: 'visible', template: `<div class="item-operate" data-info={{id}}> <a class="m-portlet__nav-link btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill modifyItem" title="View"> <i class="la la-edit"></i> </a> <a class="m-portlet__nav-link btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill deleteItem" title="View"> <i class="la la-trash"></i> </a></div>`, }, ], toolbar: { layout: ['pagination', 'info'], placement: ['bottom'], //'top', 'bottom' items: { pagination: { type: 'default', pages: { desktop: { layout: 'default', pagesNumber: 6, }, tablet: { layout: 'default', pagesNumber: 3, }, mobile: { layout: 'compact', }, }, navigation: { prev: true, next: true, first: true, last: true, }, pageSizeSelect: [10, 20, 30, 50, 100], }, info: true, }, }, translate: { records: { processing: '正在获取项目列表', noRecords: '当前还没有配置项目', }, toolbar: { pagination: { items: { default: { first: '首页', prev: '上一页', next: '下一页', last: '末页', more: '更多页', input: 'Page number', select: '请选择每页显示数量', }, info: '显示第 {{start}} - {{end}} 条记录,总共 {{total}} 条', }, }, }, }, }; let self = this; this.datatable = (<any>$('#m_datatable')).mDatatable(options); $('#m_datatable').on('click', '.deleteItem', event => { let id = $(event.target) .parents('.item-operate') .attr('data-info'); self.deleteEnv(id); }); $('#m_datatable').on('click', '.modifyItem', event => { let id = $(event.target) .parents('.item-operate') .attr('data-info'); self.editProduct(id); }); } ngAfterViewInit(): void { this.dataTableInit(); this.initFormValid(); } initFormValid() { /* * Translated default messages for the jQuery validation plugin. * Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語) */ $.extend($.validator.messages, { required: '这是必填字段', remote: '请修正此字段', email: '请输入有效的电子邮件地址', url: '请输入有效的网址', date: '请输入有效的日期', dateISO: '请输入有效的日期 (YYYY-MM-DD)', number: '请输入有效的数字', digits: '只能输入数字', creditcard: '请输入有效的信用卡号码', equalTo: '你的输入不相同', extension: '请输入有效的后缀', maxlength: $.validator.format('最多可以输入 {0} 个字符'), minlength: $.validator.format('最少要输入 {0} 个字符'), rangelength: $.validator.format( '请输入长度在 {0} 到 {1} 之间的字符串' ), range: $.validator.format('请输入范围在 {0} 到 {1} 之间的数值'), max: $.validator.format('请输入不大于 {0} 的数值'), min: $.validator.format('请输入不小于 {0} 的数值'), }); $('#id-product-form').validate({ // define validation rules rules: { productName: { required: true, }, productEnv: { required: true, }, }, //display error alert on form submit invalidHandler: function(event, validator) { console.log(event); }, submitHandler: form => { this.save(); }, }); } async save() { if (this.formData.type !== 'edit') { try { let params = { name: this.formData.name, labels: this.formData.labels, envs: this.envList .filter(item => { if (item.checked) { return true; } }) .map(item => { return { id: item.id, }; }), }; let result = await this.ajax.post('/xhr/project', params); toastr.success('新增项目成功!'); $('#m_modal_1').modal('hide'); this.datatable.reload(); } catch (e) { toastr.error('新增项目失败!'); } } else { try { let params = { id: this.formData.id, name: this.formData.name, labels: this.formData.labels, envs: this.envList .filter(item => { if (item.checked) { return true; } }) .map(item => { return { id: item.id, }; }), }; let result = await this.ajax.put('/xhr/project', params); toastr.success('更新项目成功!'); $('#m_modal_1').modal('hide'); this.datatable.reload(); } catch (e) { toastr.error('更新项目失败!'); } } } async createProduct() { this.formData = { name: '', labels: [ { name: 'master', }, ], type: 'add', }; this.initEnvList(); $('#m_modal_1').modal('show'); } async editProduct(id) { let allData = this.datatable.getColumn(id).originalDataSet; let result = allData.filter(item => { if (item.id == id) { return true; } else { return false; } }); let envIds = result[0].envs.map(item => { return item.id; }); this.formData = { id: id, name: result[0].name, type: 'edit', labels: result[0].labels, }; await this.initEnvList(); this.envList.map(item => { if (envIds.indexOf(item.id) >= 0) { item.checked = true; } return item; }); $('#m_modal_1').modal('show'); } async deleteEnv(id) { swal({ title: 'Are you sure?', text: '你确定删除这个项目吗?', type: 'warning', showCancelButton: !0, confirmButtonText: '确定', cancelButtonText: '取消', }).then(async e => { if (e.value) { let params = { id: id, }; try { let result = await this.ajax.delete('/xhr/project', params); toastr.success('删除项目成功!'); this.datatable.reload(); } catch (e) { toastr.error('删除项目失败!'); } } }); } addLabel() { this.bInAdd = true; this.label = ''; } async addLabel2Array() { try { let result = await this.ajax.post( '/xhr/project/label?' + `projectId=${this.formData.id}&labelName=${this.label}`, {} ); toastr.success('新增配置版本成功!'); this.formData.labels.push({ name: this.label, id: result.id, }); this.bInAdd = false; } catch (e) { toastr.error('新增配置版本失败!'); } } async remove(index) { try { let label = this.formData.labels.splice(index)[0]; let result = await this.ajax.delete( `/xhr/project/label?labelId=${label.id}`, {} ); toastr.success('删除配置版本成功!'); } catch (e) { toastr.error('删除配置版本失败!'); } } }
the_stack
import { exists } from "@hpcc-js/util"; import { max as d3Max, mean as d3Mean } from "d3-array"; import { IConnection, IOptions } from "../connection"; import { ESPConnection } from "../espConnection"; /* Response structures generated via: * http://192.168.3.22:8010/ws_machine/GetTargetClusterInfo?respjson_ * http://json2ts.com/ */ export namespace GetTargetClusterInfo { export interface TargetClusters { Item: string[]; } export interface Request { TargetClusters?: TargetClusters; AddProcessesToFilter?: string; ApplyProcessFilter?: boolean; GetProcessorInfo?: boolean; GetStorageInfo?: boolean; LocalFileSystemsOnly?: boolean; GetSoftwareInfo?: boolean; MemThreshold?: number; DiskThreshold?: number; CpuThreshold?: number; AutoRefresh?: number; MemThresholdType?: string; DiskThresholdType?: string; } export interface Exception { Code: string; Audience: string; Source: string; Message: string; } export interface Exceptions { Source: string; Exception: Exception[]; } export interface Columns { Item: string[]; } export interface Addresses { Item: string[]; } export interface RequestInfo { Addresses: Addresses; ClusterType: string; Cluster: string; OldIP: string; Path: string; AddProcessesToFilter: string; ApplyProcessFilter: boolean; GetProcessorInfo: boolean; GetStorageInfo: boolean; LocalFileSystemsOnly: boolean; GetSoftwareInfo: boolean; MemThreshold: number; DiskThreshold: number; CpuThreshold: number; AutoRefresh: number; MemThresholdType: string; DiskThresholdType: string; SecurityString: string; UserName: string; Password: string; EnableSNMP: boolean; } export interface ProcessorInfo { Type: string; Load: number; } export interface Processors { ProcessorInfo: ProcessorInfo[]; } export interface StorageInfo { Description: string; Type: string; Available: number; PercentAvail: number; Total: number; Failures: number; } export interface Storage { StorageInfo: StorageInfo[]; } export interface SWRunInfo { Name: string; Instances: number; State: number; } export interface Running { SWRunInfo: SWRunInfo[]; } export interface PhysicalMemory { Description: string; Type: string; Available: number; PercentAvail: number; Total: number; Failures: number; } export interface VirtualMemory { Description: string; Type: string; Available: number; PercentAvail: number; Total: number; Failures: number; } export interface ComponentInfo { Condition: number; State: number; UpTime: string; } export interface MachineInfoEx { Address: string; ConfigAddress: string; Name: string; ProcessType: string; DisplayType: string; Description: string; AgentVersion: string; Contact: string; Location: string; UpTime: string; ComponentName: string; ComponentPath: string; RoxieState: string; RoxieStateDetails: string; OS: number; ProcessNumber: number; Processors: Processors; Storage: Storage; Running: Running; PhysicalMemory: PhysicalMemory; VirtualMemory: VirtualMemory; ComponentInfo: ComponentInfo; } export interface Processes { MachineInfoEx: MachineInfoEx[]; } export interface TargetClusterInfo { Name: string; Type: string; Processes: Processes; } export interface TargetClusterInfoList { TargetClusterInfo: TargetClusterInfo[]; } export interface Response { Exceptions: Exceptions; Columns: Columns; RequestInfo: RequestInfo; TargetClusterInfoList: TargetClusterInfoList; TimeStamp: string; AcceptLanguage: string; } } export namespace GetTargetClusterUsage { export interface TargetClusters { Item: string[]; } export interface Request { TargetClusters?: TargetClusters; BypassCachedResult: boolean; } export interface Exception { Code: string; Audience: string; Source: string; Message: string; } export interface Exceptions { Source: string; Exception: Exception[]; } export interface DiskUsage { Name: string; Path: string; Description: string; InUse: number; Available: number; PercentAvailable: number; } export interface DiskUsages { DiskUsage: DiskUsage[]; } export interface MachineUsage { Name: string; NetAddress: string; Description: string; DiskUsages: DiskUsages; } export interface MachineUsages { MachineUsage: MachineUsage[]; } export interface ComponentUsage { Type: string; Name: string; Description: string; MachineUsages: MachineUsages; } export interface ComponentUsages { ComponentUsage: ComponentUsage[]; } export interface TargetClusterUsage { Name: string; Description: string; ComponentUsages: ComponentUsages; } export interface TargetClusterUsages { TargetClusterUsage: TargetClusterUsage[]; } export interface Response { Exceptions: Exceptions; TargetClusterUsages: TargetClusterUsages; } } export namespace GetTargetClusterUsageEx { export interface DiskUsage { Name: string; Path: string; Description: string; InUse: number; Available: number; Total: number; PercentAvailable: number; PercentUsed: number; } export interface MachineUsage { Name: string; NetAddress: string; Description: string; DiskUsages: DiskUsage[]; mean: number; max: number; } export interface ComponentUsage { Type: string; Name: string; Description: string; MachineUsages: MachineUsage[]; MachineUsagesDescription: string; mean: number; max: number; } export interface TargetClusterUsage { Name: string; Description: string; ComponentUsages: ComponentUsage[]; ComponentUsagesDescription: string; mean: number; max: number; } } export class MachineService { private _connection: ESPConnection; constructor(optsConnection: IOptions | IConnection) { this._connection = new ESPConnection(optsConnection, "ws_machine", "1.13"); } GetTargetClusterInfo(request: GetTargetClusterInfo.Request = {}): Promise<GetTargetClusterInfo.Response> { return this._connection.send("GetTargetClusterInfo", request); } GetTargetClusterUsage(targetClusters?: string[], bypassCachedResult: boolean = false): Promise<GetTargetClusterUsage.TargetClusterUsage[]> { return this._connection.send("GetTargetClusterUsage", { TargetClusters: targetClusters ? { Item: targetClusters } : {}, BypassCachedResult: bypassCachedResult }).then(response => { return exists("TargetClusterUsages.TargetClusterUsage", response) ? response.TargetClusterUsages.TargetClusterUsage : []; }); } GetTargetClusterUsageEx(targetClusters?: string[], bypassCachedResult: boolean = false): Promise<GetTargetClusterUsageEx.TargetClusterUsage[]> { return this.GetTargetClusterUsage(targetClusters, bypassCachedResult).then(response => { return response.filter(tcu => !!tcu.ComponentUsages).map(tcu => { const ComponentUsages: GetTargetClusterUsageEx.ComponentUsage[] = tcu.ComponentUsages.ComponentUsage.map(cu => { const MachineUsages = (cu.MachineUsages && cu.MachineUsages.MachineUsage ? cu.MachineUsages.MachineUsage : []).map(mu => { const DiskUsages: GetTargetClusterUsageEx.DiskUsage[] = mu.DiskUsages && mu.DiskUsages.DiskUsage ? mu.DiskUsages.DiskUsage.map(du => { return { ...du, Total: du.InUse + du.Available, PercentUsed: 100 - du.PercentAvailable }; }) : []; return { Name: mu.Name, NetAddress: mu.NetAddress, Description: mu.Description, DiskUsages, mean: d3Mean(DiskUsages.filter(du => !isNaN(du.PercentUsed)), du => du.PercentUsed), max: d3Max(DiskUsages.filter(du => !isNaN(du.PercentUsed)), du => du.PercentUsed) }; }); return { Type: cu.Type, Name: cu.Name, Description: cu.Description, MachineUsages, MachineUsagesDescription: MachineUsages.reduce((prev, mu) => prev + (mu.Description || ""), ""), mean: d3Mean(MachineUsages.filter(mu => !isNaN(mu.mean)), mu => mu.mean), max: d3Max(MachineUsages.filter(mu => !isNaN(mu.max)), mu => mu.max) }; }); return { Name: tcu.Name, Description: tcu.Description, ComponentUsages, ComponentUsagesDescription: ComponentUsages.reduce((prev, cu) => prev + (cu.MachineUsagesDescription || ""), ""), mean: d3Mean(ComponentUsages.filter(cu => !isNaN(cu.mean)), cu => cu.mean), max: d3Max(ComponentUsages.filter(cu => !isNaN(cu.max)), cu => cu.max) }; }); }); } }
the_stack
import React, {ForwardedRef, forwardRef, RefObject, useEffect, useImperativeHandle, useRef, useState} from 'react'; import {HEADER_HEIGHT, ROW_HEIGHT} from '../constants'; import {useGridEventBus} from '../grid-event-bus'; import {GridEventTypes} from '../grid-event-bus-types'; import {ColumnDefs, DataSetState, SelectionRef, TableSelection} from '../types'; import {ColumnSelection, RowSelection} from './widgets'; const computeRowSelectionPosition = (options: { rowIndex: number; scrollTop: number; clientHeight: number }) => { const {rowIndex} = options; if (rowIndex === -1) { return {rowTop: 0, rowHeight: 0}; } const {scrollTop, clientHeight} = options; const top = 32 - 1; let rowTop = rowIndex === -1 ? 0 : top + 24 * rowIndex - scrollTop; let rowHeight = ROW_HEIGHT; if (rowTop + rowHeight <= top || rowTop > clientHeight) { return {rowTop: 0, rowHeight: 0}; } if (rowTop < top) { rowHeight -= top - rowTop; rowHeight = Math.max(0, rowHeight); rowTop = top; } if (rowTop + rowHeight > clientHeight) { rowHeight = clientHeight - rowTop; } return {rowTop, rowHeight}; }; const computeColumnSelectionPosition = (options: { inFixTable: boolean; columnIndex: number; scrollLeft: number; dataTableClientWidth: number; verticalScroll: boolean; data: DataSetState; columnDefs: ColumnDefs; rowNoColumnWidth: number; }) => { const {columnIndex} = options; if (columnIndex === -1) { return {columnLeft: 0, columnWidth: 0, columnHeight: 0}; } const { inFixTable, scrollLeft, dataTableClientWidth, verticalScroll, data, columnDefs, rowNoColumnWidth } = options; const selectColumnDef = inFixTable ? columnDefs.fixed[columnIndex] : columnDefs.data[columnIndex]; const selectColumnWidth = selectColumnDef?.width || 0; // compute left in my table, total width of previous columns const selectColumnLeft = (inFixTable ? columnDefs.fixed : columnDefs.data).reduce((left, columnDef, index) => { if (index < columnIndex) { left += columnDef.width; } return left; }, 0); let columnWidth = selectColumnWidth; let columnLeft; const fixTableWidth = columnDefs.fixed.reduce((left, column) => left + column.width, rowNoColumnWidth); const totalWidth = fixTableWidth + dataTableClientWidth; if (inFixTable) { columnLeft = selectColumnLeft + rowNoColumnWidth; } else { columnLeft = fixTableWidth + selectColumnLeft - scrollLeft; if (columnLeft + columnWidth <= fixTableWidth || columnLeft >= totalWidth) { // column is hide in fix table // or column is beyond total width return {columnLeft: 0, columnWidth: 0, columnHeight: 0}; } if (columnLeft < fixTableWidth) { columnWidth -= fixTableWidth - columnLeft; columnWidth = Math.max(0, columnWidth); columnLeft = fixTableWidth; } } if (columnWidth + columnLeft > totalWidth) { columnWidth = totalWidth - columnLeft; } return { columnLeft, columnWidth, columnHeight: verticalScroll ? 0 : data.data.length * ROW_HEIGHT + HEADER_HEIGHT }; }; const buildDefaultSelection = () => ({ row: -1, rowTop: 0, rowHeight: 0, column: -1, columnLeft: 0, columnWidth: 0, columnHeight: 0, inFixTable: false, verticalScroll: 0, horizontalScroll: 0 }); const useSelection = (options: { data: DataSetState; columnDefs: ColumnDefs; dataTableRef: RefObject<HTMLDivElement>; rowNoColumnWidth: number; rowSelectionRef: RefObject<HTMLDivElement>; columnSelectionRef: RefObject<HTMLDivElement>; }) => { const { data, columnDefs, rowNoColumnWidth, dataTableRef, rowSelectionRef, columnSelectionRef } = options; const {on, off} = useGridEventBus(); const [selection, setSelection] = useState<TableSelection>(buildDefaultSelection()); const select = (inFixTable: boolean, rowIndex: number, columnIndex: number) => { if (!dataTableRef.current) { return; } const dataTable = dataTableRef.current; const {offsetWidth, offsetHeight, clientWidth, clientHeight, scrollTop, scrollLeft} = dataTable; const scroll = { verticalScroll: offsetWidth - clientWidth, horizontalScroll: offsetHeight - clientHeight }; const rowPos = computeRowSelectionPosition({rowIndex, scrollTop, clientHeight}); const colPos = computeColumnSelectionPosition({ inFixTable, columnIndex, scrollLeft, dataTableClientWidth: clientWidth, verticalScroll: offsetWidth !== clientWidth, data, columnDefs, rowNoColumnWidth }); setSelection({ row: rowIndex, ...rowPos, column: columnIndex, ...colPos, inFixTable, ...scroll }); }; useEffect(() => { // compute and set new positions of row and column selection here. // in case of handle scroll, transition is not needed; in the meantime, refresh by state change is not as fast as hoped. // therefore, use plain javascript to clear transition css and set positions. // and synchronize selection state after a short time (setTimeout on several milliseconds), and remove the transition clearing. // selection state synchronization is required, otherwise cannot response click cell/row header/column header correctly. const repaintSelection = () => { if (!dataTableRef.current) { return; } const dataTable = dataTableRef.current; let { inFixTable, row: rowIndex, column: columnIndex, rowTop, rowHeight, columnLeft, columnWidth } = selection; if (rowIndex !== -1 && rowSelectionRef.current) { const {scrollTop, clientHeight} = dataTable; const {rowTop: top, rowHeight: height} = computeRowSelectionPosition({ rowIndex, scrollTop, clientHeight }); const bar = rowSelectionRef.current; bar.style.transition = 'none'; bar.style.top = `${top}px`; bar.style.height = `${height}px`; rowTop = top; rowHeight = height; } if (columnIndex !== -1 && columnSelectionRef.current) { const {scrollLeft, clientWidth: dataTableClientWidth, offsetHeight, clientHeight} = dataTable; const {columnLeft: left, columnWidth: width} = computeColumnSelectionPosition({ inFixTable, columnIndex, scrollLeft, dataTableClientWidth, verticalScroll: offsetHeight !== clientHeight, data, columnDefs, rowNoColumnWidth }); const bar = columnSelectionRef.current; bar.style.transition = 'none'; bar.style.left = `${left}px`; bar.style.width = `${width}px`; columnLeft = left; columnWidth = width; } if (rowIndex !== -1 || columnIndex !== -1) { setTimeout(() => { setSelection(selection => { return {...selection, rowTop, rowHeight, columnLeft, columnWidth}; }); rowSelectionRef.current && (rowSelectionRef.current.style.transition = ''); columnSelectionRef.current && (columnSelectionRef.current.style.transition = ''); }, 5); } }; const dataTable = dataTableRef.current; // @ts-ignore dataTable?.addEventListener('scroll', repaintSelection); on(GridEventTypes.REPAINT_SELECTION, repaintSelection); return () => { // @ts-ignore dataTable?.removeEventListener('scroll', repaintSelection); off(GridEventTypes.REPAINT_SELECTION, repaintSelection); }; // do not use dependencies here }); return {selection, select}; }; export const GridSelection = forwardRef((props: { data: DataSetState; columnDefs: ColumnDefs; dataTableRef: RefObject<HTMLDivElement>; rowNoColumnWidth: number; }, ref: ForwardedRef<SelectionRef>) => { const { data, columnDefs, dataTableRef, rowNoColumnWidth } = props; const {on, off} = useGridEventBus(); const rowSelectionRef = useRef<HTMLDivElement>(null); const columnSelectionRef = useRef<HTMLDivElement>(null); const {selection, select} = useSelection({ data, columnDefs, rowNoColumnWidth, dataTableRef, rowSelectionRef, columnSelectionRef }); useImperativeHandle(ref, () => ({selection: () => selection})); useEffect(() => { const onFixColumnChange = (fix: boolean, columnCount: number) => { const {column: selectionColumnIndex, inFixTable} = selection; if (selectionColumnIndex === -1) { // no selection column return; } if (inFixTable) { // current selection column in fix table if (fix) { // append columns to fix table, do nothing return; } else { // move columns from fix table to data table if (selectionColumnIndex < columnDefs.fixed.length) { // selection column still in fix table, do nothing return; } else { // selection column move to data table select(false, selection.row, selectionColumnIndex - columnDefs.fixed.length); } } } else { // current selection column in data table if (fix) { // move columns from data table to fix table if (selectionColumnIndex >= columnCount) { // selection column remains in data table select(false, selection.row, selectionColumnIndex - columnCount); } else { // selection column moves to fix table // index starts from original fix columns count select(true, selection.row, columnDefs.fixed.length - columnCount + selectionColumnIndex); } } else { // move columns from fix table to data table // index always be increased, because of columns prepended select(false, selection.row, selectionColumnIndex + columnCount); } } }; on(GridEventTypes.SELECTION_CHANGED, select); on(GridEventTypes.FIX_COLUMN_CHANGED, onFixColumnChange); return () => { off(GridEventTypes.SELECTION_CHANGED, select); off(GridEventTypes.FIX_COLUMN_CHANGED, onFixColumnChange); }; // do not use dependencies here }); return <> <RowSelection index={selection.row} top={selection.rowTop} height={selection.rowHeight} scroll={selection.verticalScroll} ref={rowSelectionRef}/> <ColumnSelection index={selection.column} left={selection.columnLeft} width={selection.columnWidth} height={selection.columnHeight} scroll={selection.horizontalScroll} ref={columnSelectionRef}/> </>; });
the_stack
import { NumberArray } from '../types' import { v3new, v3cross } from './vector-utils' export class Matrix { size: number data: Float32Array constructor (readonly cols: number, readonly rows: number) { this.size = this.cols * this.rows this.data = new Float32Array(this.size) } copyTo (matrix: Matrix) { matrix.data.set(this.data) } } export function transpose (At: Matrix, A: Matrix) { let i = 0 let j = 0 const nrows = A.rows const ncols = A.cols let Ai = 0 let Ati = 0 let pAt = 0 const ad = A.data const atd = At.data for (; i < nrows; Ati += 1, Ai += ncols, i++) { pAt = Ati for (j = 0; j < ncols; pAt += nrows, j++) atd[pAt] = ad[Ai + j] } } // C = A * B export function multiply (C: Matrix, A: Matrix, B: Matrix) { let i = 0 let j = 0 let k = 0 let Ap = 0 let pA = 0 let pB = 0 let _pB = 0 let Cp = 0 const ncols = A.cols const nrows = A.rows const mcols = B.cols const ad = A.data const bd = B.data const cd = C.data let sum = 0.0 for (; i < nrows; Ap += ncols, i++) { for (_pB = 0, j = 0; j < mcols; Cp++, _pB++, j++) { pB = _pB pA = Ap sum = 0.0 for (k = 0; k < ncols; pA++, pB += mcols, k++) { sum += ad[pA] * bd[pB] } cd[Cp] = sum } } } // C = A * B' export function multiplyABt (C: Matrix, A: Matrix, B: Matrix) { let i = 0 let j = 0 let k = 0 let Ap = 0 let pA = 0 let pB = 0 let Cp = 0 const ncols = A.cols const nrows = A.rows const mrows = B.rows const ad = A.data const bd = B.data const cd = C.data let sum = 0.0 for (; i < nrows; Ap += ncols, i++) { for (pB = 0, j = 0; j < mrows; Cp++, j++) { pA = Ap sum = 0.0 for (k = 0; k < ncols; pA++, pB++, k++) { sum += ad[pA] * bd[pB] } cd[Cp] = sum } } } // C = A' * B export function multiplyAtB (C: Matrix, A: Matrix, B: Matrix) { let i = 0 let j = 0 let k = 0 let Ap = 0 let pA = 0 let pB = 0 let _pB = 0 let Cp = 0 const ncols = A.cols const nrows = A.rows const mcols = B.cols const ad = A.data const bd = B.data const cd = C.data let sum = 0.0 for (; i < ncols; Ap++, i++) { for (_pB = 0, j = 0; j < mcols; Cp++, _pB++, j++) { pB = _pB pA = Ap sum = 0.0 for (k = 0; k < nrows; pA += ncols, pB += mcols, k++) { sum += ad[pA] * bd[pB] } cd[Cp] = sum } } } export function invert3x3 (from: Matrix, to: Matrix) { const A = from.data const invA = to.data const t1 = A[4] const t2 = A[8] const t4 = A[5] const t5 = A[7] const t8 = A[0] const t9 = t8 * t1 const t11 = t8 * t4 const t13 = A[3] const t14 = A[1] const t15 = t13 * t14 const t17 = A[2] const t18 = t13 * t17 const t20 = A[6] const t21 = t20 * t14 const t23 = t20 * t17 const t26 = 1.0 / (t9 * t2 - t11 * t5 - t15 * t2 + t18 * t5 + t21 * t4 - t23 * t1) invA[0] = (t1 * t2 - t4 * t5) * t26 invA[1] = -(t14 * t2 - t17 * t5) * t26 invA[2] = -(-t14 * t4 + t17 * t1) * t26 invA[3] = -(t13 * t2 - t4 * t20) * t26 invA[4] = (t8 * t2 - t23) * t26 invA[5] = -(t11 - t18) * t26 invA[6] = -(-t13 * t5 + t1 * t20) * t26 invA[7] = -(t8 * t5 - t21) * t26 invA[8] = (t9 - t15) * t26 } export function mat3x3determinant (M: Matrix) { const md = M.data return md[0] * md[4] * md[8] - md[0] * md[5] * md[7] - md[3] * md[1] * md[8] + md[3] * md[2] * md[7] + md[6] * md[1] * md[5] - md[6] * md[2] * md[4] } // C = A * B export function multiply3x3 (C: Matrix, A: Matrix, B: Matrix) { const Cd = C.data const Ad = A.data const Bd = B.data const m10 = Ad[0] const m11 = Ad[1] const m12 = Ad[2] const m13 = Ad[3] const m14 = Ad[4] const m15 = Ad[5] const m16 = Ad[6] const m17 = Ad[7] const m18 = Ad[8] const m20 = Bd[0] const m21 = Bd[1] const m22 = Bd[2] const m23 = Bd[3] const m24 = Bd[4] const m25 = Bd[5] const m26 = Bd[6] const m27 = Bd[7] const m28 = Bd[8] Cd[0] = m10 * m20 + m11 * m23 + m12 * m26 Cd[1] = m10 * m21 + m11 * m24 + m12 * m27 Cd[2] = m10 * m22 + m11 * m25 + m12 * m28 Cd[3] = m13 * m20 + m14 * m23 + m15 * m26 Cd[4] = m13 * m21 + m14 * m24 + m15 * m27 Cd[5] = m13 * m22 + m14 * m25 + m15 * m28 Cd[6] = m16 * m20 + m17 * m23 + m18 * m26 Cd[7] = m16 * m21 + m17 * m24 + m18 * m27 Cd[8] = m16 * m22 + m17 * m25 + m18 * m28 } export function meanRows (A: Matrix) { const nrows = A.rows const ncols = A.cols const Ad = A.data const mean = new Array(ncols) for (let j = 0; j < ncols; ++j) { mean[ j ] = 0.0 } for (let i = 0, p = 0; i < nrows; ++i) { for (let j = 0; j < ncols; ++j, ++p) { mean[ j ] += Ad[ p ] } } for (let j = 0; j < ncols; ++j) { mean[ j ] /= nrows } return mean } export function meanCols (A: Matrix) { const nrows = A.rows const ncols = A.cols const Ad = A.data const mean = new Array(nrows) for (let j = 0; j < nrows; ++j) { mean[ j ] = 0.0 } for (let i = 0, p = 0; i < ncols; ++i) { for (let j = 0; j < nrows; ++j, ++p) { mean[ j ] += Ad[ p ] } } for (let j = 0; j < nrows; ++j) { mean[ j ] /= ncols } return mean } export function subRows (A: Matrix, row: number[]) { const nrows = A.rows const ncols = A.cols const Ad = A.data for (let i = 0, p = 0; i < nrows; ++i) { for (let j = 0; j < ncols; ++j, ++p) { Ad[ p ] -= row[ j ] } } } export function subCols (A: Matrix, col: number[]) { const nrows = A.rows const ncols = A.cols const Ad = A.data for (let i = 0, p = 0; i < ncols; ++i) { for (let j = 0; j < nrows; ++j, ++p) { Ad[ p ] -= col[ j ] } } } export function addRows (A: Matrix, row: number[]) { const nrows = A.rows const ncols = A.cols const Ad = A.data for (let i = 0, p = 0; i < nrows; ++i) { for (let j = 0; j < ncols; ++j, ++p) { Ad[ p ] += row[ j ] } } } export function addCols (A: Matrix, col: number[]) { const nrows = A.rows const ncols = A.cols const Ad = A.data for (let i = 0, p = 0; i < ncols; ++i) { for (let j = 0; j < nrows; ++j, ++p) { Ad[ p ] += col[ j ] } } } export function swap (A: NumberArray, i0: number, i1: number, t: number) { t = A[i0] A[i0] = A[i1] A[i1] = t } export function hypot (a: number, b: number) { a = Math.abs(a) b = Math.abs(b) if (a > b) { b /= a return a * Math.sqrt(1.0 + b * b) } if (b > 0) { a /= b return b * Math.sqrt(1.0 + a * a) } return 0.0 } const EPSILON = 0.0000001192092896 const FLT_MIN = 1E-37 export function JacobiSVDImpl (At: NumberArray, astep: number, _W: NumberArray, Vt: NumberArray, vstep: number, m: number, n: number, n1: number) { const eps = EPSILON * 2.0 const minval = FLT_MIN let i = 0 let j = 0 let k = 0 let iter = 0 const maxIter = Math.max(m, 30) let Ai = 0 let Aj = 0 let Vi = 0 let Vj = 0 let changed = 0 let c = 0.0 let s = 0.0 let t = 0.0 let t0 = 0.0 let t1 = 0.0 let sd = 0.0 let beta = 0.0 let gamma = 0.0 let delta = 0.0 let a = 0.0 let p = 0.0 let b = 0.0 let seed = 0x1234 let val = 0.0 let val0 = 0.0 let asum = 0.0 const W = new Float64Array(n << 3) for (; i < n; i++) { for (k = 0, sd = 0; k < m; k++) { t = At[i * astep + k] sd += t * t } W[i] = sd if (Vt) { for (k = 0; k < n; k++) { Vt[i * vstep + k] = 0 } Vt[i * vstep + i] = 1 } } for (; iter < maxIter; iter++) { changed = 0 for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { Ai = (i * astep) | 0 Aj = (j * astep) | 0 a = W[i] p = 0 b = W[j] k = 2 p += At[Ai] * At[Aj] p += At[Ai + 1] * At[Aj + 1] for (; k < m; k++) { p += At[Ai + k] * At[Aj + k] } if (Math.abs(p) <= eps * Math.sqrt(a * b)) continue p *= 2.0 beta = a - b gamma = hypot(p, beta) if (beta < 0) { delta = (gamma - beta) * 0.5 s = Math.sqrt(delta / gamma) c = (p / (gamma * s * 2.0)) } else { c = Math.sqrt((gamma + beta) / (gamma * 2.0)) s = (p / (gamma * c * 2.0)) } a = 0.0 b = 0.0 k = 2 // unroll t0 = c * At[Ai] + s * At[Aj] t1 = -s * At[Ai] + c * At[Aj] At[Ai] = t0; At[Aj] = t1 a += t0 * t0; b += t1 * t1 t0 = c * At[Ai + 1] + s * At[Aj + 1] t1 = -s * At[Ai + 1] + c * At[Aj + 1] At[Ai + 1] = t0; At[Aj + 1] = t1 a += t0 * t0; b += t1 * t1 for (; k < m; k++) { t0 = c * At[Ai + k] + s * At[Aj + k] t1 = -s * At[Ai + k] + c * At[Aj + k] At[Ai + k] = t0; At[Aj + k] = t1 a += t0 * t0; b += t1 * t1 } W[i] = a W[j] = b changed = 1 if (Vt) { Vi = (i * vstep) | 0 Vj = (j * vstep) | 0 k = 2 t0 = c * Vt[Vi] + s * Vt[Vj] t1 = -s * Vt[Vi] + c * Vt[Vj] Vt[Vi] = t0; Vt[Vj] = t1 t0 = c * Vt[Vi + 1] + s * Vt[Vj + 1] t1 = -s * Vt[Vi + 1] + c * Vt[Vj + 1] Vt[Vi + 1] = t0; Vt[Vj + 1] = t1 for (; k < n; k++) { t0 = c * Vt[Vi + k] + s * Vt[Vj + k] t1 = -s * Vt[Vi + k] + c * Vt[Vj + k] Vt[Vi + k] = t0; Vt[Vj + k] = t1 } } } } if (changed === 0) break } for (i = 0; i < n; i++) { for (k = 0, sd = 0; k < m; k++) { t = At[i * astep + k] sd += t * t } W[i] = Math.sqrt(sd) } for (i = 0; i < n - 1; i++) { j = i for (k = i + 1; k < n; k++) { if (W[j] < W[k]) { j = k } } if (i !== j) { swap(W, i, j, sd) if (Vt) { for (k = 0; k < m; k++) { swap(At, i * astep + k, j * astep + k, t) } for (k = 0; k < n; k++) { swap(Vt, i * vstep + k, j * vstep + k, t) } } } } for (i = 0; i < n; i++) { _W[i] = W[i] } if (!Vt) { return } for (i = 0; i < n1; i++) { sd = i < n ? W[i] : 0 while (sd <= minval) { // if we got a zero singular value, then in order to get the corresponding left singular vector // we generate a random vector, project it to the previously computed left singular vectors, // subtract the projection and normalize the difference. val0 = (1.0 / m) for (k = 0; k < m; k++) { seed = (seed * 214013 + 2531011) val = (((seed >> 16) & 0x7fff) & 256) !== 0 ? val0 : -val0 At[i * astep + k] = val } for (iter = 0; iter < 2; iter++) { for (j = 0; j < i; j++) { sd = 0 for (k = 0; k < m; k++) { sd += At[i * astep + k] * At[j * astep + k] } asum = 0.0 for (k = 0; k < m; k++) { t = (At[i * astep + k] - sd * At[j * astep + k]) At[i * astep + k] = t asum += Math.abs(t) } asum = asum ? 1.0 / asum : 0 for (k = 0; k < m; k++) { At[i * astep + k] *= asum } } } sd = 0 for (k = 0; k < m; k++) { t = At[i * astep + k] sd += t * t } sd = Math.sqrt(sd) } s = (1.0 / sd) for (k = 0; k < m; k++) { At[i * astep + k] *= s } } } export function svd (A: Matrix, W: Matrix, U: Matrix, V: Matrix) { let at = 0 let i = 0 const _m = A.rows const _n = A.cols let m = _m let n = _n if (m < n) { at = 1 i = m m = n n = i } const amt = new Matrix(m, m) const wmt = new Matrix(1, n) const vmt = new Matrix(n, n) if (at === 0) { transpose(amt, A) } else { for (i = 0; i < _n * _m; i++) { amt.data[i] = A.data[i] } for (; i < n * m; i++) { amt.data[i] = 0 } } JacobiSVDImpl(amt.data, m, wmt.data, vmt.data, n, m, n, m) if (W) { for (i = 0; i < n; i++) { W.data[i] = wmt.data[i] } for (; i < _n; i++) { W.data[i] = 0 } } if (at === 0) { if (U) transpose(U, amt) if (V) transpose(V, vmt) } else { if (U) transpose(U, vmt) if (V) transpose(V, amt) } } // export function m4new () { return new Float32Array([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]) } export function m4set (out: Float32Array, n11: number, n12: number, n13: number, n14: number, n21: number, n22: number, n23: number, n24: number, n31: number, n32: number, n33: number, n34: number, n41: number, n42: number, n43: number, n44: number) { out[ 0 ] = n11; out[ 4 ] = n12; out[ 8 ] = n13; out[ 12 ] = n14 out[ 1 ] = n21; out[ 5 ] = n22; out[ 9 ] = n23; out[ 13 ] = n24 out[ 2 ] = n31; out[ 6 ] = n32; out[ 10 ] = n33; out[ 14 ] = n34 out[ 3 ] = n41; out[ 7 ] = n42; out[ 11 ] = n43; out[ 15 ] = n44 } export function m4identity (out: Float32Array) { m4set(out, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ) } (m4identity as any).__deps = [ m4set ] export function m4multiply (out: Float32Array, a: Float32Array, b: Float32Array) { const a11 = a[ 0 ] const a12 = a[ 4 ] const a13 = a[ 8 ] const a14 = a[ 12 ] const a21 = a[ 1 ] const a22 = a[ 5 ] const a23 = a[ 9 ] const a24 = a[ 13 ] const a31 = a[ 2 ] const a32 = a[ 6 ] const a33 = a[ 10 ] const a34 = a[ 14 ] const a41 = a[ 3 ] const a42 = a[ 7 ] const a43 = a[ 11 ] const a44 = a[ 15 ] const b11 = b[ 0 ] const b12 = b[ 4 ] const b13 = b[ 8 ] const b14 = b[ 12 ] const b21 = b[ 1 ] const b22 = b[ 5 ] const b23 = b[ 9 ] const b24 = b[ 13 ] const b31 = b[ 2 ] const b32 = b[ 6 ] const b33 = b[ 10 ] const b34 = b[ 14 ] const b41 = b[ 3 ] const b42 = b[ 7 ] const b43 = b[ 11 ] const b44 = b[ 15 ] out[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41 out[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42 out[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43 out[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44 out[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41 out[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42 out[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43 out[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44 out[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41 out[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42 out[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43 out[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44 out[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41 out[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42 out[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43 out[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44 } export function m4makeScale (out: Float32Array, x: number, y: number, z: number) { m4set(out, x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 ) } (m4makeScale as any).__deps = [ m4set ] export function m4makeTranslation (out: Float32Array, x: number, y: number, z: number) { m4set(out, 1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1 ) } (m4makeTranslation as any).__deps = [ m4set ] export function m4makeRotationY (out: Float32Array, theta: number) { const c = Math.cos(theta) const s = Math.sin(theta) m4set(out, c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1 ) } (m4makeRotationY as any).__deps = [ m4set ] // export function m3new () { return new Float32Array([ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]) } export function m3makeNormal (out: Float32Array, m4: Float32Array) { const r0 = v3new([ m4[0], m4[1], m4[2] ]) const r1 = v3new([ m4[4], m4[5], m4[6] ]) const r2 = v3new([ m4[8], m4[9], m4[10] ]) const cp = v3new() // [ r0 ] [ r1 x r2 ] // M3x3 = [ r1 ] N = [ r2 x r0 ] // [ r2 ] [ r0 x r1 ] v3cross(cp, r1, r2) out[ 0 ] = cp[ 0 ] out[ 1 ] = cp[ 1 ] out[ 2 ] = cp[ 2 ] v3cross(cp, r2, r0) out[ 3 ] = cp[ 0 ] out[ 4 ] = cp[ 1 ] out[ 5 ] = cp[ 2 ] v3cross(cp, r0, r1) out[ 6 ] = cp[ 0 ] out[ 7 ] = cp[ 1 ] out[ 8 ] = cp[ 2 ] } (m3makeNormal as any).__deps = [ v3new, v3cross ]
the_stack
import { Box, createStyles, Link as KMLink, Theme, WithStyles } from "@material-ui/core"; import { grey } from "@material-ui/core/colors"; import withStyles from "@material-ui/core/styles/withStyles"; import { deleteApplicationAction } from "actions/application"; import { setErrorNotificationAction, setSuccessNotificationAction } from "actions/notification"; import { blinkTopProgressAction } from "actions/settings"; import { api } from "api"; import { push } from "connected-react-router"; import { withNamespace, WithNamespaceProps } from "hoc/withNamespace"; import { withUserAuth, WithUserAuthProps } from "hoc/withUserAuth"; import { ApplicationSidebar } from "pages/Application/ApplicationSidebar"; import { getPodLogQuery } from "pages/Application/Log"; import { ComponentCPUChart, ComponentMemoryChart } from "pages/Components/Chart"; import { getPod } from "pages/Components/Pod"; import React, { useState } from "react"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import { RootState } from "reducers"; import CustomButton from "theme/Button"; import { ApplicationComponentDetails, ApplicationDetails } from "types/application"; import sc from "utils/stringConstants"; import { CustomizedButton } from "widgets/Button"; import { ConfirmDialog } from "widgets/ConfirmDialog"; import { EmptyInfoBox } from "widgets/EmptyInfoBox"; import { EditIcon, KalmComponentsIcon, KalmViewListIcon, LockIcon, PlayIcon } from "widgets/Icon"; import { IconButtonWithTooltip, IconLinkWithToolTip } from "widgets/IconButtonWithTooltip"; import { InfoBox } from "widgets/InfoBox"; import { KRTable } from "widgets/KRTable"; import { Namespaces } from "widgets/Namespaces"; import { RoutesPopover } from "widgets/RoutesPopover"; import { BasePage } from "../BasePage"; const styles = (theme: Theme) => createStyles({ emptyWrapper: { width: "100%", display: "flex", justifyContent: "center", paddingTop: "110px", }, componentIcon: { height: "1.25rem", color: theme.palette.type === "light" ? theme.palette.primary.light : "#FFFFFF", }, }); const mapStateToProps = (state: RootState) => { const routesMap = state.routes.httpRoutes; const clusterInfo = state.cluster.info; const httpRoutes = state.routes.httpRoutes; const registriesState = state.registries; return { clusterInfo, routesMap, httpRoutes, registries: registriesState.registries, }; }; interface Props extends WithStyles<typeof styles>, WithUserAuthProps, WithNamespaceProps, ReturnType<typeof mapStateToProps> {} const ComponentRaw: React.FC<Props> = (props) => { const [isDeleteConfirmDialogOpen, setIsDeleteConfirmDialogOpen] = useState(false); const [deletingComponentItem] = useState<ApplicationDetails | undefined>(undefined); const closeDeleteConfirmDialog = () => { setIsDeleteConfirmDialogOpen(false); }; const renderDeleteConfirmDialog = () => { return ( <ConfirmDialog open={isDeleteConfirmDialogOpen} onClose={closeDeleteConfirmDialog} title={`${sc.ARE_YOU_SURE_PREFIX} this Application(${deletingComponentItem?.name})?`} content="This application is already disabled. You will lost this application config, and this action is irrevocable." onAgree={confirmDelete} /> ); }; const confirmDelete = async () => { const { dispatch } = props; try { if (deletingComponentItem) { await dispatch(deleteApplicationAction(deletingComponentItem.name)); await dispatch(setSuccessNotificationAction("Successfully delete an application")); } } catch { dispatch(setErrorNotificationAction()); } }; const renderSecondHeaderRight = () => { const { activeNamespaceName, canEditNamespace } = props; return ( <> {canEditNamespace(activeNamespaceName) && ( <CustomButton tutorial-anchor-id="add-component-button" component={Link} color="primary" size="small" variant="outlined" to={`/applications/${activeNamespaceName}/components/new`} > Add Component </CustomButton> )} </> ); }; const renderEmpty = () => { const { dispatch, activeNamespaceName, canEditNamespace } = props; return ( <EmptyInfoBox image={<KalmComponentsIcon style={{ height: 120, width: 120, color: grey[300] }} />} title={"This App doesn’t have any Components"} content="Components are the fundamental building blocks of your Application. Each Component corresponds to a single image, and typically represents a service or a cronjob." button={ canEditNamespace(activeNamespaceName) && ( <CustomizedButton variant="contained" color="primary" onClick={() => { blinkTopProgressAction(); dispatch(push(`/applications/${activeNamespaceName}/components/new`)); }} > Add Component </CustomizedButton> ) } /> ); }; // eslint-disable-next-line @typescript-eslint/no-unused-vars const renderInfoBox = () => { const title = "References"; const options = [ { title: ( <KMLink href="https://docs.kalm.dev/crd/component" target="_blank"> Component CRD </KMLink> ), content: "", }, ]; return <InfoBox title={title} options={options} />; }; const renderProtected = (component: ApplicationComponentDetails) => { const { activeNamespaceName, canEditNamespace } = props; const appName = activeNamespaceName; return ( <Box> {component.protectedEndpoint ? ( <IconLinkWithToolTip disabled={!canEditNamespace(appName)} onClick={() => { blinkTopProgressAction(); }} size="small" tooltipTitle="External access is restricted through SSO" to={`/applications/${appName}/components/${component.name}/edit#Access`} > <LockIcon fontSize="small" color="default" /> </IconLinkWithToolTip> ) : ( "" )} </Box> ); }; const getKRTableColumns = () => { return [ { Header: "", accessor: "protected" }, { Header: "", accessor: "componentName" }, { Header: "Pods", accessor: "pods" }, { Header: "CPU", accessor: "cpu" }, { Header: "Memory", accessor: "memory" }, { Header: "Type", accessor: "type" }, // { Header: "Image", accessor: "image" }, { Header: "Routes", accessor: "routes" }, { Header: "Actions", accessor: "actions" }, ]; }; const getKRTableData = () => { const { components, activeNamespaceName } = props; const data: any[] = []; components && components.forEach((component, index) => { data.push({ protected: renderProtected(component), componentName: ( <Box display={"flex"}> <Box display="flex" minWidth={100}> <KMLink component={Link} to={`/applications/${activeNamespaceName}/components/${component.name}`}> {component.name} </KMLink> </Box> </Box> ), pods: getPodsStatus(component, activeNamespaceName), cpu: renderCPU(component), memory: renderMemory(component), type: component.workloadType, // image: renderImage(component.image), routes: renderExternalAccesses(component, activeNamespaceName), actions: componentControls(component), }); }); return data; }; const getRoutes = (componentName: string, applicationName: string) => { const { httpRoutes } = props; const applicationRoutes = httpRoutes.filter((x) => { let isCurrent = false; x.destinations.map((target) => { const hostInfos = target.host.split("."); if ( hostInfos[0] && hostInfos[0].startsWith(componentName) && hostInfos[1] && hostInfos[1].startsWith(applicationName) ) { isCurrent = true; } return target; }); return isCurrent; }); return applicationRoutes; }; const renderCPU = (component: ApplicationComponentDetails) => { return <ComponentCPUChart component={component} />; }; const renderMemory = (component: ApplicationComponentDetails) => { return <ComponentMemoryChart component={component} />; }; const renderExternalAccesses = (component: ApplicationComponentDetails, applicationName: string) => { const { canViewNamespace, canEditNamespace } = props; const applicationRoutes = getRoutes(component.name, applicationName); if (applicationRoutes && applicationRoutes.length > 0 && canViewNamespace(applicationName)) { return ( <RoutesPopover applicationRoutes={applicationRoutes} applicationName={applicationName} canEdit={canEditNamespace(applicationName)} /> ); } else { return "-"; } }; const getPodsStatus = (component: ApplicationComponentDetails, activeNamespaceName: string) => { let pods: React.ReactElement[] = []; component.pods?.forEach((pod, index) => { if (pod.statusText !== "Terminated: Completed") { pods.push( <IconLinkWithToolTip onClick={() => { blinkTopProgressAction(); }} key={index} size="small" tooltipTitle={`${pod.name} ${pod.statusText}`} target="_blank" rel="noopener noreferrer" to={`/applications/${activeNamespaceName}/logs?` + getPodLogQuery(activeNamespaceName, pod)} > {getPod({ info: pod, key: index })} </IconLinkWithToolTip>, ); } }); return ( <Box display={"flex"} flexDirection="row" maxWidth={100} flexWrap="wrap"> {pods.length > 0 ? ( pods ) : ( <Box width={12} display={"flex"} flexDirection="row" justifyContent={"center"}> - </Box> )} </Box> ); }; const componentControls = (component: ApplicationComponentDetails) => { const { activeNamespaceName, dispatch, canEditNamespace } = props; const appName = activeNamespaceName; return ( <Box> <IconLinkWithToolTip onClick={() => { blinkTopProgressAction(); }} size="small" tooltipTitle="Details" to={`/applications/${appName}/components/${component.name}`} > <KalmViewListIcon /> </IconLinkWithToolTip> {canEditNamespace(activeNamespaceName) ? ( <IconLinkWithToolTip onClick={() => { blinkTopProgressAction(); }} tooltipTitle="Edit" size="small" to={`/applications/${appName}/components/${component.name}/edit`} > <EditIcon /> </IconLinkWithToolTip> ) : null} {component.workloadType === "cronjob" ? ( <IconButtonWithTooltip onClick={async () => { blinkTopProgressAction(); try { await api.triggerApplicationComponentJob(appName, component.name); dispatch(setSuccessNotificationAction(`Trigger Cronjob ${component.name} successful!`)); } catch (error) { dispatch(setErrorNotificationAction(`Trigger Cronjob ${component.name} failed: ${error}`)); } }} tooltipTitle="Trigger" size="small" > <PlayIcon /> </IconButtonWithTooltip> ) : null} </Box> ); }; const { components } = props; return ( <BasePage secondHeaderRight={renderSecondHeaderRight()} secondHeaderLeft={<Namespaces />} leftDrawer={<ApplicationSidebar />} > {renderDeleteConfirmDialog()} <Box p={2}> {components && components.length > 0 ? ( <> <Box pb={1}> <KRTable showTitle={true} title="Components" columns={getKRTableColumns()} data={getKRTableData()} /> </Box> {/* {renderInfoBox()} */} </> ) : ( renderEmpty() )} </Box> </BasePage> ); }; export const ComponentListPage = withStyles(styles)( withNamespace(withUserAuth(connect(mapStateToProps)(ComponentRaw))), );
the_stack
declare module 'planout' { export interface Inputs { [key: string]: string; } export type ParamValue = string | number | boolean | null | undefined; export type Params = { [key: string]: ParamValue; }; export interface PlanoutEvent { event: string; name: string; salt: string; inputs: Inputs; params: Params; } export interface PlanoutNamespaceConfig { name: string; num_segments: number; primary_unit: string; compiled: PlanoutCode; } export interface PlanoutExperimentConfig { name: string; namespace_name: string; num_segments: number; compiled: PlanoutCode; } export interface PlanoutNamespaceOp { op: 'add' | 'remove'; experiment: PlanoutExperimentConfig; } export interface PlanoutConfig { namespaces: PlanoutNamespaceConfig[], experiments: PlanoutNamespaceOp[], } export class Assignment<ParamsType> { constructor(experimentSalt: string, overrides?: Partial<ParamsType>); evaluate(value: unknown): unknown; getOverrides(): Partial<ParamsType>; /** * Set a value as an "override" - this value will not be replaced by calls * to `set`. */ addOverride<K extends keyof ParamsType>(key: K, value: ParamsType[K]): void; /** * Set all the overrides (fixed values) at once */ setOverrides(overrides: Partial<ParamsType>): void; /** * Set a value * * If a literal value is provided, it is used as is. * * If a PlanOutOpRandom instance is passed, this calls `execute(this)` on * it to calculate the value to store. * * If the value was previously set as an override, this will not replace * the existing value. * * @param key Name of the parameter * @param value Value or calculation */ set<K extends keyof ParamsType>( key: K, value: ParamsType[K] | Ops.Base.PlanOutOp<any, ParamsType[K]>, ): void; /** * Get a parameter value. If the value would have been null or undefined, * `def` is returned. */ get<K extends keyof ParamsType>(name: K, def?: ParamsType[K]): ParamsType[K]; /** * Get all the parameter values set so far */ getParams(): Partial<ParamsType>; /** * Remove a parameter value */ del(name: string): void; /** * Number of params set so far */ length(): number; } export class BaseExperiment<InputsType, ParamsType> { constructor(inputs: InputsType); } export class Experiment<InputsType, ParamsType> extends BaseExperiment<InputsType, ParamsType> { protected _exposureLogged: boolean; protected _inExperiment: boolean; protected inputs?: InputsType; public _assigned: boolean; public _assignment: Assignment<Partial<ParamsType>>; /** * Subclasses can use this implementation of getParamNames to calculate * the parameter names by examining the source code of `assign` at runtime. */ getDefaultParamNames(): string[]; requireAssignment(): void; requireExposureLogging(): void; /** * Called by the constructor to do any additional setup the subclass * wants to do. * * This should at a minimum call `this.setName('<experiment name>')`. * * Experiment names should be chosen to be unique - there should not be * two experiments with the same name running at similar times, as this * will confuse this library and also make it harder to distinguish the * results of different experiments. * * @abstract */ setup(): void; /** * True if this experiment is active */ inExperiment(): boolean; /** * Override a parameter, preventing it from being randomly selected */ addOverride(key: string, value: string): void; /** * Replace all overrides */ setOverrides(obj: Partial<InputsType> & Partial<ParamsType>): void; getSalt(): string; setSalt(value: string): void; getName(): string; /** * This is where you define the calculation of the parameters of the * experiment. You call params.set(<name>, <value or op>) * * @abstract * @param params Object to receive parameter definitions * @param args Constructor argument */ assign(params: Assignment<ParamsType>, args: InputsType): boolean | void; /** * Get the parameter names for this experiment. This is a list of names * that are calculated / defined by the experiment, which you can fetch * using "get". * * @abstract */ getParamNames(): string[]; shouldFetchExperimentParameter(name: string): boolean; /** * Call this in your setup implementation to set the experiment name */ setName(name: string): void; setAutoExposureLogging(b: boolean): void; getParams(): ParamsType; get<K extends keyof ParamsType, DT>( name: K, def: ParamsType[K], ): ParamsType[K]; toString(): string; logExposure(extras: { [k: string]: any }): void; shouldLogExposure(paramName: string): boolean; logEvent(eventType: string, extras: { [k: string]: any }): void; /** * Called to configure logging when an experiment starts up. * * @abstract */ configureLogger(): void; /** * Log a message to the analytics system * * @abstract * @param data */ log(data: { event?: string; name?: string; time?: number; salt?: string; inputs?: InputsType; params?: ParamsType; extra_data?: { [k: string]: any }; }): void; /** * Return whether exposure to this experiment was already logged * * Suggested implementation is to return this._exposureLogged in client * side code, but you might also want to cache this information in * localStorage or somesuch to avoid repeated logging of the exposure. * * @abstract */ previouslyLogged(): boolean; } export namespace ExperimentSetup { const registerExperimentInput: ( key: string, value: string | number | boolean | null | undefined, experimentName?: string | null, ) => void; const getExperimentInputs: (experimentName: string) => any; } export interface PlanoutCodeLiteralOp { op: 'literal'; value: any; } export interface PlanoutCodeGetOp { op: 'get'; var: string; } export interface PlanoutCodeSetOp { op: 'set'; var: string; value: PlanoutCode; } export interface PlanoutCodeSeqOp { op: 'seq'; seq: PlanoutCode[]; } export interface PlanoutCodeCondOp { op: 'cond'; cond: Array<{ if: PlanoutCode; then: PlanoutCode }>; } export interface PlanoutCodeBinaryOp { op: 'equals' | 'and' | 'or' | '>' | '<' | '>=' | '<=' | '%' | '/'; left: PlanoutCode; } export interface PlanoutCodeUnaryOp { op: 'return' | 'not' | 'round' | '-' | 'length'; value: PlanoutCode; } export interface PlanoutCodeCommutativeOp { op: 'min' | 'max' | 'product' | 'sum'; values: PlanoutCode[]; } export type PlanoutCodeValue = string | number | boolean | null; export interface PlanoutCodeRandomRangeOp { op: 'randomFloat' | 'randomInteger'; min: PlanoutCode; max: PlanoutCode; } export interface PlanoutCodeRandomTrialOp { op: 'bernoulliTrial'; p: PlanoutCode; } export interface PlanoutCodeRandomFilterOp { op: 'bernoulliFilter'; p: PlanoutCode; choices: PlanoutCode[]; } export interface PlanoutCodeUniformChoiceOp { op: 'uniformChoice'; choices: PlanoutCode[]; } export interface PlanoutCodeWeightedChoiceOp { op: 'weightedChoice'; choices: PlanoutCode[]; } export interface PlanoutCodeSampleOp { op: 'sample'; choices: PlanoutCode[]; draws: PlanoutCode; } export type PlanoutCodeRandomOp = { unit: PlanoutCode } & ( | PlanoutCodeRandomRangeOp | PlanoutCodeRandomTrialOp | PlanoutCodeRandomFilterOp | PlanoutCodeUniformChoiceOp | PlanoutCodeWeightedChoiceOp | PlanoutCodeSampleOp ); export type PlanoutCodeCoreOp = | PlanoutCodeGetOp | PlanoutCodeSetOp | PlanoutCodeSeqOp | PlanoutCodeCondOp | PlanoutCodeLiteralOp | PlanoutCodeBinaryOp | PlanoutCodeUnaryOp | PlanoutCodeCommutativeOp; type PlanoutCodeUnit = | PlanoutCodeValue | PlanoutCodeCoreOp | PlanoutCodeRandomOp; export type PlanoutCode = PlanoutCodeUnit | PlanoutCodeUnit[]; /** * Execute some PlanoutCode AST * * Values that are set in the code are stored in the "env" inside the * interpreter, and can be fetched using "get". "get" also returns * values from the input. */ export class Interpreter<InputsType, ParamsType> extends Object { name: string; _inExperiment?: boolean; /** * Run some planout code * * @param serialization Code to execute to update the environment * @param experimentSalt Salt to use for "random" values * @param inputs Values to provide initially as variables in the script * @param environment Environment to use; if not provided, one will be created */ constructor( serialization: PlanoutCode, experimentSalt?: string, inputs?: InputsType, environment?: Assignment<ParamsType>, ); inExperiment(): boolean; setEnv(newEnv: Assignment<ParamsType>): Interpreter<InputsType, ParamsType>; has(name: string): boolean; get<K extends keyof ParamsType>(name: K, def: ParamsType[K]): ParamsType[K]; getParams(): ParamsType; set<K extends keyof ParamsType>( key: K, value: ParamsType[K] | Ops.Base.PlanOutOp<any, ParamsType[K]>, ): Interpreter<InputsType, ParamsType>; getSaltSeparator(): string; setOverrides(overrides: Partial<ParamsType>): void; getOverrides(): Partial<ParamsType>; hasOverride(name: string): boolean; registerCustomOperators(operators: unknown): void; evaluate(code: PlanoutCode): any; } export namespace Namespace { class Namespace<ParamsType> { public numSegments: number; // Add an experiment; returns false if the experiment could not be added addExperiment<T extends ParamsType>( name: string, obj: BaseExperiment<unknown, T>, segments: number, ): boolean; removeExperiment(name: string): void; setAutoExposureLogging(value: boolean): void; inExperiment(): boolean; get<K extends keyof ParamsType>(name: string, def: ParamsType[K]): ParamsType[K]; logExposure(extras: object): void; logEvent(eventType: string, extras: object): void; requireExperiment(): void; requireDefaultExperiment(): void; } class SimpleNamespace<InputsType, ParamsType> extends Namespace<ParamsType> { constructor(args: InputsType); inputs: InputsType; _experiment?: Experiment<InputsType, ParamsType>; _defaultExperiment?: Experiment<InputsType, ParamsType>; _assignExperiment(): void; _assignExperimentObject(name: string): void; currentExperiments: { [key: string]: BaseExperiment<InputsType, ParamsType> }; setupDefaults(): void; setup(): void; setupExperiments(): void; getPrimaryUnit(): string; allowedOverride(): boolean; getOverrides(): Partial<ParamsType>; setPrimaryUnit(value: string): void; getSegment(): number; defaultGet<K extends keyof ParamsType>( name: K, def: ParamsType[K], ): ParamsType[K]; getName(): string; setName(name: string): void; previouslyLogged(): boolean; inExperiment(): boolean; setGlobalOverride(name: string): void; setLocalOverride(name: string): void; getParams(experimentName: string): ParamsType | null; getOriginalExperimentName(): string | null; } } type PlanOutOpMapper<T> = Assignment<T> | Interpreter<any, T>; interface PlanOutOp<T> { execute(assignment: PlanOutOp<unknown>): T; } export namespace Ops { namespace Core { class Literal<T> extends Ops.Base.PlanOutOp<{ value: T }, T> {} class Get extends Ops.Base.PlanOutOp<{ var: string }, string> {} class Seq<T> extends Ops.Base.PlanOutOp<{ seq: T[] }, T[]> {} class Set< T extends string | number | Ops.Base.PlanOutOp<any, any> > extends Ops.Base.PlanOutOp<{ var: string; value: T }, void> {} class Arr<T> extends Ops.Base.PlanOutOp<{ values: T[] }, T[]> {} class Map<ArgsT> extends Ops.Base.PlanOutOp<ArgsT, ArgsT> {} class Coalesce<T> extends Ops.Base.PlanOutOp<{ values: T[] }, T> {} class Index<T> extends Ops.Base.PlanOutOp< { base: T; index: keyof T }, T > {} class Cond<T> extends Ops.Base.PlanOutOp< { cond: Array<{ if: any; then: T }> }, T > {} class And<T> extends Ops.Base.PlanOutOp<{ values: T[] }, boolean> {} class Or<T> extends Ops.Base.PlanOutOp<{ values: T[] }, boolean> {} class Product extends Ops.Base.PlanOutOpCommutative<number> {} class Sum extends Ops.Base.PlanOutOpCommutative<number> {} class Equals<T> extends Ops.Base.PlanOutOpBinary<T, boolean> {} class GreaterThan extends Ops.Base.PlanOutOpBinary<number, boolean> {} class LessThan extends Ops.Base.PlanOutOpBinary<number, boolean> {} class LessThanOrEqualTo extends Ops.Base.PlanOutOpBinary< number, boolean > {} class GreaterThanOrEqualTo extends Ops.Base.PlanOutOpBinary< number, boolean > {} class Mod extends Ops.Base.PlanOutOpBinary<number, number> {} class Divide extends Ops.Base.PlanOutOpBinary<number, number> {} class Round extends Ops.Base.PlanOutOpUnary<number, number> {} class Not<T> extends Ops.Base.PlanOutOpUnary<T, boolean> {} class Negative extends Ops.Base.PlanOutOpUnary<number, number> {} class Min extends Ops.Base.PlanOutOpCommutative<number> {} class Max extends Ops.Base.PlanOutOpCommutative<number> {} class Length<T extends { length: any }> extends Ops.Base.PlanOutOpUnary< T, T['length'] > {} class Return<T> extends Ops.Base.PlanOutOp<{ value: T }, never> {} } namespace Random { type UnitType = null | string | number | Array<string | number | null>; class PlanOutOpRandom<InputsType, ValueT> extends Ops.Base .PlanOutOpSimple< InputsType & { unit: UnitType; }, ValueT > {} // Pick `draws` elements at random from `choices` class Sample<T> extends PlanOutOpRandom< { choices: T[]; draws: number }, T[] > {} // Pick one element at random from `choices`; weights make the selection // uneven class WeightedChoice<T> extends PlanOutOpRandom< { choices: T[]; weights: number[] }, T > {} // Pick one element at random from `choices`, all choices equally likely class UniformChoice<T> extends PlanOutOpRandom<{ choices: T[] }, T> {} class BernoulliFilter<T> extends PlanOutOpRandom< { p: number; choices: T[] }, T[] > {} class BernoulliTrial extends PlanOutOpRandom<{ p: number }, 0 | 1> {} class RandomInteger extends PlanOutOpRandom< { min: number; max: number }, number > {} class RandomFloat extends PlanOutOpRandom< { min: number; max: number }, number > {} } namespace Base { class PlanOutOp<ArgsT, ValueT, OtherParamsT = unknown> { constructor(args: ArgsT); execute(mapper: PlanOutOpMapper<OtherParamsT>): ValueT; getArgMixed<K extends keyof ArgsT>(name: K): ArgsT[K]; getArgNumber<K extends keyof Extract<ArgsT, number>>(name: K): number; getArgString<K extends keyof Extract<ArgsT, string>>(name: K): string; getArgList<K extends keyof Extract<ArgsT, any[]>>(name: K): any[]; getArgObject<K extends keyof Extract<ArgsT, object>>(name: K): object; getArgIndexish<K extends keyof Extract<ArgsT, object | any[]>>( name: K, ): object | any[]; } class PlanOutOpSimple< ArgsT, ValueT, OtherParamsT = unknown > extends PlanOutOp<ArgsT, ValueT, OtherParamsT> { simpleExecute(): unknown; } class PlanOutOpUnary<ArgT, ValueT> extends PlanOutOpSimple< { value: ArgT }, ValueT > {} class PlanOutOpBinary<T, U> extends PlanOutOpSimple< { left: T; right: T }, U > {} class PlanOutOpCommutative<T> extends PlanOutOpSimple< { left: T; right: T }, T > {} } } }
the_stack
import { spawn } from 'child_process'; import { dirname } from 'path'; import qs from 'querystring'; import { BrowserWindow, dialog, shell, webContents } from 'electron'; import { stat } from 'fs-extra'; import semver from 'semver'; import { Injectable, Autowired, INJECTOR_TOKEN, Injector } from '@opensumi/di'; import { Domain, isWindows, IEventBus, URI } from '@opensumi/ide-core-common'; import { IElectronMainUIService, IElectronMainUIServiceShape, IElectronPlainWebviewWindowOptions, } from '@opensumi/ide-core-common/lib/electron'; import { ElectronMainApiProvider, ElectronMainContribution, ElectronMainApiRegistry } from '../types'; import { WindowCreatedEvent } from './events'; @Injectable() export class ElectronMainUIService extends ElectronMainApiProvider<'fullScreenStatusChange' | 'windowClosed' | 'maximizeStatusChange'> implements IElectronMainUIServiceShape { @Autowired(IEventBus) eventBus: IEventBus; constructor() { super(); this.eventBus.on(WindowCreatedEvent, (e) => { const window = e.payload; window.getBrowserWindow().on('enter-full-screen', () => { this.fireFullScreenChangedEvent(window.getBrowserWindow().id, true); }); window.getBrowserWindow().on('leave-full-screen', () => { this.fireFullScreenChangedEvent(window.getBrowserWindow().id, false); }); window.getBrowserWindow().on('maximize', () => { this.fireMaximizeChangedEvent(window.getBrowserWindow().id, true); }); window.getBrowserWindow().on('unmaximize', () => { this.fireMaximizeChangedEvent(window.getBrowserWindow().id, false); }); window.getBrowserWindow().on('resized', () => { this.fireMaximizeChangedEvent(window.getBrowserWindow().id, window.getBrowserWindow().isMaximized()); }); window.getBrowserWindow().on('moved', () => { this.fireMaximizeChangedEvent(window.getBrowserWindow().id, window.getBrowserWindow().isMaximized()); }); }); } fireFullScreenChangedEvent(windowId: number, isFullScreen: boolean) { this.eventEmitter.fire('fullScreenStatusChange', windowId, isFullScreen); } fireMaximizeChangedEvent(windowId: number, isMaximized: boolean) { this.eventEmitter.fire('maximizeStatusChange', windowId, isMaximized); } async isFullScreen(windowId: number) { const win = BrowserWindow.fromId(windowId); return win ? win.isFullScreen() : false; } async isMaximized(windowId: number) { const win = BrowserWindow.fromId(windowId); return win ? win.isMaximized() : false; } async maximize(windowId: number) { BrowserWindow.fromId(windowId)?.maximize(); } async openPath(path: string) { return await shell.openPath(path); } async openExternal(uri: string) { await shell.openExternal(uri); } async moveToTrash(path: string) { if (semver.lt(process.versions.electron, '13.0.0')) { // Removed: shell.moveItemToTrash() // https://www.electronjs.org/docs/latest/breaking-changes#removed-shellmoveitemtotrash await (shell as any).moveItemToTrash(path); } else { await shell.trashItem(path); } } async revealInFinder(path: string) { await shell.showItemInFolder(path); } async revealInSystemTerminal(path: string) { const fileStat = await stat(path); let targetPath = path; if (!fileStat.isDirectory()) { targetPath = dirname(path); } openInTerminal(targetPath); } async getZoomFactor(webContentsId: number): Promise<number | undefined> { const contents = webContents.fromId(webContentsId); return contents?.getZoomFactor(); } async setZoomFactor( webContentsId: number, options: { value?: number; delta?: number; minValue?: number; maxValue?: number } = {}, ) { if (options.minValue === undefined) { options.minValue = 0.25; } if (options.maxValue === undefined) { options.maxValue = 5; } const contents = webContents.fromId(webContentsId); if (contents) { let factor: number | undefined; if (options.value) { factor = options.value; contents.setZoomFactor(options.value); } if (options.delta) { factor = contents.getZoomFactor() + options.delta; } if (factor) { if (options.minValue && factor < options.minValue) { factor = options.minValue; } if (options.maxValue && factor > options.maxValue) { factor = options.maxValue; } contents.setZoomFactor(factor); } } } async showOpenDialog(windowId: number, options: Electron.OpenDialogOptions): Promise<string[] | undefined> { return new Promise((resolve, reject) => { try { if (semver.lt(process.versions.electron, '6.0.0')) { (dialog as any).showOpenDialog(BrowserWindow.fromId(windowId), options, (paths) => { resolve(paths); }); } else { const win = BrowserWindow.fromId(windowId); if (!win) { return reject(new Error(`BrowserWindow ${windowId} not found`)); } dialog.showOpenDialog(win, options).then((value) => { if (value.canceled) { resolve(undefined); } else { resolve(value.filePaths); } }, reject); } } catch (e) { reject(e); } }); } async showSaveDialog(windowId: number, options: Electron.SaveDialogOptions): Promise<string | undefined> { return new Promise((resolve, reject) => { try { if (semver.lt(process.versions.electron, '6.0.0')) { (dialog as any).showSaveDialog(BrowserWindow.fromId(windowId), options, (path) => { resolve(path); }); } else { const win = BrowserWindow.fromId(windowId); if (!win) { return reject(new Error(`BrowserWindow ${windowId} not found`)); } dialog.showSaveDialog(win, options).then((value) => { if (value.canceled) { resolve(undefined); } else { resolve(value.filePath); } }, reject); } } catch (e) { reject(e); } }); } async createBrowserWindow(options?: IElectronPlainWebviewWindowOptions): Promise<number> { const window = new BrowserWindow(options); const windowId = window.id; window.once('closed', () => { this.eventEmitter.fire('windowClosed', windowId); }); return window.id; } async browserWindowLoadUrl(windowId: number, url: string): Promise<void> { const window = BrowserWindow.fromId(windowId); if (!window) { throw new Error('window with windowId ' + windowId + ' does not exist!'); } const formattedURL = new URL(url).toString(); const urlParsed = URI.parse(formattedURL); const queryString = qs.stringify({ ...qs.parse(urlParsed.query), windowId, }); window.loadURL(urlParsed.withQuery(queryString).toString(true)); return new Promise((resolve, reject) => { const resolved = () => { resolve(); window.webContents.removeListener('did-finish-load', resolved); window.webContents.removeListener('did-fail-load', rejected); }; const rejected = (_event, _errorCode, desc: string) => { reject(new Error(desc)); window.webContents.removeListener('did-finish-load', resolved); window.webContents.removeListener('did-fail-load', rejected); }; window.webContents.once('did-finish-load', resolved); window.webContents.once('did-fail-load', rejected); }); } async closeBrowserWindow(windowId: number): Promise<void> { const window = BrowserWindow.fromId(windowId); if (!window) { throw new Error('window with windowId ' + windowId + ' does not exist!'); } window.close(); return new Promise<void>((resolve) => { window.once('closed', () => { resolve(); }); }); } async postMessageToBrowserWindow(windowId: number, channel: string, message: any): Promise<void> { const window = BrowserWindow.fromId(windowId); if (!window) { throw new Error('window with windowId ' + windowId + ' does not exist!'); } window.webContents.send(channel, message); } async getWebContentsId(windowId): Promise<number> { const window = BrowserWindow.fromId(windowId); if (!window) { throw new Error('window with windowId ' + windowId + ' does not exist!'); } return window.webContents.id; } async showBrowserWindow(windowId: number): Promise<void> { const window = BrowserWindow.fromId(windowId); if (!window) { throw new Error('window with windowId ' + windowId + ' does not exist!'); } window.show(); } async hideBrowserWindow(windowId: number): Promise<void> { const window = BrowserWindow.fromId(windowId); if (!window) { throw new Error('window with windowId ' + windowId + ' does not exist!'); } window.hide(); } async setSize(windowId: number, size: { width: number; height: number }): Promise<void> { const window = BrowserWindow.fromId(windowId); if (!window) { throw new Error('window with windowId ' + windowId + ' does not exist!'); } window.setSize(size.width, size.height); } async setAlwaysOnTop(windowId: number, flag: boolean): Promise<void> { const window = BrowserWindow.fromId(windowId); if (!window) { throw new Error('window with windowId ' + windowId + ' does not exist!'); } window.setAlwaysOnTop(flag); } } @Domain(ElectronMainContribution) export class UIElectronMainContribution implements ElectronMainContribution { @Autowired(INJECTOR_TOKEN) injector: Injector; registerMainApi(registry: ElectronMainApiRegistry) { registry.registerMainApi(IElectronMainUIService, this.injector.get(ElectronMainUIService)); } } export async function openInTerminal(dir: string) { if (isWindows) { spawn('cmd', ['/s', '/c', 'start', 'cmd.exe', '/K', 'cd', '/D', dir], { detached: true, }); } else { spawn('open', ['-a', 'Terminal', dir], { detached: true, }); } }
the_stack
namespace shaka { namespace polyfill { function installAll(): void; function register(polyfill: () => void, priority?: number): void; class polyfill_install { static install(): void; } class Fullscreen extends polyfill_install {} class IndexedDB extends polyfill_install {} class InputEvent extends polyfill_install {} class MathRound extends polyfill_install {} class MediaSource extends polyfill_install {} class VideoPlaybackQuality extends polyfill_install {} class VideoPlayPromise extends polyfill_install {} class VTTCue extends polyfill_install {} class PatchedMediaKeysMs extends polyfill_install { static setMediaKeys(mediaKeys: MediaKeys): void; static requestMediaKeySystemAccess( keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[] ): Promise<MediaKeySystemAccess>; } class PatchedMediaKeysNop extends polyfill_install { static setMediaKeys(mediaKeys: MediaKeys): void; static requestMediaKeySystemAccess( keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[] ): Promise<MediaKeySystemAccess>; } class PatchedMediaKeysWebkit extends polyfill_install { static setMediaKeys(mediaKeys: MediaKeys): void; static requestMediaKeySystemAccess( keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[] ): Promise<MediaKeySystemAccess>; } } interface EventMap { abrstatuschanged: Player.AbrStatusChangedEvent; adaptation: Player.AdaptationEvent; buffering: Player.BufferingEvent; drmsessionupdate: Player.DrmSessionUpdateEvent; emsg: Player.EmsgEvent; error: Player.ErrorEvent; expirationupdated: Player.ExpirationUpdatedEvent; largegap: Player.LargeGapEvent; loading: Player.LoadingEvent; manifestparsed: Player.ManifestParsedEvent; onstatechange: Player.StateChangeEvent; onstateidle: Player.StateIdleEvent; streaming: Player.StreamingEvent; textchanged: Player.TextChangedEvent; texttrackvisibility: Player.TextTrackVisibilityEvent; timelineregionadded: Player.TimelineRegionAddedEvent; timelineregionenter: Player.TimelineRegionEnterEvent; timelineregionexit: Player.TimelineRegionExitEvent; trackschanged: Player.TracksChangedEvent; unloading: Player.UnloadingEvent; variantchanged: Player.VariantChangedEvent; } class Player extends util.FakeEventTarget implements util.IDestroyable { /** * Construct a Player * * @param mediaElem When provided, the player will attach to * `mediaElement`, similar to calling * `attach`. When not provided, the player * will remain detached. * @param dependencyInjector Optional callback which is * called to inject mocks into the * Player. Used for testing. */ constructor(mediaElem?: HTMLMediaElement, dependencyInjector?: (arg1: Player) => void); static version: string; /** * Return whether the browser provides basic support. If this returns false, * Shaka Player cannot be used at all. In this case, do not construct a Player * instance and do not use the library. */ static isBrowserSupported(): boolean; /** * Probes the browser to determine what features are supported. * This makes a number of requests to EME/MSE/etc which may * result in user prompts. This should only be used for * diagnostics. * * NOTE: This may show a request to the user for permission. */ static probSupport(): Promise<extern.SupportType>; /** * Registers a plugin callback that will be called with support(). * The callback will return the value that will be stored in the * return value from support(). */ static registerSupportPlugin(name: string, callback: () => void): void; /** * Add an event listener to this object. * * @param type The event type to listen for. * @param listener The callback or listener object to invoke. * @param options Ignored. */ addEventListener<K extends keyof EventMap>( type: K, listener: (event: EventMap[K]) => boolean | void | undefined, options?: AddEventListenerOptions ): void; // eslint-disable-next-line no-dupe-class-members addEventListener( type: string, listener: util.FakeEventTarget.ListenerType, options?: AddEventListenerOptions ): void; /** * Adds the given text track to the loaded manifest. load() must resolve before calling. * The presentation must have a duration. This returns the created track, which can immediately be selected by the application. * The track will not be automatically selected. * * @param uri * @param language * @param kind * @param mime * @param codec * @param label */ addTextTrack( uri: string, language: string, kind: string, mime: string, codec?: string, label?: string ): extern.Track; /** * Tell the player to use |mediaElement| for all |load| requests * until |detach| or |destroy| are called. Calling |attach| with * |initializedMediaSource=true| will tell the player to take * the initial load step and initialize media source. * * Calls to |attach| will interrupt any in-progress calls to * |load| but cannot interrupt calls to |attach|, |detach|, or * `unload`. * * @param mediaElem * @param initializeMediaSource */ attach(mediaElem: HTMLMediaElement, initializeMediaSource?: boolean): Promise<unknown>; /** * Cancel trick-play. If the player has not loaded content or is * still loading content this will be a no-op. */ cancelTrickPlay(): void; /** * Configure the Player instance. The config object passed in need * not be complete. It will be merged with the existing Player * configuration. Config keys and types will be checked. If any * problems with the config object are found, errors will be * reported through logs and this returns false. If there are * errors, valid config objects are still set. * * @returns `true` if the passed config object was valid, `false` * if there were invalid entries. */ configure(config: extern.PlayerConfiguration | string): boolean; /** * After destruction, a Player object cannot be * used again. */ destroy(): Promise<unknown>; /** * Tell the player to stop using its current media element. * If the player is: * - detached, this will do nothing, * - attached, this will release the media element, * - loading, this will abort loading, unload, and release * the media element, * - playing content, this will stop playback, unload, and * release the media element. * * Calls to `detach` will interrupt any in-progress calls * to `load` but cannot interrupt calls to `attach`, * `detach`, or `unload`. */ detach(): Promise<unknown>; /** * Get the drm info used to initialize EME. If EME is * not being used, this will return `null`. If the * player is idle or has not initialized EME yet, this * will return `null`. */ drmInfo(): extern.DrmInfo | null; /** * Get the uri to the asset that the player has loaded. * If the player has not loaded content, this will * return `null`. */ getAssetUri(): string | null; /** * Return a list of audio languages available for the * current period. If the player has not loaded any * content, this will return an empty list. */ getAudioLanguages(): string[]; /** * Return a list of audio language-role combinations * available for the current period. If the player * has not loaded any content, this will return an * empty list. */ getAudioLanguagesAndRoles(): extern.LanguageRole[]; /** * Get information about what the player has buffered. If * the player has not loaded content or is currently * loading content, the buffered content will be empty. */ getBufferedInfo(): extern.BufferedInfo; /** * Return a copy of the current configuration. Modifications * of the returned value will not affect the Player"s active * configuration. You must call player.configure() to make * changes. */ getConfiguration(): extern.PlayerConfiguration; /** * Get the next known expiration time for any EME session. * If the session never expires, this will return `Infinity`. * If there are no EME sessions, this will return `Infinity`. * If the player has not loaded content, this will * return `Infinity`. */ getExpiration(): number; /** Get the current load mode. */ getLoadMode(): Player.LoadMode; /** * Get the manifest that the player has loaded. If the player * has not loaded any content, this will return `null`. */ getManifest(): extern.Manifest | null; /** * Get the type of manifest parser that the player is using. * If the player has not loaded any content, this will * return `null`. */ getManifestParserFactory(): extern.ManifestParser.Factory | null; // In older versions /** @deprecated */ getManifestUri(): string | null; /** * Get the media element that the player is currently using * to play loaded content. If the player has not loaded * content, this will return `null`. */ getMediaElement(): HTMLMediaElement; /** * @returns A reference to the Player"s networking engine. * Applications may use this to make requests * through Shaka"s networking plugins. */ getNetworkingEngine(): net.NetworkingEngine; /** * Get the playback rate of what is playing right now. * If we are using trick play, this will return the * trick play rate. If no content is playing, this * will return 0. If content is buffering, this will * return 0. If the player has not loaded content, this * will return a playback rate of `0`. */ getPlaybackRate(): number; /** * Get the current playhead position as a date. This * should only be called when the player has loaded * a live stream. If the player has not loaded a live * stream, this will return `null`. */ getPlayheadTimeAsTime(): Date | null; /** * Get the presentation start time as a date. This * should only be called when the player has loaded * a live stream. If the player has not loaded a * live stream, this will return `null`. */ getPresentationStartTimeAsDate(): Date | null; /** * Get statistics for the current playback session. * If the player is not playing content, this will * return an empty stats object. */ getStats(): extern.Stats; /** * Return a list of text languages available for the * current period. If the player has not loaded any * content, this will return an empty list. */ getTextLanguages(): string[] | null; /** * Return a list of text language-role combinations * available for the current period. If the player * has not loaded any content, this will be return * an empty list. */ getTextLanguagesAndRoles(): extern.LanguageRole[]; /** * Return a list of text tracks that can be switched * to in the current period. If there are multiple * periods, you must seek to a period in order to get * text tracks from that period. If the player has * not loaded content, this will return an empty list. */ getTextTracks(): extern.Track[]; /** * Return a list of variant tracks that can be * switched to in the current period. If there * are multiple periods, you must seek to the * period in order to get variants from that * period. If the player has not loaded content, * this will return an empty list. */ getVariantTracks(): extern.Track[]; /** * Check if the manifest contains only audio-only * content. If the player has not loaded content, * this will return `false`. The player does not * support content that contain more than one type * of variants (i.e. mixing audio-only, video-only, * audio-video). Content will be filtered to only * contain one type of variant. */ isAudioOnly(): boolean; /** * Check if the player is currently in a buffering * state (has too little content to play smoothly). * If the player has not loaded content, this will * return `false`. */ isBuffering(): boolean; /** * Get if the player is playing in-progress content. * If the player has not loaded content, this will * return `false`. */ isInProgress(): boolean; /** * Get if the player is playing live content. If the player * has not loaded content, this will return `false`. */ isLive(): boolean; /** Check if the text displayer is enabled. */ isTextTrackVisible(): boolean; /** * Get the key system currently used by EME. If EME is not * being used, this will return an empty string. If the * player has not loaded content, this will return an * empty string. */ keySystem(): string; /** * Tell the player to load the content at `assetUri` and start * playback at `startTime`. Before calling `load`, a call to * `attach` must have succeeded. Calls to `load` will interrupt * any in-progress calls to `load` but cannot interrupt calls * to `attach`, `detach`, or `unload`. * * @param assetUri * @param startTime When `startTime` is `null` or `undefined`, * playback will start at the default start * time (startTime=0 for VOD and * startTime=liveEdge for LIVE). * @param mimeType */ load( assetUri: string, startTime?: number | null, mimeType?: string | extern.ManifestParser.Factory ): Promise<unknown>; /** Reset configuration to default.*/ resetConfiguration(): void; /** * Retry streaming after a streaming failure has occurred. * When the player has not loaded content or is loading * content, this will be a no-op and will return `false`. * If the player has loaded content, and streaming has * not seen an error, this will return `false`. If the * player has loaded content, and streaming seen an error, * but the could not resume streaming, this will return * `false`. */ retryStreaming(): boolean; /** * Get the range of time (in seconds) that seeking is allowed. * If the player has not loaded content, this will return a * range from 0 to 0. */ seekRange(): { start: number; end: number }; /** * Sets currentAudioLanguage and currentVariantRole to the * selected language and role, and chooses a new variant * if need be. If the player has not loaded any content, * this will be a no-op. */ selectAudioLanguage(language: string, role?: string): void; /** @deprecated */ selectEmbeddedTextTrack(): void; /** * Sets currentTextLanguage and currentTextRole to the * selected language and role, and chooses a new variant * if need be. If the player has not loaded any content, * this will be a no-op. */ selectTextLanguage(language: string, role?: string): void; /** * Select a specific text track from the current period. * `track` should come from a call to `getTextTracks`. * If the track is not found in the current period, this * will be a no-op. If the player has not loaded content, * this will be a no-op. Note that AdaptationEvents are * not fired for manual track selections. */ selectTextTrack(track: extern.Track): void; /** * Select variant tracks that have a given label. This assumes * the label uniquely identifies an audio stream, so all the * variants are expected to have the same variant.audio. */ selectVariantsByLabel(label: string): void; /** * Select a specific variant track to play from the current * period. `track` should come from a call to * `getVariantTracks`. If `track` cannot be found in the * current variant, this will be a no-op. If the player has * not loaded content, this will be a no-op. Changing * variants will take effect once the currently buffered * content has been played. To force the change to happen * sooner, use `clearBuffer` with `safeMargin`. Setting * `clearBuffer` to `true` will clear all buffered content * after `safeMargin`, allowing the new variant to start * playing sooner. Note that AdaptationEvents are not fired * for manual track selections. * * @param track * @param clearBuffer * @param safeMargin Optional amount of buffer (in seconds) * to retain when clearing the buffer. * Useful for switching variant quickly * without causing a buffering event. * Defaults to 0 if not provided. Ignored * if clearBuffer is false. Can cause * hiccups on some browsers if chosen too * small, e.g. The amount of two segments * is a fair minimum to consider as * safeMargin value. */ selectVariantTrack(track: extern.Track, clearBuffer?: boolean, safeMargin?: number): void; /** * Set the maximum resolution that the platform"s hardware * can handle. This will be called automatically by * shaka.cast.CastReceiver to enforce limitations of the * Chromecast hardware. */ setMaxHardwareResolution(width: number, height: number): void; /** * Enable or disable the text displayer. If the player * is in an unloaded state, the request will be applied * next time content is loaded. */ setTextTrackVisibility(on: boolean): void; /** * Enable trick play to skip through content without * playing by repeatedly seeking. For example, a rate * of 2.5 would result in 2.5 seconds of content * being skipped every second. A negative rate will * result in moving backwards. If the player has not * loaded content or is still loading content this * will be a no-op. Wait until |load| has completed * before calling. Trick play will be canceled * automatically if the playhead hits the beginning * or end of the seekable range for the content. */ trickPlay(rate: number): void; /** * Tell the player to either return to: * - detached (when it does not have a media element), * - attached (when it has a media element and * `initializedMediaSource=false`) * - media source initialized (when it has a media * element and `initializedMediaSource=true`) * * Calls to `unload` will interrupt any in-progress * calls to `load` but cannot interrupt calls to * `attach`, `detach`, or `unload`. */ unload(reinitializeMediaSource?: boolean): Promise<unknown>; /** @deprecated */ usingEmbeddedTextTrack(): boolean; setVideoContainer(container: HTMLElement): void; getPlayheadTimeAsDate(): Date | null; } namespace Player { /** * In order to know what method of loading the player used * for some content, we have this enum. It lets us know * if content has not been loaded, loaded with media source, * or loaded with src equals. This enum has a low resolution, * because it is only meant to express the outer limits of * the various states that the player is in. For example, * when someone calls a public method on player, it should * not matter if they have initialized drm engine, it should * only matter if they finished loading content. */ enum LoadMode { DESTROYED = 0, NOT_LOADED = 1, MEDIA_SOURCE = 2, SRC_EQUALS = 3, } /** * Fired when the state of abr has been * changed. (Enabled or disabled). */ interface AbrStatusChangedEvent extends Event { type: "abrstatuschanged"; newStatus: boolean; } /** * Fired when an automatic adaptation causes * the active tracks to change. Does not * fire when the application calls * selectVariantTrack() selectTextTrack(), * selectAudioLanguage() or selectTextLanguage(). */ interface AdaptationEvent extends Event { type: "adaptation"; } /** * Fired when the player"s buffering state changes. */ interface BufferingEvent extends Event { type: "buffering"; /** * True when the Player enters the * buffering state. False when the * Player leaves the buffering state. */ buffering: boolean; } interface DrmSessionUpdateEvent extends CustomEvent<void> { type: "drmsessionupdate"; } interface EmsgEvent extends CustomEvent<extern.EmsgInfo> { type: "emsg"; detail: extern.EmsgInfo; } interface ErrorEvent extends CustomEvent<util.Error> { type: "error"; } /** * Fired when there is a change in the * expiration times of an EME session. */ interface ExpirationUpdatedEvent extends Event { type: "expirationupdated"; } /** * Fired when the playhead enters a large gap. * If |config.streaming.jumpLargeGaps| is set, * the default action of this event is to jump * the gap; this can be prevented by calling * preventDefault() on the event object. */ interface LargeGapEvent { type: "largegap"; /** The current time of the playhead. */ currentTime: number; /** The size of the gap, in seconds. */ gapSize: number; } /** * Fired when the player begins loading. * The start of loading is defined as * when the user has communicated intent * to load content (i.e. Player.load has * been called). */ interface LoadingEvent extends Event { type: "loading"; } interface ManifestParsedEvent extends Event { type: "manifestparsed"; } /** Fired when the player changes load states. */ interface StateChangeEvent extends Event { type: "onstatechange"; state: string; } /** * Fired when the player has stopped changing * states and will remain idle until a new * state change request (e.g. load, attach, * etc.) is made. */ interface StateIdleEvent extends Event { type: "onstateidle"; state: string; } /** * Fired after the manifest has been parsed * and track information is available, but * before streams have been chosen and * before any segments have been fetched. * You may use this event to configure the * player based on information found in the * manifest. */ interface StreamingEvent extends Event { type: "streaming"; } /** * Fired when a call from the application * caused a text stream change. Can be * triggered by calls to selectTextTrack() * or selectTextLanguage(). */ interface TextChangedEvent extends Event { type: "textchanged"; } /** Fired when text track visibility changes. */ interface TextTrackVisibilityEvent extends Event { type: "texttrackvisibility"; } /** Fired when a media timeline region is added. */ interface TimelineRegionAddedEvent extends CustomEvent<extern.TimelineRegionInfo> { type: "timelineregionadded"; } /** Fired when the playhead enters a timeline region. */ interface TimelineRegionEnterEvent extends CustomEvent<extern.TimelineRegionInfo> { type: "timelineregionenter"; } /** Fired when the playhead exits a timeline region. */ interface TimelineRegionExitEvent extends CustomEvent<extern.TimelineRegionInfo> { type: "timelineregionexit"; } /** * Fired when the list of tracks changes. * For example, this will happen when * changing periods or when track * restrictions change. */ interface TracksChangedEvent extends Event { type: "trackschanged"; } /** * Fired when the player unloads or fails * to load. Used by the Cast receiver to * determine idle state. */ interface UnloadingEvent extends Event { type: "unloading"; } /** * Fired when a call from the application * caused a variant change. Can be * triggered by calls to selectVariantTrack() * or selectAudioLanguage(). Does not * fire when an automatic adaptation * causes a variant change. */ interface VariantChangedEvent extends Event { type: "variantchanged"; } } namespace log { function setLevel(level: Level): void; enum Level { NONE = 0, ERROR = 1, WARNING = 2, INFO = 3, DEBUG = 4, V1 = 5, V2 = 6, } } namespace net { namespace NetworkingEngine { // @see: https://shaka-player-demo.appspot.com/docs/api/shaka.net.NetworkingEngine.html#.RequestType enum RequestType { MANIFEST = 0, SEGMENT = 1, LICENSE = 2, APP = 3, TIMING = 4, } enum PluginPriority { FALLBACK = 1, PREFERRED = 2, APPLICATION = 3, } /** Fired when the networking engine receives a recoverable error and retries. */ interface RetryEvent extends Event { type: "retry"; /** The error that caused the retry. If it was a non-Shaka error, this is set to null. */ error: util.Error | null; } /** * A wrapper class for the number of bytes remaining to be downloaded for the * request. * Instead of using PendingRequest directly, this class is needed to be sent to * plugin as a parameter, and a Promise is returned, before PendingRequest is * created. */ class NumBytesRemainingClass { setBytes(bytesToLoad: number): void; getBytes(): number; } /** * @param promise A Promise which represents the underlying operation. It is * resolved when the operation is complete, and rejected if * the operation fails or is aborted. Aborted operations should * be rejected with a `shaka.util.Error` object using the error * code `OPERATION_ABORTED`. * @param onAbort Will be called by this object to abort the underlying * operation. This is not cancelation, and will not necessarily * result in any work being undone. abort() should return a * Promise which is resolved when the underlying operation has * been aborted. The returned Promise should never be rejected. */ class PendingRequest<T = extern.Response> extends util.AbortableOperation<T> implements extern.IAbortableOperation<T> { promise: Promise<T>; constructor( promise: Promise<T>, onAbort: ConstructorParameters<typeof util.AbortableOperation>["1"], numBytesRemainingObj: NetworkingEngine.NumBytesRemainingClass ); abort(): ReturnType<util.AbortableOperation<T>["abort"]>; chain<U>( onSuccess: Parameters<util.AbortableOperation<T>["chain"]>[0], onError?: Parameters<util.AbortableOperation<T>["chain"]>[1] ): util.AbortableOperation<U>; finally(): util.AbortableOperation<T>; } } class NetworkingEngine extends util.FakeEventTarget implements util.IDestroyable { constructor(onProgressUpdated?: (duration: number, transferredByteAmount: number) => void); /** Gets a copy of the default retry parameters. */ static defaultRetryParameters(): extern.RetryParameters; /** Makes a simple network request for the given URIs */ static makeRequest(uris: Array<string>, retryParams: extern.RetryParameters): extern.Request; /** * Registers a scheme plugin. This plugin will handle all requests * with the given scheme. If a plugin with the same scheme already * exists, it is replaced, unless the existing plugin is of higher * priority. If no priority is provided, this defaults to the * highest priority of APPLICATION. */ static registerScheme(scheme: string, plugin: extern.SchemePlugin, priority?: number): void; /** Removes a scheme plugin. */ static unregisterScheme(scheme: string): void; /** Clears all request filters. */ clearAllRequestFilters(): void; /** Clears all response filters. */ clearAllResponseFilters(): void; /** * Registers a new request filter. All filters are applied in the * order they are registered. */ registerRequestFilter(filter: extern.RequestFilter): void; /** * Registers a new response filter. All filters are applied in the * order they are registered. */ registerResponseFilter(filter: extern.ResponseFilter): void; /** Makes a network request and returns the resulting data. */ request( type: net.NetworkingEngine.RequestType, request: extern.Request ): net.NetworkingEngine.PendingRequest; /** Removes a request filter. */ unregisterRequestFilter(filter: extern.RequestFilter): void; /** Removes a response filter. */ unregisterResponseFilter(filter: extern.ResponseFilter): void; destroy(): Promise<unknown>; } declare const HttpXHRPlugin: | { static parse: ( uri: string, request: extern.Request, requestType: net.NetworkingEngine.RequestType, progressUpdated?: shaka.extern.ProgressUpdated ) => util.AbortableOperation<shaka.extern.Response>; } | { ( uri: string, request: extern.Request, requestType: net.NetworkingEngine.RequestType, progressUpdated?: shaka.extern.ProgressUpdated ): util.AbortableOperation<shaka.extern.Response>; static parse: undefined; }; } namespace media { class initSegmentReference { constructor(uris: () => string[], startByte: number, endByte: number | null); createUris(): string[]; getEndByte(): number | undefined | null; getStartByte(): number; } class SegmentReference { constructor( position: number, startTime: number, endTime: number, uris: () => string[], startByte: number, endByte: number | null ); createUris(): string[]; getEndByte(): number | undefined | null; getStartByte(): number; getEndTime(): number; getPosition(): number; getStartTime(): number; } class PresentationTimeline { constructor(presentationStartTime: number | null, presentationDelay: number); getDuration(): number; getPresentationStartTime(): number | null; getSafeSeekRangeStart(offset: number): number; getSeekRangeEnd(): number; getSeekRangeStart(): number; getSegmentAvailabilityEnd(): number; getSegmentAvailabilityStart(): number; isInprogress(): boolean; isLive(): boolean; notifyMaxSegmentDuration(maxSegmentDuration: number): void; notifySegments(references: SegmentReference[], isFirstPeriod: boolean): void; setClockOffset(offset: number): void; setDelay(delay: number): void; setDuration(duration: number): void; setSegmentAvailabilityDuration(SegmentAvailabilityDuration: number): void; setStatic(isStatic: boolean): void; setUserSeekStart(time: boolean): void; } class ManifestParser { static registerParserByExtension(extension: string, parserFactory: unknown); static registerParserByMime(mimeType: string, parserFactory: unknown); } class SegmentIndex { constructor(references: SegmentReference[]); destroy(): Promise<void>; release(): void; markImmutable(): void; find(time: number): number | null; get(position: number): SegmentReference | null; offset(number): void; merge(references: SegmentReference[]); } } namespace text { namespace Cue { enum displayAlign { BEFORE = "before", CENTER = "center", AFTER = "after", } enum fontStyle { NORMAL = "normal", ITALIC = "italic", OBLIQUE = "oblique", } enum fontWeight { NORMAL = 400, BOLD = 700, } enum lineAlign { CENTER = "center", START = "start", END = "end", } enum lineInterpretation { LINE_NUMBER = 0, PERCENTAGE = 1, } enum positionAlign { LEFT = "line-left", RIGHT = "line-right", CENTER = "center", AUTO = "auto", } enum textAlign { LEFT = "left", RIGHT = "right", CENTER = "center", START = "start", END = "end", } enum textDecoration { UNDERLINE = "underline", LINE_THROUGH = "lineThrough", OVERLINE = "overline", } enum writingDirection { HORIZONTAL_LEFT_TO_RIGHT = 0, HORIZONTAL_RIGHT_TO_LEFT = 1, VERTICAL_LEFT_TO_RIGHT = 2, VERTICAL_RIGHT_TO_LEFT = 3, } } class Cue { constructor(startTime: number, endTime: number, payload: string); public backgroundColor: string; public color: string; public displayAlign: Cue.displayAlign; public endTime: number; public fontFamily: string; public fontSize: string; public fontStyle: Cue.fontStyle; public fontWeight: Cue.fontWeight; public id: string; public line: number; public lineAlign: Cue.lineAlign; public lineHeight: string; public lineInterpretation: Cue.lineInterpretation; public payload: string; public position: number | null; public positionAlign: Cue.positionAlign; public region: extern.CueRegion; public size: number; public startTime: number; public textAlign: Cue.textAlign; public textDecoration: Cue.textDecoration[]; public wrapLine: boolean; public writingDirection: Cue.writingDirection; } namespace CueRegion { enum scrollMode { NONE, UP = "up", } enum units { PX = 0, PERCENTAGE = 1, LINES = 2, } } class CueRegion { height: number; heightUnits: CueRegion.units; id: string; regionAnchorX: number; regionAnchorY: number; scroll: text.CueRegion.scrollMode; viewportAnchorUnits: text.CueRegion.units; viewportAnchorX: number; viewportAnchorY: number; width: number; widthUnits: text.CueRegion.units; } } namespace util { /** * @param promise * A Promise which represents the underlying operation. It is resolved when * the operation is complete, and rejected if the operation fails or is * aborted. Aborted operations should be rejected with a shaka.util.Error * object using the error code OPERATION_ABORTED. * @param onAbort * Will be called by this object to abort the underlying operation. * This is not cancelation, and will not necessarily result in any work * being undone. abort() should return a Promise which is resolved when the * underlying operation has been aborted. The returned Promise should never * be rejected. */ class AbortableOperation<T, A = unknown> implements extern.IAbortableOperation<T> { promise: Promise<T>; constructor(promise: Promise<T>, onAbort: () => Promise<A>); /** * @returns An operation which has already failed with the error OPERATION_ABORTED. */ static aborted(): AbortableOperation<util.Error>; /** * @returns An operation which is resolved when all operations are successful * and fails when any operation fails. For this operation, abort() * aborts all given operations. */ static all(operations: AbortableOperation<unknown>[]): AbortableOperation<unknown>; static completed<U>(value: U): AbortableOperation<U>; static failed(error: Error): AbortableOperation<unknown>; static notAbortable<U>(promise: Promise<U>): AbortableOperation<U>; abort(): ReturnType<ConstructorParameters<typeof util.AbortableOperation>["1"]>; /** * * @param onSuccess A callback to be invoked after this operation is complete, * to chain to another operation. The callback can return a * plain value, a Promise to an asynchronous value, or another * AbortableOperation. * @param onError An optional callback to be invoked if this operation fails, to * perform some cleanup or error handling. Analogous to the second * parameter of Promise.prototype.then. */ chain<U>( onSuccess?: (value: T) => Promise<U> | AbortableOperation<U>, onError?: () => void ): AbortableOperation<U>; finally(onFinal: (arg: boolean) => void): ThisType<T>; } namespace DataViewReader { enum Endianness { BIG_ENDIAN = 0, LITTLE_ENDIAN = 1, } } class DataViewReader { static endianness: number; constructor(dataView: DataView, endianness: DataViewReader.Endianness); getLength(): number; getPosition(): number; hasMoreData(): boolean; readBytes(bytes: number): Uint8Array; readInt32(): number; readTerminatedString(): string; readUint8(): number; readUint16(): number; readUint32(): number; readUint64(): number; rewind(bytes: number): void; seek(position: number): void; skip(bytes: number): void; } namespace StringUtils { function fromBytesAutoDetect(data: BufferSource | null): string; function fromUTF8(data: BufferSource | null): string; function fromUTF16(data: BufferSource | null, littleEndian?: boolean, opt_noThrow?: boolean): string; function toUTF8(str: string): ArrayBuffer; } namespace FakeEventTarget { type ListenerType = (evt: Event) => boolean | undefined | void; } class FakeEventTarget { /** * A work-alike for EventTarget. Only DOM elements may be true * EventTargets, but this can be used as a base class to * provide event dispatch to non-DOM classes. Only FakeEvents * should be dispatched. */ constructor(); /** * Add an event listener to this object. * * @param type The event type to listen for. * @param listener The callback or listener object to invoke. * @param options Ignored. */ addEventListener( type: string, listener: FakeEventTarget.ListenerType, options?: AddEventListenerOptions ): void; /** * Dispatch an event from this object * * @returns `true` if the default action was prevented */ dispatchEvent(event: Event): boolean; /** * Remove an event listener from this object. * * @param type The event type for which you wish to remove a listener * @param listener The callback or listener object to remove. * @param options Ignored. */ removeEventListener( type: string, listener: FakeEventTarget.ListenerType, options?: EventListenerOptions | boolean ): void; } interface IDestroyable { /** * Request that this object be destroyed, releasing all resources * and shutting down all operations. Returns a Promise which is * resolved when destruction is complete. This Promise should * never be rejected. */ destroy(): Promise<unknown>; } class Error { constructor(severity: Error.Severity, category: Error.Category, code: Error.Code, ...var_args: unknown); data: Array<unknown>; category: util.Error.Category; severity: util.Error.Severity; code: util.Error.Code; handled: boolean; message: string; stack: string; } namespace Error { // For full description, @see: https://shaka-player-demo.appspot.com/docs/api/shaka.util.Error.html#.Category enum Category { NETWORK = 1, TEXT = 2, MEDIA = 3, MANIFEST = 4, STREAMING = 5, DRM = 6, PLAYER = 7, CAST = 8, STORAGE = 9, } // For full description, @see: https://shaka-player-demo.appspot.com/docs/api/shaka.util.Error.html#.Severity enum Severity { RECOVERABLE = 1, CRITICAL = 2, } // For full description, @see: https://shaka-player-demo.appspot.com/docs/api/shaka.util.Error.html#.Code enum Code { UNSUPPORTED_SCHEME = 1000, BAD_HTTP_STATUS = 1001, HTTP_ERROR = 1002, TIMEOUT = 1003, MALFORMED_DATA_URI = 1004, UNKNOWN_DATA_URI_ENCODING = 1005, REQUEST_FILTER_ERROR = 1006, RESPONSE_FILTER_ERROR = 1007, MALFORMED_TEST_URI = 1008, UNEXPECTED_TEST_REQUEST = 1009, INVALID_TEXT_HEADER = 2000, INVALID_TEXT_CUE = 2001, UNABLE_TO_DETECT_ENCODING = 2003, BAD_ENCODING = 2004, INVALID_XML = 2005, INVALID_MP4_TTML = 2007, INVALID_MP4_VTT = 2008, UNABLE_TO_EXTRACT_CUE_START_TIME = 2009, BUFFER_READ_OUT_OF_BOUNDS = 3000, JS_INTEGER_OVERFLOW = 3001, EBML_OVERFLOW = 3002, EBML_BAD_FLOATING_POINT_SIZE = 3003, MP4_SIDX_WRONG_BOX_TYPE = 3004, MP4_SIDX_INVALID_TIMESCALE = 3005, MP4_SIDX_TYPE_NOT_SUPPORTED = 3006, WEBM_CUES_ELEMENT_MISSING = 3007, WEBM_EBML_HEADER_ELEMENT_MISSING = 3008, WEBM_SEGMENT_ELEMENT_MISSING = 3009, WEBM_INFO_ELEMENT_MISSING = 3010, WEBM_DURATION_ELEMENT_MISSING = 3011, WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING = 3012, WEBM_CUE_TIME_ELEMENT_MISSING = 3013, MEDIA_SOURCE_OPERATION_FAILED = 3014, MEDIA_SOURCE_OPERATION_THREW = 3015, VIDEO_ERROR = 3016, QUOTA_EXCEEDED_ERROR = 3017, TRANSMUXING_FAILED = 3018, UNABLE_TO_GUESS_MANIFEST_TYPE = 4000, DASH_INVALID_XML = 4001, DASH_NO_SEGMENT_INFO = 4002, DASH_EMPTY_ADAPTATION_SET = 4003, DASH_EMPTY_PERIOD = 4004, DASH_WEBM_MISSING_INIT = 4005, DASH_UNSUPPORTED_CONTAINER = 4006, DASH_PSSH_BAD_ENCODING = 4007, DASH_NO_COMMON_KEY_SYSTEM = 4008, DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED = 4009, DASH_CONFLICTING_KEY_IDS = 4010, UNPLAYABLE_PERIOD = 4011, RESTRICTIONS_CANNOT_BE_MET = 4012, NO_PERIODS = 4014, HLS_PLAYLIST_HEADER_MISSING = 4015, INVALID_HLS_TAG = 4016, HLS_INVALID_PLAYLIST_HIERARCHY = 4017, DASH_DUPLICATE_REPRESENTATION_ID = 4018, HLS_MULTIPLE_MEDIA_INIT_SECTIONS_FOUND = 4020, HLS_COULD_NOT_GUESS_MIME_TYPE = 4021, HLS_MASTER_PLAYLIST_NOT_PROVIDED = 4022, HLS_REQUIRED_ATTRIBUTE_MISSING = 4023, HLS_REQUIRED_TAG_MISSING = 4024, HLS_COULD_NOT_GUESS_CODECS = 4025, HLS_KEYFORMATS_NOT_SUPPORTED = 4026, DASH_UNSUPPORTED_XLINK_ACTUATE = 4027, DASH_XLINK_DEPTH_LIMIT = 4028, HLS_COULD_NOT_PARSE_SEGMENT_START_TIME = 4030, CONTENT_UNSUPPORTED_BY_BROWSER = 4032, CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM = 4033, INVALID_STREAMS_CHOSEN = 5005, NO_RECOGNIZED_KEY_SYSTEMS = 6000, REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE = 6001, FAILED_TO_CREATE_CDM = 6002, FAILED_TO_ATTACH_TO_VIDEO = 6003, INVALID_SERVER_CERTIFICATE = 6004, FAILED_TO_CREATE_SESSION = 6005, FAILED_TO_GENERATE_LICENSE_REQUEST = 6006, LICENSE_REQUEST_FAILED = 6007, LICENSE_RESPONSE_REJECTED = 6008, ENCRYPTED_CONTENT_WITHOUT_DRM_INFO = 6010, NO_LICENSE_SERVER_GIVEN = 6012, OFFLINE_SESSION_REMOVED = 6013, EXPIRED = 6014, LOAD_INTERRUPTED = 7000, OPERATION_ABORTED = 7001, NO_VIDEO_ELEMENT = 7002, CAST_API_UNAVAILABLE = 8000, NO_CAST_RECEIVERS = 8001, ALREADY_CASTING = 8002, UNEXPECTED_CAST_ERROR = 8003, CAST_CANCELED_BY_USER = 8004, CAST_CONNECTION_TIMED_OUT = 8005, CAST_RECEIVER_APP_UNAVAILABLE = 8006, STORAGE_NOT_SUPPORTED = 9000, INDEXED_DB_ERROR = 9001, DEPRECATED_OPERATION_ABORTED = 9002, REQUESTED_ITEM_NOT_FOUND = 9003, MALFORMED_OFFLINE_URI = 9004, CANNOT_STORE_LIVE_OFFLINE = 9005, STORE_ALREADY_IN_PROGRESS = 9006, NO_INIT_DATA_FOR_OFFLINE = 9007, LOCAL_PLAYER_INSTANCE_REQUIRED = 9008, NEW_KEY_OPERATION_NOT_SUPPORTED = 9011, KEY_NOT_FOUND = 9012, MISSING_STORAGE_CELL = 9013, } } } namespace extern { type ProgressUpdated = (duration: number, downloadedBytes: number, remainingBytes: number) => void; type RequestFilter = (type: net.NetworkingEngine.RequestType, request: Request) => void | Promise<unknown>; type ResponseFilter = (type: net.NetworkingEngine.RequestType, response: Response) => void | Promise<unknown>; type SchemePlugin = ( uri: string, request: Request, type: net.NetworkingEngine.RequestType, progressUpdated?: ProgressUpdated ) => IAbortableOperation<Response>; // @see: https://shaka-player-demo.appspot.com/docs/api/shakaExtern.html#.Request interface Request { /** * An array of URIs to attempt. They will be tried in the order * they are given. */ uris: string[]; /** The HTTP method to use for the request. */ method: string; /** The body of the request. */ body?: BufferSource; /** A mapping of headers for the request. e.g.: {"HEADER": "VALUE"} */ headers?: { [key: string]: string }; /** * Make requests with credentials. This will allow cookies in * cross-site requests. * * @see https://bit.ly/CorsCred */ allowCrossSiteCredentials?: boolean; /** An object used to define how often to make retries.*/ retryParameters?: extern.RetryParameters; /** * If this is a LICENSE request, this field contains the type of license * request it is (not the type of license). This is the `messageType` field * of the EME message. For example, this could be `license-request` or * `license-renewal` */ licenseRequestType?: string | null; /** * If this is a LICENSE request, this field contains the session ID of the * EME session that made the request. */ sessionId?: string | null; } interface Response { /** * The URI which was loaded. Request filters and server redirects * can cause this to be different from the original request URIs. */ uri: string; /** * The original URI passed to the browser for networking. This is * before any redirects, but after request filters are executed. */ originalUri: string; /** The body of the response.*/ data: ArrayBuffer; /** * A map of response headers, if supported by the underlying protocol. * All keys should be lowercased. For HTTP/HTTPS, may not be available * cross-origin. */ headers: { [key: string]: string }; /** * The time it took to get the response, in miliseconds. If not * given, NetworkingEngine will calculate it using Date.now. */ timeMs?: number; /** * If true, this response was from a cache and should be ignored * for bandwidth estimation. */ fromCache?: boolean; } /** Parameters for retrying requests. */ interface RetryParameters { /** The maximum number of times the request should be attempted. */ maxAttempts?: number; /** The delay before the first retry, in milliseconds. */ baseDelay?: number; /** The multiplier for successive retry delays. */ backoffFactor?: number; /** The maximum amount of fuzz to apply to each retry delay. For example, 0.5 means "between 50% below and 50% above the retry delay." */ fuzzFactor?: number; /** The request timeout, in milliseconds. Zero means "unlimited". */ timeout?: number; } interface SupportType { manifest: { [key: string]: boolean }; media: { [key: string]: boolean }; drm: { [key: string]: extern.DrmSupportType }; } interface DrmSupportType { persistentState: boolean; } interface IAbortableOperation<T> { /** * A Promise which represents the underlying operation. It is resolved * when the operation is complete, and rejected if the operation fails * or is aborted. Aborted operations should be rejected with a * `shaka.util.Error` object using the error code `OPERATION_ABORTED`. */ promise: Promise<T>; /** * Can be called by anyone holding this object to abort the underlying * operation. This is not cancelation, and will not necessarily result * in any work being undone. `abort()` should return a Promise which is * resolved when the underlying operation has been aborted. The * returned Promise should never be rejected. */ abort(): Promise<unknown>; /** * @param onFinal A callback to be invoked after the operation succeeds * or fails. The boolean argument is true if the * operation succeeded and false if it failed. */ finally(onFinal: (arg: boolean) => void): ThisType<T>; } // @see https://shaka-player-demo.appspot.com/docs/api/shakaExtern.html#.Track interface Track { id: number; active: boolean; type: string; bandwidth: number; language: string; primary: boolean; roles: string[]; label: string | null; kind: string | null; width: number | null; height: number | null; frameRate: number | null; mimeType: string | null; codecs: string | null; audioCodec: string | null; videoCodec: string | null; videoId: number | null; audioId: number | null; channelsCount: number | null; audioBandwidth: number | null; videoBandwidth: number | null; } const enum WidevineDrmRobustness { SW_SECURE_CRYPTO = "SW_SECURE_CRYPTO", SW_SECURE_DECODE = "SW_SECURE_DECODE", HW_SECURE_CRYPTO = "HW_SECURE_CRYPTO", HW_SECURE_DECODE = "HW_SECURE_DECODE", HW_SECURE_ALL = "HW_SECURE_ALL", } interface DrmInfo { keySystem: string; licenseServerUri: string; distinctiveIdentifierRequired?: boolean; persistentStateRequired?: boolean; // Widevine specific or other strings audioRobustness?: WidevineDrmRobustness | string; videoRobustness?: WidevineDrmRobustness | string; serverCertificate?: Uint8Array | null; initData?: InitDataOverride[]; keyIds?: string[]; } interface DrmSupportType { persistentState: boolean; } interface InitDataOverride { initData: Uint8Array; initDataType: string; keyId: string | null; } interface LanguageRole { language: string; role: string; } interface BufferedInfo { total: BufferedRange[]; audio: BufferedRange[]; video: BufferedRange[]; text: BufferedRange[]; } interface BufferedRange { start: number; // seconds end: number; // seconds } interface PlayerConfiguration { drm?: DrmConfiguration; manifest?: ManifestConfiguration; streaming?: StreamingConfiguration; abrFactory?: AbrManager.Factory; abr?: AbrConfiguration; preferredAudioLanguage?: string; preferredTextLanguage?: string; preferredVariantRole?: string; preferredTextRole?: string; preferredAudioChannelCount?: number; restrictions?: Restrictions; playRangeStart?: number; playRangeEnd?: number; textDisplayFactory?: TextDisplayer.Factory; } interface DrmConfiguration { retryParameters?: RetryParameters; servers?: { [key: string]: string }; clearKeys?: { [key: string]: string }; delayLicenseRequestUntilPlayer?: boolean; advanced?: { [key: string]: AdvancedDrmConfiguration }; } interface AdvancedDrmConfiguration { distinciveIdentifierRequired?: boolean; persistendStateRequired?: boolean; videoRobustness?: string; audioRobustness?: string; serverCertificate?: Uint8Array | null; } interface ManifestConfiguration { retryParameters: RetryParameters; availabilityWindowOverride: number; // seconds dash: DashManifestConfiguration; } interface DashManifestConfiguration { customScheme: DashContentProtectionCallback; clockSyncUri: string; ignoreDrmInfo?: boolean; xlinkFailGracefully?: boolean; defaultPresentationDelay: number; } type DashContentProtectionCallback = (e: Element) => Array<DrmInfo>; interface StreamingConfiguration { retryParameters?: RetryParameters; failureCallback?: () => void; rebufferingGoal?: number; // seconds bufferingGoal?: number; bufferBehind?: number; ignoreTextStreamFailures?: boolean; smallGapLimit?: number; // seconds jumpLargeGaps?: boolean; durationBackoff?: number; alwaysStreamText?: boolean; startAtSegmentBoundary?: boolean; forceTransmuxTS?: boolean; safeSeekOffset?: number; stallEnabled?: boolean; stallThreshold?: number; stallSkip?: boolean; useNativeHlsOnSafari?: boolean; } interface Variant { id: number; language?: string; primary?: boolean; audio: Stream | null; video: Stream | null; bandwidth: number; drmInfos?: DrmInfo[]; allowedByApplication?: boolean; allowerByKeySystem?: boolean; } interface Stream { id: number; createSegmentIndex: CreateSegmentIndexFunction; findSegmentPosition: FindSegmentPositionFunction; getSegmentReference: GetSegmentReferenceFunction; initSegmentReference: media.initSegmentReference; presentationTimeOffset?: number | undefined; mimeType: string; codecs?: string; frameRage?: number | undefined; bandwidth?: number | undefined; width?: number | undefined; height?: number | undefined; kind?: string | undefined; encrypted?: boolean; keyId?: string | null; language: string; label: string | null; type: string; primary?: boolean; trickModeVideo: extern.Stream; containsEmsgBoxes?: boolean; roles: string[]; channelsCount: number | null; segmentIndex: media.SegmentIndex; } type CreateSegmentIndexFunction = () => Promise<media.SegmentIndex>; type FindSegmentPositionFunction = (number: number) => number; type GetSegmentReferenceFunction = (number: number) => media.SegmentReference | null; namespace AbrManager { type Factory = (newAbr: AbrManager) => void; type SwitchCallback = (variant: Variant, dataFromBuffer?: boolean) => void; } interface AbrManager { chooseVariant(): Variant; configure(config: extern.AbrConfiguration): void; disable(): void; enable(): void; getBandwidthEstimate(): number; init(switchCallback: AbrManager.SwitchCallback): void; segmentDownloaded(deltaTimeMs: number, numBytes: number): void; setVariants(variants: Variant[]): void; stop(): void; } interface AbrConfiguration { enabled?: boolean; defaultBandwidthEstimate: number; restrictions: Restrictions; switchInterval: number; bandwidthUpgradeTarget: number; bandwidthDowngradeTarget: number; } interface Restrictions { minWidth: number; maxWidth: number; minHeight: number; maxHeight: number; mixPixels: number; maxPixels: number; minBandwidth: number; maxBandwidth: number; } namespace TextDisplayer { type Factory = (newTD: TextDisplayer) => void; } interface TextDisplayer extends util.IDestroyable { append(cues: text.Cue[]): void; isTextVisible(): boolean; remove(startTime: number, endTime: number): boolean; setTextVisibility(on: boolean): void; } interface CueRegion { height: number; heightUnits: text.CueRegion.units; id: string; regionAnchorX: number; regionAnchorY: number; scroll: text.CueRegion.scrollMode; viewportAnchorUnits: text.CueRegion.units; viewportAnchorX: number; viewportAnchorY: number; width: number; widthUnits: text.CueRegion.units; } interface Manifest { presentationTimeline: media.PresentationTimeline; periods: Period[]; offlineSessionids: string[]; minBufferTime: number; } interface Period { startTime: number; variants: Variant[]; textStreams: extern.Stream[]; } interface Stats { width: number; height: number; streamBandwidth: number; decodedFrames: number; droppedFrames: number; estimatedBandwidth: number; loadLatency: number; playTime: number; bufferingTime: number; switchHistory: TrackChoice[]; stateHistory: StateChange[]; } interface TrackChoice { timestamp: number; id: number; type: "variant" | "text"; fromAdaptation: boolean; bandwidth: number | null; } interface StateChange { timestamp: number; state: string; duration: number; } interface EmsgInfo { /** Identifies the message scheme. */ schemeIdUri: string; /** Specifies the value for the event. */ value: string; /** The time that the event starts (in presentation time). */ startTime: number; /** The time that the event ends (in presentation time). */ endTime: number; /** Provides the timescale, in ticks per second. */ timescale: number; /** The offset that the event starts, relative to the start of the segment this is contained in (in units of timescale). */ presentationTimeDelta: number; /** The duration of the event (in units of timescale). */ eventDuration: number; /** A field identifying this instance of the message. */ id: number; /** Body of the message. */ messageData: Uint8Array; } interface HlsManifestConfiguration { /** If true, ignore any errors in a text stream and filter out those streams. */ ignoreTextStreamFailures: boolean; } namespace ManifestParser { type Factory = (newManifest: ManifestParser) => void; interface PlayerInterface { networkingEngine: net.NetworkingEngine; filterNewPeriod: (period: Period) => void; filterAllperiods: (periods: Period[]) => void; onTimelineRegionAdded: (tri: TimelineRegionInfo) => void; onEvent: (evt: Event) => void; onError: (error: util.Error) => void; } } interface ManifestParser { configure(config: ManifestConfiguration): void; onExpirationUpdated(sessionId: string, expiration: number): void; start(uri: string, playerInterface: ManifestParser.PlayerInterface): Promise<Manifest>; stop(): Promise<unknown>; update(): void; } interface TimelineRegionInfo {} } namespace hls { class HlsParser implements extern.ManifestParser { configure(config: ManifestConfiguration): void; onExpirationUpdated(sessionId: string, expiration: number): void; start(uri: string, playerInterface: ManifestParser.PlayerInterface): Promise<Manifest>; stop(): Promise<unknown>; update(): void; } } namespace dash { class DashParser implements extern.ManifestParser { configure(config: ManifestConfiguration): void; onExpirationUpdated(sessionId: string, expiration: number): void; start(uri: string, playerInterface: ManifestParser.PlayerInterface): Promise<Manifest>; stop(): Promise<unknown>; update(): void; } } }
the_stack
import { createFetchFn, FetchFn } from '@stacks/network'; import * as bitcoin from 'bitcoinjs-lib'; import blockstack from 'blockstack'; import { BlockstackNetwork } from 'blockstack/lib/network'; import { CLI_CONFIG_TYPE } from './argparse'; export interface CLI_NETWORK_OPTS { consensusHash: string | null; feeRate: number | null; namespaceBurnAddress: string | null; priceToPay: string | null; priceUnits: string | null; receiveFeesPeriod: number | null; gracePeriod: number | null; altAPIUrl: string | null; altTransactionBroadcasterUrl: string | null; nodeAPIUrl: string | null; } export interface PriceType { units: 'BTC' | 'STACKS'; amount: bigint; } export type NameInfoType = { address: string; blockchain?: string; did?: string; expire_block?: number; grace_period?: number; last_txid?: string; renewal_deadline?: number; resolver?: string | null; status?: string; zonefile?: string | null; zonefile_hash?: string | null; }; /* * Adapter class that allows us to use data obtained * from the CLI. */ export class CLINetworkAdapter { consensusHash: string | null; feeRate: number | null; namespaceBurnAddress: string | null; priceToPay: string | null; priceUnits: string | null; gracePeriod: number | null; receiveFeesPeriod: number | null; nodeAPIUrl: string; optAlwaysCoerceAddress: boolean; legacyNetwork: BlockstackNetwork; constructor(network: BlockstackNetwork, opts: CLI_NETWORK_OPTS) { const optsDefault: CLI_NETWORK_OPTS = { consensusHash: null, feeRate: null, namespaceBurnAddress: null, priceToPay: null, priceUnits: null, receiveFeesPeriod: null, gracePeriod: null, altAPIUrl: opts.nodeAPIUrl, altTransactionBroadcasterUrl: network.broadcastServiceUrl, nodeAPIUrl: opts.nodeAPIUrl, }; opts = Object.assign({}, optsDefault, opts); this.legacyNetwork = new BlockstackNetwork( opts.nodeAPIUrl!, opts.altTransactionBroadcasterUrl!, network.btc, network.layer1 ); this.consensusHash = opts.consensusHash; this.feeRate = opts.feeRate; this.namespaceBurnAddress = opts.namespaceBurnAddress; this.priceToPay = opts.priceToPay; this.priceUnits = opts.priceUnits; this.receiveFeesPeriod = opts.receiveFeesPeriod; this.gracePeriod = opts.gracePeriod; this.nodeAPIUrl = opts.nodeAPIUrl!; this.optAlwaysCoerceAddress = false; } isMainnet(): boolean { return this.legacyNetwork.layer1.pubKeyHash === bitcoin.networks.bitcoin.pubKeyHash; } isTestnet(): boolean { return this.legacyNetwork.layer1.pubKeyHash === bitcoin.networks.testnet.pubKeyHash; } setCoerceMainnetAddress(value: boolean) { this.optAlwaysCoerceAddress = value; } coerceMainnetAddress(address: string): string { const addressInfo = bitcoin.address.fromBase58Check(address); const addressHash = addressInfo.hash; const addressVersion = addressInfo.version; let newVersion = 0; if (addressVersion === this.legacyNetwork.layer1.pubKeyHash) { newVersion = 0; } else if (addressVersion === this.legacyNetwork.layer1.scriptHash) { newVersion = 5; } return bitcoin.address.toBase58Check(addressHash, newVersion); } getFeeRate(): Promise<number> { if (this.feeRate) { // override with CLI option return Promise.resolve(this.feeRate); } return this.legacyNetwork.getFeeRate(); } getConsensusHash(): Promise<string> { // override with CLI option if (this.consensusHash) { return new Promise((resolve: any) => resolve(this.consensusHash)); } return this.legacyNetwork.getConsensusHash().then((c: string) => c); } getGracePeriod(): Promise<number> { if (this.gracePeriod) { return new Promise((resolve: any) => resolve(this.gracePeriod)); } return this.legacyNetwork.getGracePeriod().then((g: number) => g); } getNamePrice(name: string): Promise<PriceType> { // override with CLI option if (this.priceUnits && this.priceToPay) { return new Promise((resolve: any) => resolve({ units: String(this.priceUnits), amount: BigInt(this.priceToPay || 0), } as PriceType) ); } // @ts-ignore return this.legacyNetwork.getNamePrice(name).then((priceInfo: PriceType) => { // use v2 scheme if (!priceInfo.units) { priceInfo = { units: 'BTC', amount: BigInt(priceInfo.amount), }; } return priceInfo; }); } getNamespacePrice(namespaceID: string): Promise<PriceType> { // override with CLI option if (this.priceUnits && this.priceToPay) { return new Promise((resolve: any) => resolve({ units: String(this.priceUnits), amount: BigInt(this.priceToPay || 0), } as PriceType) ); } // @ts-ignore return super.getNamespacePrice(namespaceID).then((priceInfo: PriceType) => { // use v2 scheme if (!priceInfo.units) { priceInfo = { units: 'BTC', amount: BigInt(priceInfo.amount), } as PriceType; } return priceInfo; }); } getNamespaceBurnAddress( namespace: string, useCLI: boolean = true, receiveFeesPeriod: number = -1, fetchFn: FetchFn = createFetchFn() ): Promise<string> { // override with CLI option if (this.namespaceBurnAddress && useCLI) { return new Promise((resolve: any) => resolve(this.namespaceBurnAddress)); } return Promise.all([ fetchFn(`${this.legacyNetwork.blockstackAPIUrl}/v1/namespaces/${namespace}`), this.legacyNetwork.getBlockHeight(), ]) .then(([resp, blockHeight]: [any, number]) => { if (resp.status === 404) { throw new Error(`No such namespace '${namespace}'`); } else if (resp.status !== 200) { throw new Error(`Bad response status: ${resp.status}`); } else { return Promise.all([resp.json(), blockHeight]); } }) .then(([namespaceInfo, blockHeight]: [any, number]) => { let address = '1111111111111111111114oLvT2'; // default burn address if (namespaceInfo.version === 2) { // pay-to-namespace-creator if this namespace is less than $receiveFeesPeriod blocks old if (receiveFeesPeriod < 0) { receiveFeesPeriod = this.receiveFeesPeriod!; } // eslint-disable-next-line @typescript-eslint/restrict-plus-operands if (namespaceInfo.reveal_block + receiveFeesPeriod > blockHeight) { address = namespaceInfo.address; } } return address; }) .then((address: string) => this.legacyNetwork.coerceAddress(address)); } getNameInfo(name: string): Promise<NameInfoType> { // optionally coerce addresses return this.legacyNetwork.getNameInfo(name).then((ni: any) => { const nameInfo: NameInfoType = { address: this.optAlwaysCoerceAddress ? this.coerceMainnetAddress(ni.address) : ni.address, blockchain: ni.blockchain, did: ni.did, expire_block: ni.expire_block, grace_period: ni.grace_period, last_txid: ni.last_txid, renewal_deadline: ni.renewal_deadline, resolver: ni.resolver, status: ni.status, zonefile: ni.zonefile, zonefile_hash: ni.zonefile_hash, }; return nameInfo; }); } getBlockchainNameRecord(name: string, fetchFn: FetchFn = createFetchFn()): Promise<any> { // TODO: send to blockstack.js const url = `${this.legacyNetwork.blockstackAPIUrl}/v1/blockchains/bitcoin/names/${name}`; return fetchFn(url) .then(resp => { if (resp.status !== 200) { throw new Error(`Bad response status: ${resp.status}`); } else { return resp.json(); } }) .then(nameInfo => { // coerce all addresses const fixedAddresses: Record<string, any> = {}; for (const addrAttr of ['address', 'importer_address', 'recipient_address']) { if (nameInfo.hasOwnProperty(addrAttr) && nameInfo[addrAttr]) { fixedAddresses[addrAttr] = this.legacyNetwork.coerceAddress(nameInfo[addrAttr]); } } return Object.assign(nameInfo, fixedAddresses); }); } getNameHistory( name: string, page: number, fetchFn: FetchFn = createFetchFn() ): Promise<Record<string, any[]>> { // TODO: send to blockstack.js const url = `${this.legacyNetwork.blockstackAPIUrl}/v1/names/${name}/history?page=${page}`; return fetchFn(url) .then(resp => { if (resp.status !== 200) { throw new Error(`Bad response status: ${resp.status}`); } return resp.json(); }) .then(historyInfo => { // coerce all addresses const fixedHistory: Record<string, any[]> = {}; for (const historyBlock of Object.keys(historyInfo)) { const fixedHistoryList: any[] = []; for (const historyEntry of historyInfo[historyBlock]) { const fixedAddresses: Record<string, string> = {}; let fixedHistoryEntry: any = {}; for (const addrAttr of ['address', 'importer_address', 'recipient_address']) { if (historyEntry.hasOwnProperty(addrAttr) && historyEntry[addrAttr]) { fixedAddresses[addrAttr] = this.legacyNetwork.coerceAddress(historyEntry[addrAttr]); } } fixedHistoryEntry = Object.assign(historyEntry, fixedAddresses); fixedHistoryList.push(fixedHistoryEntry); } fixedHistory[historyBlock] = fixedHistoryList; } return fixedHistory; }); } coerceAddress(address: string) { return this.legacyNetwork.coerceAddress(address); } getAccountHistoryPage(address: string, page: number) { return this.legacyNetwork.getAccountHistoryPage(address, page); } broadcastTransaction(tx: string) { return this.legacyNetwork.broadcastTransaction(tx); } broadcastZoneFile(zonefile: string, txid: string) { return this.legacyNetwork.broadcastZoneFile(zonefile, txid); } getNamesOwned(address: string) { return this.legacyNetwork.getNamesOwned(address); } } /* * Instantiate a network using settings from the config file. */ export function getNetwork(configData: CLI_CONFIG_TYPE, testNet: boolean): BlockstackNetwork { if (testNet) { const network = new blockstack.network.LocalRegtest( configData.blockstackAPIUrl, configData.broadcastServiceUrl, new blockstack.network.BitcoindAPI(configData.utxoServiceUrl, { username: configData.bitcoindUsername || 'blockstack', password: configData.bitcoindPassword || 'blockstacksystem', }) ); return network; } else { const network = new BlockstackNetwork( configData.blockstackAPIUrl, configData.broadcastServiceUrl, new blockstack.network.BlockchainInfoApi(configData.utxoServiceUrl) ); return network; } }
the_stack
namespace AMDLoader { export interface AnnotatedLoadingError extends Error { phase: 'loading'; moduleId: string; neededBy: string[]; } export interface AnnotatedFactoryError extends Error { phase: 'factory'; moduleId: string; neededBy: string[]; } export interface AnnotatedValidationError extends Error { phase: 'configuration'; } export type AnnotatedError = AnnotatedLoadingError | AnnotatedFactoryError | AnnotatedValidationError; export function ensureError<T extends Error>(err: any): T { if (err instanceof Error) { return <T>err; } const result = new Error(err.message || String(err) || 'Unknown Error'); if (err.stack) { result.stack = err.stack; } return <T>result; } /** * The signature for the loader's AMD "define" function. */ export interface IDefineFunc { (id: 'string', dependencies: string[], callback: any): void; (id: 'string', callback: any): void; (dependencies: string[], callback: any): void; (callback: any): void; amd: { jQuery: boolean; }; } /** * The signature for the loader's AMD "require" function. */ export interface IRequireFunc { (module: string): any; (config: any): void; (modules: string[], callback: Function): void; (modules: string[], callback: Function, errorback: (err: any) => void): void; config(params: IConfigurationOptions, shouldOverwrite?: boolean): void; getConfig(): IConfigurationOptions; /** * Non standard extension to reset completely the loader state. This is used for running amdjs tests */ reset(): void; /** * Non standard extension to fetch loader state for building purposes. */ getBuildInfo(): IBuildModuleInfo[] | null; /** * Non standard extension to fetch loader events */ getStats(): LoaderEvent[]; /** * The define function */ define(id: 'string', dependencies: string[], callback: any): void; define(id: 'string', callback: any): void; define(dependencies: string[], callback: any): void; define(callback: any): void; } export interface IModuleConfiguration { [key: string]: any; } export interface INodeRequire { (nodeModule: string): any; main: { filename: string; }; } export interface INodeCachedDataConfiguration { /** * Directory path in which cached is stored. */ path: string; /** * Seed when generating names of cache files. */ seed?: string; /** * Optional delay for filesystem write/delete operations */ writeDelay?: number; }; export interface IConfigurationOptions { /** * The prefix that will be aplied to all modules when they are resolved to a location */ baseUrl?: string; /** * Redirect rules for modules. The redirect rules will affect the module ids themselves */ paths?: { [path: string]: any; }; /** * Per-module configuration */ config?: { [moduleId: string]: IModuleConfiguration }; /** * Catch errors when invoking the module factories */ catchError?: boolean; /** * Record statistics */ recordStats?: boolean; /** * The suffix that will be aplied to all modules when they are resolved to a location */ urlArgs?: string; /** * Callback that will be called when errors are encountered */ onError?: (err: AnnotatedError) => void; /** * The loader will issue warnings when duplicate modules are encountered. * This list will inhibit those warnings if duplicate modules are expected. */ ignoreDuplicateModules?: string[]; /** * Flag to indicate if current execution is as part of a build. Used by plugins */ isBuild?: boolean; /** * Content Security Policy nonce value used to load child scripts. */ cspNonce?: string; /** * If running inside an electron renderer, prefer using <script> tags to load code. * Defaults to false. */ preferScriptTags?: boolean; /** * A trusted types policy which will be used to create TrustedScriptURL-values. * https://w3c.github.io/webappsec-trusted-types/dist/spec/#introduction. */ trustedTypesPolicy?: { createScriptURL(value: string): string & object; createScript(_: string, value: string): string; }; /** * A regex to help determine if a module is an AMD module or a node module. * If defined, then all amd modules in the system must match this regular expression. */ amdModulesPattern?: RegExp; /** * A list of known node modules that should be directly loaded via node's require. */ nodeModules?: string[]; /** * The main entry point node's require */ nodeRequire?: INodeRequire; /** * An optional transformation applied to the source before it is loaded in node's vm */ nodeInstrumenter?: (source: string, vmScriptSrc: string) => string; /** * The main entry point. */ nodeMain?: string; /** * Support v8 cached data (http://v8project.blogspot.co.uk/2015/07/code-caching.html) */ nodeCachedData?: INodeCachedDataConfiguration } export interface IValidatedConfigurationOptions extends IConfigurationOptions { baseUrl: string; paths: { [path: string]: any; }; config: { [moduleId: string]: IModuleConfiguration }; catchError: boolean; recordStats: boolean; urlArgs: string; onError: (err: AnnotatedError) => void; ignoreDuplicateModules: string[]; isBuild: boolean; cspNonce: string; preferScriptTags: boolean; nodeModules: string[]; } export class ConfigurationOptionsUtil { /** * Ensure configuration options make sense */ private static validateConfigurationOptions(options: IConfigurationOptions): IValidatedConfigurationOptions { function defaultOnError(err: AnnotatedError): void { if (err.phase === 'loading') { console.error('Loading "' + err.moduleId + '" failed'); console.error(err); console.error('Here are the modules that depend on it:'); console.error(err.neededBy); return; } if (err.phase === 'factory') { console.error('The factory function of "' + err.moduleId + '" has thrown an exception'); console.error(err); console.error('Here are the modules that depend on it:'); console.error(err.neededBy); return; } } options = options || {}; if (typeof options.baseUrl !== 'string') { options.baseUrl = ''; } if (typeof options.isBuild !== 'boolean') { options.isBuild = false; } if (typeof options.paths !== 'object') { options.paths = {}; } if (typeof options.config !== 'object') { options.config = {}; } if (typeof options.catchError === 'undefined') { options.catchError = false; } if (typeof options.recordStats === 'undefined') { options.recordStats = false; } if (typeof options.urlArgs !== 'string') { options.urlArgs = ''; } if (typeof options.onError !== 'function') { options.onError = defaultOnError; } if (!Array.isArray(options.ignoreDuplicateModules)) { options.ignoreDuplicateModules = []; } if (options.baseUrl.length > 0) { if (!Utilities.endsWith(options.baseUrl, '/')) { options.baseUrl += '/'; } } if (typeof options.cspNonce !== 'string') { options.cspNonce = ''; } if (typeof options.preferScriptTags === 'undefined') { options.preferScriptTags = false; } if (!Array.isArray(options.nodeModules)) { options.nodeModules = []; } if (options.nodeCachedData && typeof options.nodeCachedData === 'object') { if (typeof options.nodeCachedData.seed !== 'string') { options.nodeCachedData.seed = 'seed'; } if (typeof options.nodeCachedData.writeDelay !== 'number' || options.nodeCachedData.writeDelay < 0) { options.nodeCachedData.writeDelay = 1000 * 7; } if (!options.nodeCachedData.path || typeof options.nodeCachedData.path !== 'string') { const err = ensureError<AnnotatedValidationError>(new Error('INVALID cached data configuration, \'path\' MUST be set')); err.phase = 'configuration'; options.onError(err); options.nodeCachedData = undefined; } } return <IValidatedConfigurationOptions>options; } public static mergeConfigurationOptions(overwrite: IConfigurationOptions | null = null, base: IConfigurationOptions | null = null): IValidatedConfigurationOptions { let result: IConfigurationOptions = Utilities.recursiveClone(base || {}); // Merge known properties and overwrite the unknown ones Utilities.forEachProperty(overwrite, (key: string, value: any) => { if (key === 'ignoreDuplicateModules' && typeof result.ignoreDuplicateModules !== 'undefined') { result.ignoreDuplicateModules = result.ignoreDuplicateModules.concat(value); } else if (key === 'paths' && typeof result.paths !== 'undefined') { Utilities.forEachProperty(value, (key2: string, value2: any) => result.paths![key2] = value2); } else if (key === 'config' && typeof result.config !== 'undefined') { Utilities.forEachProperty(value, (key2: string, value2: any) => result.config![key2] = value2); } else { result[key] = Utilities.recursiveClone(value); } }); return ConfigurationOptionsUtil.validateConfigurationOptions(result); } } export class Configuration { private readonly _env: Environment; private options: IValidatedConfigurationOptions; /** * Generated from the `ignoreDuplicateModules` configuration option. */ private ignoreDuplicateModulesMap: { [moduleId: string]: boolean; }; /** * Generated from the `nodeModules` configuration option. */ private nodeModulesMap: { [nodeModuleId: string]: boolean }; /** * Generated from the `paths` configuration option. These are sorted with the longest `from` first. */ private sortedPathsRules: { from: string; to: string[]; }[]; constructor(env: Environment, options?: IConfigurationOptions) { this._env = env; this.options = ConfigurationOptionsUtil.mergeConfigurationOptions(options); this._createIgnoreDuplicateModulesMap(); this._createNodeModulesMap(); this._createSortedPathsRules(); if (this.options.baseUrl === '') { if (this.options.nodeRequire && this.options.nodeRequire.main && this.options.nodeRequire.main.filename && this._env.isNode) { let nodeMain = this.options.nodeRequire.main.filename; let dirnameIndex = Math.max(nodeMain.lastIndexOf('/'), nodeMain.lastIndexOf('\\')); this.options.baseUrl = nodeMain.substring(0, dirnameIndex + 1); } if (this.options.nodeMain && this._env.isNode) { let nodeMain = this.options.nodeMain; let dirnameIndex = Math.max(nodeMain.lastIndexOf('/'), nodeMain.lastIndexOf('\\')); this.options.baseUrl = nodeMain.substring(0, dirnameIndex + 1); } } } private _createIgnoreDuplicateModulesMap(): void { // Build a map out of the ignoreDuplicateModules array this.ignoreDuplicateModulesMap = {}; for (let i = 0; i < this.options.ignoreDuplicateModules.length; i++) { this.ignoreDuplicateModulesMap[this.options.ignoreDuplicateModules[i]] = true; } } private _createNodeModulesMap(): void { // Build a map out of nodeModules array this.nodeModulesMap = Object.create(null); for (const nodeModule of this.options.nodeModules) { this.nodeModulesMap[nodeModule] = true; } } private _createSortedPathsRules(): void { // Create an array our of the paths rules, sorted descending by length to // result in a more specific -> less specific order this.sortedPathsRules = []; Utilities.forEachProperty(this.options.paths, (from: string, to: any) => { if (!Array.isArray(to)) { this.sortedPathsRules.push({ from: from, to: [to] }); } else { this.sortedPathsRules.push({ from: from, to: to }); } }); this.sortedPathsRules.sort((a, b) => { return b.from.length - a.from.length; }); } /** * Clone current configuration and overwrite options selectively. * @param options The selective options to overwrite with. * @result A new configuration */ public cloneAndMerge(options?: IConfigurationOptions): Configuration { return new Configuration(this._env, ConfigurationOptionsUtil.mergeConfigurationOptions(options, this.options)); } /** * Get current options bag. Useful for passing it forward to plugins. */ public getOptionsLiteral(): IValidatedConfigurationOptions { return this.options; } private _applyPaths(moduleId: string): string[] { let pathRule: { from: string; to: string[]; }; for (let i = 0, len = this.sortedPathsRules.length; i < len; i++) { pathRule = this.sortedPathsRules[i]; if (Utilities.startsWith(moduleId, pathRule.from)) { let result: string[] = []; for (let j = 0, lenJ = pathRule.to.length; j < lenJ; j++) { result.push(pathRule.to[j] + moduleId.substr(pathRule.from.length)); } return result; } } return [moduleId]; } private _addUrlArgsToUrl(url: string): string { if (Utilities.containsQueryString(url)) { return url + '&' + this.options.urlArgs; } else { return url + '?' + this.options.urlArgs; } } private _addUrlArgsIfNecessaryToUrl(url: string): string { if (this.options.urlArgs) { return this._addUrlArgsToUrl(url); } return url; } private _addUrlArgsIfNecessaryToUrls(urls: string[]): string[] { if (this.options.urlArgs) { for (let i = 0, len = urls.length; i < len; i++) { urls[i] = this._addUrlArgsToUrl(urls[i]); } } return urls; } /** * Transform a module id to a location. Appends .js to module ids */ public moduleIdToPaths(moduleId: string): string[] { if (this._env.isNode) { const isNodeModule = ( (this.nodeModulesMap[moduleId] === true) || (this.options.amdModulesPattern instanceof RegExp && !this.options.amdModulesPattern.test(moduleId)) ); if (isNodeModule) { // This is a node module... if (this.isBuild()) { // ...and we are at build time, drop it return ['empty:']; } else { // ...and at runtime we create a `shortcut`-path return ['node|' + moduleId]; } } } let result = moduleId; let results: string[]; if (!Utilities.endsWith(result, '.js') && !Utilities.isAbsolutePath(result)) { results = this._applyPaths(result); for (let i = 0, len = results.length; i < len; i++) { if (this.isBuild() && results[i] === 'empty:') { continue; } if (!Utilities.isAbsolutePath(results[i])) { results[i] = this.options.baseUrl + results[i]; } if (!Utilities.endsWith(results[i], '.js') && !Utilities.containsQueryString(results[i])) { results[i] = results[i] + '.js'; } } } else { if (!Utilities.endsWith(result, '.js') && !Utilities.containsQueryString(result)) { result = result + '.js'; } results = [result]; } return this._addUrlArgsIfNecessaryToUrls(results); } /** * Transform a module id or url to a location. */ public requireToUrl(url: string): string { let result = url; if (!Utilities.isAbsolutePath(result)) { result = this._applyPaths(result)[0]; if (!Utilities.isAbsolutePath(result)) { result = this.options.baseUrl + result; } } return this._addUrlArgsIfNecessaryToUrl(result); } /** * Flag to indicate if current execution is as part of a build. */ public isBuild(): boolean { return this.options.isBuild; } /** * Test if module `moduleId` is expected to be defined multiple times */ public isDuplicateMessageIgnoredFor(moduleId: string): boolean { return this.ignoreDuplicateModulesMap.hasOwnProperty(moduleId); } /** * Get the configuration settings for the provided module id */ public getConfigForModule(moduleId: string): IModuleConfiguration | undefined { if (this.options.config) { return this.options.config[moduleId]; } } /** * Should errors be caught when executing module factories? */ public shouldCatchError(): boolean { return this.options.catchError; } /** * Should statistics be recorded? */ public shouldRecordStats(): boolean { return this.options.recordStats; } /** * Forward an error to the error handler. */ public onError(err: AnnotatedError): void { this.options.onError(err); } } }
the_stack
import React from "react"; import Observer from "react-intersection-observer"; import { unionize, ofType, UnionOf } from "unionize"; /** * Valid props for LazyImage components */ export type CommonLazyImageProps = ImageProps & { // NOTE: if you add props here, remember to destructure them out of being // passed to the children, in the render() callback. /** Whether to skip checking for viewport and always show the 'actual' component * @see https://github.com/fpapado/react-lazy-images/#eager-loading--server-side-rendering-ssr */ loadEagerly?: boolean; /** Subset of props for the IntersectionObserver * @see https://github.com/thebuilder/react-intersection-observer#props */ observerProps?: ObserverProps; /** Use the Image Decode API; * The call to a new HTML <img> element’s decode() function returns a promise, which, * when fulfilled, ensures that the image can be appended to the DOM without causing * a decoding delay on the next frame. * @see: https://www.chromestatus.com/feature/5637156160667648 */ experimentalDecode?: boolean; /** Whether to log out internal state transitions for the component */ debugActions?: boolean; /** Delay a certain duration before starting to load, in ms. * This can help avoid loading images while the user scrolls quickly past them. * TODO: naming things. */ debounceDurationMs?: number; }; /** Valid props for LazyImageFull */ export interface LazyImageFullProps extends CommonLazyImageProps { /** Children should be either a function or a node */ children: (args: RenderCallbackArgs) => React.ReactNode; } /** Values that the render props take */ export interface RenderCallbackArgs { imageState: ImageState; imageProps: ImageProps; /** When not loading eagerly, a ref to bind to the DOM element. This is needed for the intersection calculation to work. */ ref?: React.RefObject<any>; } export interface ImageProps { /** The source of the image to load */ src: string; /** The source set of the image to load */ srcSet?: string; /** The alt text description of the image you are loading */ alt?: string; /** Sizes descriptor */ sizes?: string; } /** Subset of react-intersection-observer's props */ export interface ObserverProps { /** * Margin around the root that expands the area for intersection. * @see https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/rootMargin * @default "50px 0px" * @example Declaration same as CSS margin: * `"10px 20px 30px 40px"` (top, right, bottom, left). */ rootMargin?: string; /** Number between 0 and 1 indicating the the percentage that should be * visible before triggering. * @default `0.01` */ threshold?: number; } /** States that the image loading can be in. * Used together with LazyImageFull render props. * External representation of the internal state. * */ export enum ImageState { NotAsked = "NotAsked", Loading = "Loading", LoadSuccess = "LoadSuccess", LoadError = "LoadError" } /** The component's state */ const LazyImageFullState = unionize({ NotAsked: {}, Buffering: {}, // Could try to make it Promise<HTMLImageElement>, // but we don't use the element anyway, and we cache promises Loading: {}, LoadSuccess: {}, LoadError: ofType<{ msg: string }>() }); type LazyImageFullState = UnionOf<typeof LazyImageFullState>; /** Actions that change the component's state. * These are not unlike Actions in Redux or, the ones I'm inspired by, * Msg in Elm. */ const Action = unionize({ ViewChanged: ofType<{ inView: boolean }>(), BufferingEnded: {}, // MAYBE: Load: {}, LoadSuccess: {}, LoadError: ofType<{ msg: string }>() }); type Action = UnionOf<typeof Action>; /** Commands (Cmd) describe side-effects as functions that take the instance */ // FUTURE: These should be tied to giving back a Msg / asynchronoulsy giving a Msg with conditions type Cmd = (instance: LazyImageFull) => void; /** The output from a reducer is the next state and maybe a command */ type ReducerResult = { nextState: LazyImageFullState; cmd?: Cmd; }; ///// Commands, things that perform side-effects ///// /** Get a command that sets a buffering Promise */ const getBufferingCmd = (durationMs: number): Cmd => instance => { // Make cancelable buffering Promise const bufferingPromise = makeCancelable(delayedPromise(durationMs)); // Kick off promise chain bufferingPromise.promise .then(() => instance.update(Action.BufferingEnded())) .catch( _reason => {} //console.log({ isCanceled: _reason.isCanceled }) ); // Side-effect; set the promise in the cache instance.promiseCache.buffering = bufferingPromise; }; /** Get a command that sets an image loading Promise */ const getLoadingCmd = ( imageProps: ImageProps, experimentalDecode?: boolean ): Cmd => instance => { // Make cancelable loading Promise const loadingPromise = makeCancelable( loadImage(imageProps, experimentalDecode) ); // Kick off request for Image and attach listeners for response loadingPromise.promise .then(_res => instance.update(Action.LoadSuccess({}))) .catch(e => { // If the Loading Promise was canceled, it means we have stopped // loading due to unmount, rather than an error. if (!e.isCanceled) { // TODO: think more about the error here instance.update(Action.LoadError({ msg: "Failed to load" })); } }); // Side-effect; set the promise in the cache instance.promiseCache.loading = loadingPromise; }; /** Command that cancels the buffering Promise */ const cancelBufferingCmd: Cmd = instance => { // Side-effect; cancel the promise in the cache // We know this exists if we are in a Buffering state instance.promiseCache.buffering.cancel(); }; /** * Component that preloads the image once it is in the viewport, * and then swaps it in. Takes a render prop that allows to specify * what is rendered based on the loading state. */ export class LazyImageFull extends React.Component< LazyImageFullProps, LazyImageFullState > { static displayName = "LazyImageFull"; /** A central place to store promises. * A bit silly, but passing promsises directly in the state * was giving me weird timing issues. This way we can keep * the promises in check, and pick them up from the respective methods. * FUTURE: Could pass the relevant key in Buffering and Loading, so * that at least we know where they are from a single source. */ promiseCache: { [key: string]: CancelablePromise; } = {}; initialState = LazyImageFullState.NotAsked(); /** Emit the next state based on actions. * This is the core of the component! */ static reducer( action: Action, prevState: LazyImageFullState, props: LazyImageFullProps ): ReducerResult { return Action.match(action, { ViewChanged: ({ inView }) => { if (inView === true) { // If src is not specified, then there is nothing to preload; skip to Loaded state if (!props.src) { return { nextState: LazyImageFullState.LoadSuccess() }; // Error wtf } else { // If in view, only load something if NotAsked, otherwise leave untouched return LazyImageFullState.match(prevState, { NotAsked: () => { // If debounce is specified, then start buffering if (!!props.debounceDurationMs) { return { nextState: LazyImageFullState.Buffering(), cmd: getBufferingCmd(props.debounceDurationMs) }; } else { // If no debounce is specified, then start loading immediately return { nextState: LazyImageFullState.Loading(), cmd: getLoadingCmd(props, props.experimentalDecode) }; } }, // Do nothing in other states default: () => ({ nextState: prevState }) }); } } else { // If out of view, cancel if Buffering, otherwise leave untouched return LazyImageFullState.match(prevState, { Buffering: () => ({ nextState: LazyImageFullState.NotAsked(), cmd: cancelBufferingCmd }), // Do nothing in other states default: () => ({ nextState: prevState }) }); } }, // Buffering has ended/succeeded, kick off request for image BufferingEnded: () => ({ nextState: LazyImageFullState.Loading(), cmd: getLoadingCmd(props, props.experimentalDecode) }), // Loading the image succeeded, simple LoadSuccess: () => ({ nextState: LazyImageFullState.LoadSuccess() }), // Loading the image failed, simple LoadError: e => ({ nextState: LazyImageFullState.LoadError(e) }) }); } constructor(props: LazyImageFullProps) { super(props); this.state = this.initialState; // Bind methods this.update = this.update.bind(this); } update(action: Action) { // Get the next state and any effects const { nextState, cmd } = LazyImageFull.reducer( action, this.state, this.props ); // Debugging if (this.props.debugActions) { if (process.env.NODE_ENV === "production") { console.warn( 'You are running LazyImage with debugActions="true" in production. This might have performance implications.' ); } console.log({ action, prevState: this.state, nextState }); } // Actually set the state, and kick off any effects after that this.setState(nextState, () => cmd && cmd(this)); } componentWillUnmount() { // Clear the Promise Cache if (this.promiseCache.loading) { // NOTE: This does not cancel the request, only the callback. // We weould need fetch() and an AbortHandler for that. this.promiseCache.loading.cancel(); } if (this.promiseCache.buffering) { this.promiseCache.buffering.cancel(); } this.promiseCache = {}; } // Render function render() { // This destructuring is silly const { children, loadEagerly, observerProps, experimentalDecode, debounceDurationMs, debugActions, ...imageProps } = this.props; if (loadEagerly) { // If eager, skip the observer and view changing stuff; resolve the imageState as loaded. return children({ // We know that the state tags and the enum match up imageState: LazyImageFullState.LoadSuccess().tag as ImageState, imageProps }); } else { return ( <Observer rootMargin="50px 0px" // TODO: reconsider threshold threshold={0.01} {...observerProps} onChange={inView => this.update(Action.ViewChanged({ inView }))} > {({ ref }) => children({ // We know that the state tags and the enum match up, apart // from Buffering not being exposed imageState: this.state.tag === "Buffering" ? ImageState.Loading : (this.state.tag as ImageState), imageProps, ref }) } </Observer> ); } } } ///// Utilities ///// /** Promise constructor for loading an image */ const loadImage = ( { src, srcSet, alt, sizes }: ImageProps, experimentalDecode = false ) => new Promise((resolve, reject) => { const image = new Image(); if (srcSet) { image.srcset = srcSet; } if (alt) { image.alt = alt; } if (sizes) { image.sizes = sizes; } image.src = src; /** @see: https://www.chromestatus.com/feature/5637156160667648 */ if (experimentalDecode && "decode" in image) { return ( image // NOTE: .decode() is not in the TS defs yet // TODO: consider writing the .decode() definition and sending a PR //@ts-ignore .decode() .then((image: HTMLImageElement) => resolve(image)) .catch((err: any) => reject(err)) ); } image.onload = resolve; image.onerror = reject; }); /** Promise that resolves after a specified number of ms */ const delayedPromise = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); interface CancelablePromise { promise: Promise<{}>; cancel: () => void; } /** Make a Promise "cancelable". * * Rejects with {isCanceled: true} if canceled. * * The way this works is by wrapping it with internal hasCanceled_ state * and checking it before resolving. */ const makeCancelable = (promise: Promise<any>): CancelablePromise => { let hasCanceled_ = false; const wrappedPromise = new Promise((resolve, reject) => { promise.then( (val: any) => (hasCanceled_ ? reject({ isCanceled: true }) : resolve(val)) ); promise.catch( (error: any) => hasCanceled_ ? reject({ isCanceled: true }) : reject(error) ); }); return { promise: wrappedPromise, cancel() { hasCanceled_ = true; } }; };
the_stack
'use strict'; import Axios from 'axios'; import * as vscode from 'vscode'; import * as chai from 'chai'; import * as sinon from 'sinon'; import * as sinonChai from 'sinon-chai'; import { TestUtil } from '../TestUtil'; import { VSCodeBlockchainOutputAdapter } from '../../extension/logging/VSCodeBlockchainOutputAdapter'; import { LogType, FabricEnvironmentRegistryEntry, EnvironmentType } from 'ibm-blockchain-platform-common'; import { ExtensionCommands } from '../../ExtensionCommands'; import { FabricEnvironmentTreeItem } from '../../extension/explorer/runtimeOps/disconnectedTree/FabricEnvironmentTreeItem'; import { FabricEnvironmentManager } from '../../extension/fabric/environments/FabricEnvironmentManager'; import { UserInputUtil } from '../../extension/commands/UserInputUtil'; // tslint:disable no-unused-expression chai.should(); chai.use(sinonChai); describe('openCouchDbInBrowser', () => { const sandbox: sinon.SinonSandbox = sinon.createSandbox(); let logSpy: sinon.SinonStub; let executeStub: sinon.SinonStub; let vscodeOpenStub: sinon.SinonStub; let getConnectionStub: sinon.SinonStub; let getRegistryEntryStub: sinon.SinonStub; let envQuickPickStub: sinon.SinonStub; let axiosGetStub: sinon.SinonStub; let treeItem: FabricEnvironmentTreeItem; let registryEntry: FabricEnvironmentRegistryEntry; let environmentName: string; let environmentUrl: string; let couchDbUrl: string; before(async () => { await TestUtil.setupTests(sandbox); }); beforeEach(async () => { logSpy = sandbox.stub(VSCodeBlockchainOutputAdapter.instance(), 'log'); executeStub = sandbox.stub(vscode.commands, 'executeCommand').callThrough(); vscodeOpenStub = executeStub.withArgs('vscode.open').resolves(); getConnectionStub = sandbox.stub(FabricEnvironmentManager.instance(), 'getConnection').returns(undefined); getRegistryEntryStub = sandbox.stub(FabricEnvironmentManager.instance(), 'getEnvironmentRegistryEntry').returns(undefined); envQuickPickStub = sandbox.stub(UserInputUtil, 'showFabricEnvironmentQuickPickBox').resolves(); axiosGetStub = sandbox.stub(Axios, 'get'); environmentName = 'MicrofabEnv'; environmentUrl = 'http://console.someip:port/'; couchDbUrl = 'http://couchdb.someip:port/_utils/'; registryEntry = { name: environmentName, environmentType: EnvironmentType.MICROFAB_ENVIRONMENT, url: environmentUrl, }; treeItem = { label: environmentName, environmentRegistryEntry: registryEntry, } as unknown as FabricEnvironmentTreeItem; }); afterEach(async () => { sandbox.restore(); }); it('should open CouchDB in browser from tree', async () => { await vscode.commands.executeCommand(ExtensionCommands.OPEN_COUCHDB_IN_BROWSER, treeItem); vscodeOpenStub.should.have.been.calledOnce; axiosGetStub.should.have.been.called.calledWithExactly(couchDbUrl); getConnectionStub.should.have.not.been.called; getRegistryEntryStub.should.have.not.been.called; envQuickPickStub.should.have.not.been.called; logSpy.firstCall.should.have.been.calledWith(LogType.INFO, undefined, 'open CouchDB in browser'); logSpy.secondCall.should.have.been.calledWith(LogType.INFO, 'Default CouchDB login: Use username \'admin\' and password \'adminpw\''); logSpy.thirdCall.should.have.been.calledWith(LogType.SUCCESS, undefined, 'Successfully opened CouchDB in browser'); }); it('should open CouchDB in browser from connected environment', async () => { const localFabricRegEntry: FabricEnvironmentRegistryEntry = { name: 'LocalMicrofabEnv', environmentType: EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT, url: 'http://console.another.ip:port', }; getConnectionStub.returns(true); getRegistryEntryStub.returns(localFabricRegEntry); await vscode.commands.executeCommand(ExtensionCommands.OPEN_COUCHDB_IN_BROWSER); vscodeOpenStub.should.have.been.calledOnce; getConnectionStub.should.have.been.calledOnce; getRegistryEntryStub.should.have.been.calledOnce; envQuickPickStub.should.have.not.been.called; axiosGetStub.should.have.been.called.calledWithExactly('http://couchdb.another.ip:port/_utils/'); logSpy.firstCall.should.have.been.calledWith(LogType.INFO, undefined, 'open CouchDB in browser'); logSpy.secondCall.should.have.been.calledWith(LogType.INFO, 'Default CouchDB login: Use username \'admin\' and password \'adminpw\''); logSpy.thirdCall.should.have.been.calledWith(LogType.SUCCESS, undefined, 'Successfully opened CouchDB in browser'); }); it('should open CouchDB in browser from command palette', async () => { getConnectionStub.returns(false); envQuickPickStub.resolves({data: registryEntry}); await vscode.commands.executeCommand(ExtensionCommands.OPEN_COUCHDB_IN_BROWSER); vscodeOpenStub.should.have.been.calledOnce; getConnectionStub.should.have.been.calledOnce; getRegistryEntryStub.should.have.not.been.called; envQuickPickStub.should.have.been.calledOnce; axiosGetStub.should.have.been.called.calledWithExactly(couchDbUrl); logSpy.firstCall.should.have.been.calledWith(LogType.INFO, undefined, 'open CouchDB in browser'); logSpy.secondCall.should.have.been.calledWith(LogType.INFO, 'Default CouchDB login: Use username \'admin\' and password \'adminpw\''); logSpy.thirdCall.should.have.been.calledWith(LogType.SUCCESS, undefined, 'Successfully opened CouchDB in browser'); }); it('should handle user canceling before selecting environment when opening couchDB in browser from command palette', async () => { getConnectionStub.returns(false); await vscode.commands.executeCommand(ExtensionCommands.OPEN_COUCHDB_IN_BROWSER); vscodeOpenStub.should.have.not.been.called; getConnectionStub.should.have.been.calledOnce; getRegistryEntryStub.should.have.not.been.called; envQuickPickStub.should.have.been.calledOnce; axiosGetStub.should.have.not.been.called; logSpy.should.have.been.calledOnceWith(LogType.INFO, undefined, 'open CouchDB in browser'); }); it('should fail when environment URL not set', async () => { const noUrlTreeItem: FabricEnvironmentTreeItem = { label: environmentName, environmentRegistryEntry: { name: environmentName, environmentType: EnvironmentType.MICROFAB_ENVIRONMENT, } } as unknown as FabricEnvironmentTreeItem; const noUrlError: Error = new Error(`Microfab environment ${noUrlTreeItem.environmentRegistryEntry.name} doesn't have a URL associated with it`); await vscode.commands.executeCommand(ExtensionCommands.OPEN_COUCHDB_IN_BROWSER, noUrlTreeItem); vscodeOpenStub.should.have.not.been.called; getConnectionStub.should.have.not.been.called; getRegistryEntryStub.should.have.not.been.called; envQuickPickStub.should.have.not.been.called; axiosGetStub.should.have.not.been.called; logSpy.firstCall.should.have.been.calledWith(LogType.INFO, undefined, 'open CouchDB in browser'); logSpy.secondCall.should.have.been.calledWith(LogType.ERROR, `Error opening CouchDB in browser: ${noUrlError.message}`, `Error opening CouchDB in browser: ${noUrlError.toString()}`); }); it('should tell the user it needs microfab 0.0.8 when a 404 error is thrown from axios', async () => { const error: any = new Error(`a 404 error`); error.response = {status: 404}; axiosGetStub.rejects(error); const finalError: Error = new Error (`This functionality requires microfab v0.0.8 or above: ${error.message}`); await vscode.commands.executeCommand(ExtensionCommands.OPEN_COUCHDB_IN_BROWSER, treeItem); axiosGetStub.should.have.been.called; vscodeOpenStub.should.have.not.been.called; getConnectionStub.should.have.not.been.called; getRegistryEntryStub.should.have.not.been.called; envQuickPickStub.should.have.not.been.called; logSpy.firstCall.should.have.been.calledWith(LogType.INFO, undefined, 'open CouchDB in browser'); logSpy.secondCall.should.have.been.calledWith(LogType.ERROR, `Error opening CouchDB in browser: ${finalError.message}`, `Error opening CouchDB in browser: ${finalError.toString()}`); }); it('should fail when an error is thrown from axios', async () => { const error: Error = new Error(`some axios error`); axiosGetStub.rejects(error); await vscode.commands.executeCommand(ExtensionCommands.OPEN_COUCHDB_IN_BROWSER, treeItem); axiosGetStub.should.have.been.called; vscodeOpenStub.should.have.not.been.called; getConnectionStub.should.have.not.been.called; getRegistryEntryStub.should.have.not.been.called; envQuickPickStub.should.have.not.been.called; logSpy.firstCall.should.have.been.calledWith(LogType.INFO, undefined, 'open CouchDB in browser'); logSpy.secondCall.should.have.been.calledWith(LogType.ERROR, `Error opening CouchDB in browser: ${error.message}`, `Error opening CouchDB in browser: ${error.toString()}`); }); it('should fail when an error is thrown from vscode.open', async () => { const error: Error = new Error(`some error`); vscodeOpenStub.rejects(error); await vscode.commands.executeCommand(ExtensionCommands.OPEN_COUCHDB_IN_BROWSER, treeItem); axiosGetStub.should.have.been.called; vscodeOpenStub.should.have.been.called; getConnectionStub.should.have.not.been.called; getRegistryEntryStub.should.have.not.been.called; envQuickPickStub.should.have.not.been.called; logSpy.firstCall.should.have.been.calledWith(LogType.INFO, undefined, 'open CouchDB in browser'); logSpy.secondCall.should.have.been.calledWith(LogType.INFO, 'Default CouchDB login: Use username \'admin\' and password \'adminpw\''); logSpy.thirdCall.should.have.been.calledWith(LogType.ERROR, `Error opening CouchDB in browser: ${error.message}`, `Error opening CouchDB in browser: ${error.toString()}`); }); });
the_stack
import Component from '../component'; import Util from '../util.js'; interface IProps { element: HTMLElement|string; // the element must exist name?: null; selectable?: boolean; filterItems?: () => boolean; multiple?: boolean; tag?: boolean; } interface ISelectboxItem { text: string; value: string; element: HTMLElement; } export default class Selectbox extends Component { public static attachDOM(): void { Util.Observer.subscribe({ componentClass: 'selectbox', onAdded(element, create) { create(new Selectbox({ element })); }, onRemoved(element, remove) { remove('Selectbox', element); }, }); } private filterItemsHandler: (event: Event) => void; private searchInputInContainer: boolean; /** * * @param props */ constructor(props: IProps) { super('selectbox', { name: null, selectable: true, filterItems: null, multiple: false, tag: false, }, props); // no-template: selectbox is not a dynamic component if (!this.getProp('name')) { // Get the name from the hidden input const hiddenInput = this.getElement().querySelector('input[type="hidden"]'); if (hiddenInput) { this.setProp('name', hiddenInput.getAttribute('name')); } } this.filterItemsHandler = (event: Event) => { const target: HTMLInputElement|null = event.target as HTMLInputElement; if (!target) { return; } const search = target.value; if (search === '') { this.showItems(); return; } this.getItems().forEach((item) => { const filterItems = this.getProp('filterItems'); const fn = typeof filterItems === 'function' ? filterItems : this.filterItems; if (fn(search, item)) { item.element.style.display = 'block'; } else { item.element.style.display = 'none'; } }); }; this.registerElement({ target: this.getElement(), event: Util.Event.CLICK }); this.searchInputInContainer = this.getElement() .querySelector('.selectbox-input-container .input-select-one') !== null; // init active item const selectedItem = this.getItemData(this.getElement().querySelector('[data-selected]')); if (selectedItem) { this.setSelected(selectedItem.value, selectedItem.text); } } public getSearchInput(): HTMLInputElement|null { return this.getElement().querySelector('.input-select-one'); } public filterItems(search = '', item: ISelectboxItem): boolean { return item.value.indexOf(search) > -1 || item.text.indexOf(search) > -1; } public showItems(): void { this.getItems().forEach((item) => { item.element.style.display = 'block'; }); } public getItems(): ISelectboxItem[] { const items: HTMLElement[] = Array .from(this.getElement().querySelectorAll('.selectbox-menu-item') || []); return items.map((item) => { const info = this.getItemData(item); return { text: info.text, value: info.value, element: item }; }); } public setSelected(value: string = '', text: string = ''): boolean { const selectable = this.getProp('selectable'); if (!selectable) { return false; } const element = this.getElement(); const multiple = this.getProp('multiple'); if (multiple) { this.addItemSelection(value); } else { const itemsSelected = Array .from(element.querySelectorAll('.selectbox-item-selection .item-selected') || []); if (itemsSelected.length === 0) { // generate this.addItemSelection(value); } } // update the visual input const lastSelectedEl = element .querySelector('.selectbox-item-selection .item-selected:last-child'); const spanEl = lastSelectedEl.querySelector('[data-value]'); if (spanEl) { spanEl.innerHTML = text; } else { lastSelectedEl.innerHTML = text; } // update value for the last node const hiddenInputs: HTMLInputElement[] = Array .from(this.getElement().querySelectorAll('input[type="hidden"]') || []); const lastInput = hiddenInputs.slice(-1).pop(); if (lastInput) { lastInput.setAttribute('value', value); } // update the selected state for the list of options this.updateActiveList(); // update search this.setSearchInputWidth(); // update placeholder const searchInput = this.getSearchInput(); if (value === '') { this.showPlaceholder(); } else { this.showPlaceholder(false); } return true; } public getSelected(): string|string[] { const hiddenInputs: HTMLInputElement[] = Array .from(this.getElement().querySelectorAll('input[type="hidden"]') || []); if (!this.getProp('multiple')) { return hiddenInputs.length > 0 ? hiddenInputs[0].value : ''; } return hiddenInputs.map(input => input.value); } public setSearchInputWidth(): void { if (!this.searchInputInContainer) { return; } const selectbox = this.getElement(); const selection = selectbox.querySelector('.selectbox-item-selection'); const availableSpace = selectbox.offsetWidth - selection.offsetWidth; const searchInput = this.getSearchInput(); if (!searchInput) { throw new Error('Selectbox: search input is not defined'); } const selectedItemWidth = Array .from(selectbox.querySelectorAll('.item-selected') || []) .reduce((total: number, el) => (total + (el as HTMLElement).offsetWidth), 0); if (availableSpace > 0) { searchInput.style.width = `calc(100% - ${(selectedItemWidth + 15)}px)`; } searchInput.style.left = `${selectedItemWidth}px`; } public getItemData(item: HTMLElement|null = null) { let text = ''; let value = ''; if (item) { text = item.getAttribute('data-text') || item.innerHTML; const selectedTextNode = item.querySelector('.text'); if (selectedTextNode) { text = selectedTextNode.innerHTML; } value = item.getAttribute('data-value') || ''; } return { text, value }; } public onElementEvent(event: KeyboardEvent): void { const target = event.target as HTMLElement; if (event.type === Util.Event.START) { const selectbox = Util.Selector.closest(target, '.selectbox'); /* * hide the current selectbox only if the event concerns another selectbox * hide also if the user clicks outside a selectbox */ if (!selectbox || selectbox !== this.getElement()) { this.hide(); } } else if (event.type === Util.Event.CLICK) { const dataToggleAttr = target.getAttribute('data-toggle'); if (dataToggleAttr && dataToggleAttr === 'selectbox') { this.toggle(); return; } const dismissButton: HTMLElement|null = Util.Selector .closest(target, '[data-dismiss="selectbox"]'); if (dismissButton) { this.hide(); return; } const selectedTag: HTMLElement|null = Util.Selector.closest(target, '.icon-close'); if (selectedTag) { this.removeSelected(selectedTag.parentNode as HTMLElement); return; } const item: HTMLElement|null = Util.Selector.closest(target, '.selectbox-menu-item'); if (item && !item.classList.contains('disabled')) { const itemInfo = this.getItemData(item); if (this.getSelected() !== itemInfo.value) { // the user selected another value, we dispatch the event this.setSelected(itemInfo.value, itemInfo.text); // reset const selectInput = this.getElement().querySelector('.input-select-one').value = ''; const detail = { item, text: itemInfo.text, value: itemInfo.value }; this.triggerEvent(Util.Event.ITEM_SELECTED, detail); } this.hide(); return; } // don't toggle the selectbox if the event concerns headers, dividers const selectboxMenu = Util.Selector.closest(target, '.selectbox-menu'); if (selectboxMenu) { return; } this.toggle(); } else if (event.type === 'keyup' && event.keyCode === 8) { const inputTarget = event.target as HTMLInputElement; if (inputTarget.value !== '') { return; } if (!this.searchInputInContainer) { return; } this.removeLastSelected(); } } public addItemSelection(value: string): void { // visual const itemSelectedEl = document.createElement('div'); itemSelectedEl.classList.add('item-selected'); if (this.getProp('tag')) { itemSelectedEl.classList.add('tag'); // add value const spanEl = document.createElement('span'); spanEl.setAttribute('data-value', 'true'); itemSelectedEl.appendChild(spanEl); // add delete icon const closeEl = document.createElement('button'); closeEl.setAttribute('type', 'button'); closeEl.classList.add('icon-close'); const iconEl = document.createElement('span'); iconEl.setAttribute('class', 'icon'); iconEl.setAttribute('aria-hidden', 'true'); closeEl.appendChild(iconEl); itemSelectedEl.appendChild(closeEl); } const element = this.getElement(); element.querySelector('.selectbox-item-selection').appendChild(itemSelectedEl); // hidden input(s) const selectbox = this.getElement(); const hiddenInputs = Array.from(selectbox.querySelectorAll('input[type="hidden"]') || []); const lastHiddenInput = hiddenInputs.length > 0 ? hiddenInputs[hiddenInputs.length - 1] : null; if ((!this.getProp('multiple') && !lastHiddenInput) || this.getProp('multiple')) { const hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); const name = this.getProp('name'); hiddenInput.setAttribute('name', this.getProp('multiple') ? `${name}[]` : name); hiddenInput.setAttribute('value', value); selectbox.insertBefore( hiddenInput, lastHiddenInput ? (lastHiddenInput as HTMLInputElement).nextSibling : selectbox.firstChild, ); } } public removeLastSelected(): void { const selectbox = this.getElement(); const selectedItems = Array .from(selectbox.querySelectorAll('.selectbox-item-selection .item-selected') || []); if (selectedItems.length === 0) { // nothing to remove return; } const lastSelectedItem: HTMLElement = selectedItems[selectedItems.length - 1] as HTMLElement; this.removeSelected(lastSelectedItem); } public removeSelected(selectedItem: HTMLElement): void { const selectbox = this.getElement(); const selectedItems = Array .from(selectbox.querySelectorAll('.selectbox-item-selection .item-selected') || []); if (selectedItems.length === 0) { // nothing to remove return; } // visual selectbox.querySelector('.selectbox-item-selection').removeChild(selectedItem); if (this.getProp('multiple')) { const values: string[] = this.getSelected() as string[]; const hiddenInput = selectbox .querySelector(`input[type="hidden"][value="${values.slice(-1).pop()}"]`); this.getElement().removeChild(hiddenInput); } else { const hiddenInput = selectbox.querySelector('input[type="hidden"]'); if (!this.getProp('multiple') && hiddenInput) { hiddenInput.setAttribute('value', ''); } } this.updateActiveList(); this.setSearchInputWidth(); if (selectedItems.length === 1) { this.showPlaceholder(); } } public showPlaceholder(show: boolean = true): void { const searchInput = this.getSearchInput(); if (!searchInput) { return; } if (show && searchInput.classList.contains('hide-placeholder')) { searchInput.classList.remove('hide-placeholder'); } else if (!show && !searchInput.classList.contains('hide-placeholder')) { searchInput.classList.add('hide-placeholder'); } } public updateActiveList(): void { const selected = this.getSelected(); const selectedItems = Array.isArray(selected) ? selected : [selected]; const items: HTMLElement[] = Array .from(this.getElement().querySelectorAll('.selectbox-menu-item') || []); items.forEach((item) => { const data = this.getItemData(item); if (selectedItems.indexOf(data.value) > -1) { if (!item.classList.contains('selected')) { item.classList.add('selected'); } } else { if (item.classList.contains('selected')) { item.classList.remove('selected'); } } }); } public toggle(): boolean { if (this.getElement().classList.contains('active')) { return this.hide(); } return this.show(); } /** * Shows the selectbox * @returns {Boolean} */ public show(): boolean { const element = this.getElement(); if (element.classList.contains('active')) { return false; } element.classList.add('active'); const selectboxMenu = element.querySelector('.selectbox-menu'); const selectInput = this.getSearchInput(); // scroll to top selectboxMenu.scrollTop = 0; this.triggerEvent(Util.Event.SHOW); this.triggerEvent(Util.Event.SHOWN); this.registerElement({ target: document.body, event: Util.Event.START }); if (selectInput) { this.registerElement({ target: selectInput as HTMLElement, event: 'keyup' }); selectInput.addEventListener('keyup', this.filterItemsHandler); selectInput.focus(); } const closeButton = element.querySelector('[data-dismiss="selectbox"]'); if (closeButton) { this.registerElement({ target: closeButton, event: Util.Event.CLICK }); } return true; } /** * Hides the selectbox * @returns {Boolean} */ public hide(): boolean { const element = this.getElement(); if (!element.classList.contains('active')) { return false; } element.classList.remove('active'); this.triggerEvent(Util.Event.HIDE); this.triggerEvent(Util.Event.HIDDEN); this.unregisterElement({ target: document.body, event: Util.Event.START }); const closeButton = element.querySelector('[data-dismiss="selectbox"]'); if (closeButton) { this.unregisterElement({ target: closeButton, event: Util.Event.CLICK }); } const selectInput = this.getSearchInput(); if (selectInput) { selectInput.removeEventListener('keyup', this.filterItemsHandler); // reset selectInput.value = ''; this.unregisterElement({ target: selectInput, event: 'keyup' }); } this.showItems(); return true; } } // static boot Selectbox.attachDOM();
the_stack
module TDev { export module RT { //? A board to build 2D games //@ icon("gameboard") ctx(general,gckey,enumerable) export class Board extends RTValue { private _landscape: boolean; public _width:number; public _height:number; public _full: boolean; public scaleFactor = 1.0; private container:HTMLElement; private canvas:HTMLCanvasElement; private ctx : CanvasRenderingContext2D; private sprites: Sprite[] = []; private _orderedSprites: Sprite[]; public backgroundColor:Color = null; private backgroundPicture:Picture = null; private backgroundCamera: Camera = null; private _boundaryDistance : number = NaN; private _everyFrameTimer : Timer = undefined; constructor() { super() } private _gravity : Vector2 = new Vector2(0,0); public _worldFriction : number = 0; private _debugMode : boolean = false; private _lastUpdateMS : number = 0; // no serialization, relative time since board initialized. private _lastTimeDelta : number = 0; // no serialization public _startTime : number = 0; // no serialization private _touched : boolean = false; // no serialization private _touchStart : Vector3 = Vector3.mk(0,0,0); // no serialization private _touchCurrent : Vector3 = Vector3.mk(0,0,0); // no serialization private _touchEnd : Vector3 = Vector3.mk(0,0,0); // no serialization private _touchVelocity : Vector3 = Vector3.mk(0,0,0); // no serialization private _touchedSpriteStack: Sprite[]; private _touchLast: Vector3; private _runtime:Runtime; /// <summary> /// for debugging only /// </summary> public _minSegments: Vector4[] = []; /// <summary> /// Constructed on demand from obstacles and in the constructor. No serialization /// </summary> private _walls : WallSegment[] = []; // not serialized private _obstacles : Obstacle[] = []; private _springs: Spring[] = []; private _backgroundScene: BoardBackgroundScene = undefined; static mk(rt:Runtime, landscape : boolean, w:number, h:number, full:boolean) { var b = new Board(); b._landscape = landscape; b._width = w; b._height = h; b._full = full; b._startTime = rt.currentTime(); b.backgroundColor = Colors.transparent(); b.init(rt); return b; } public init(rt:Runtime) { this._runtime = rt; this.canvas = <HTMLCanvasElement> document.createElement("canvas"); this.canvas.className = "boardCanvas"; this.updateScaleFactor(); this.container = div("boardContainer", this.canvas); this.ctx = this.canvas.getContext("2d"); this.container.setChildren([this.canvas]); (<any>this.container).updateSizes = () => { this.updateScaleFactor(); this.redrawBoardAndContents(); }; var handler = new TouchHandler(this.canvas, (e,x,y) => { this.touchHandler(e, x, y); }); } private updateScaleFactor() { Util.assert(!!this._runtime); if (!this._runtime) return; var s0:number; var s1:number; if (this._full) { s0 = this._runtime.host.fullWallWidth() / this._width; s1 = this._runtime.host.fullWallHeight() / this._height; } else { var w = this._runtime.host.wallWidth; if (this.container && this.container.offsetWidth) w = this.container.offsetWidth; s0 = w / this._width; s1 = this._runtime.host.wallHeight / this._height; } if (s0 > s1) s0 = s1; var ww = this._width * s0; var hh = this._height * s0; this.scaleFactor = s0; this.canvas.width = ww * SizeMgr.devicePixelRatio; this.canvas.height = hh * SizeMgr.devicePixelRatio; this.canvas.style.width = ww + "px"; this.canvas.style.height = hh + "px"; if (this._full) { var topMargin = (this._runtime.host.fullWallHeight() - hh) / 2; this.canvas.style.marginTop = topMargin + "px"; } } private swipeThreshold = 10; private dragThreshold = 5; private onTap: Event_ = new Event_(); private onTouchDown: Event_ = new Event_(); private onTouchUp: Event_ = new Event_(); private onSwipe: Event_ = new Event_(); private _prevTouchTime : number; private _touchDeltaTime : number; private _touchPrevious : Vector3 = Vector3.mk(0,0,0); // no serialization private _touchDirection : Vector3 = Vector3.mk(0,0,0); // no serialization private touchHandler(e:string, x:number, y:number) : void { Util.assert(!!this._runtime); if (!this._runtime) return; x = Math.round(x / this.scaleFactor); y = Math.round(y / this.scaleFactor); switch (e) { case "down": this._touched = true; this._touchPrevious = this._touchCurrent = this._touchLast = this._touchStart = Vector3.mk(x, y, 0); this._touchedSpriteStack = this.findTouchedSprites(x, y); this._prevTouchTime = this._runtime.currentTime(); this._touchDeltaTime = 0; this._touchDirection = Vector3.mk(0, 0, 0); this.queueTouchDown(this._touchedSpriteStack, [x, y]); this._runtime.queueBoardEvent(["touch down: "], [this], [x, y]); if (!!this._touchedSpriteStack) { this._runtime.queueBoardEvent(["touch over "], this._touchedSpriteStack, [x, y], true, true); } break; case "move": this._touchCurrent = Vector3.mk(x, y, 0); var now = this._runtime.currentTime(); var deltaMove = this._touchCurrent.subtract(this._touchPrevious); var deltaTime = now - this._prevTouchTime; if (deltaTime > 50 || deltaMove.length() > 20) { this._touchDirection = deltaMove; this._touchDeltaTime = deltaTime; } if (!!this._touchedSpriteStack) { var dist = this._touchCurrent.subtract(this._touchLast); if (dist.length() > this.dragThreshold) { this._touchLast = this._touchCurrent; this.queueDrag(this._touchedSpriteStack, [x, y, dist._x, dist._y]); this._runtime.queueBoardEvent(["drag sprite in ", "drag sprite: "], this._touchedSpriteStack, [x, y, dist._x, dist._y]); } } var currentStack = this.findTouchedSprites(x, y); if (!!currentStack) { this._runtime.queueBoardEvent(["touch over "], currentStack, [x, y], true, true); } break; case "up": var currentPoint = Vector3.mk(x, y, 0); this._touchEnd = this._touchCurrent = currentPoint; this._touched = false; if (this._touchDeltaTime > 0) { this._touchVelocity = this._touchDirection.scale(1000 / this._touchDeltaTime); } else { this._touchVelocity = Vector3.mk(0, 0, 0); } var dist = this._touchEnd.subtract(this._touchStart); var stack: any[] = this._touchedSpriteStack; if (!stack) { stack = []; } stack.push(this); // add board if (dist.length() > this.swipeThreshold) { this.queueSwipe(this._touchedSpriteStack, [this._touchStart._x, this._touchStart._y, dist._x, dist._y]); this._runtime.queueBoardEvent(["swipe sprite in ", "swipe sprite: ", "swipe board: "], stack, [this._touchStart._x, this._touchStart._y, dist._x, dist._y]); } else { this.queueTap(this._touchedSpriteStack, [x, y]); this._runtime.queueBoardEvent(["tap sprite in ", "tap sprite: ", "tap board: "], stack, [x, y]); } this.queueTouchUp(this._touchedSpriteStack, [x, y]); this._runtime.queueBoardEvent(["touch up: "], [this], [x, y]); break; } } private queueDrag(stack: Sprite[], args): boolean { if (!stack) return false; for (var i = 0; i < stack.length; i++) { var sprite = stack[i]; if (sprite instanceof Board) continue; if (sprite.onDrag.handlers) { this._runtime.queueLocalEvent(sprite.onDrag, args); return true; } } return false; } private queueTouchDown(stack: Sprite[], args): boolean { if (stack && stack.length > 0) { for (var i = 0; i < stack.length; i++) { var sprite = stack[i]; if (sprite instanceof Board) continue; if (sprite.onTouchDown.handlers) { this._runtime.queueLocalEvent(sprite.onTouchDown, args); return true; } } } else { if (this.onTouchDown.handlers) { this._runtime.queueLocalEvent(this.onTouchDown, args); return true; } } return false; } private queueTouchUp(stack: Sprite[], args): boolean { if (stack && stack.length > 0) { for (var i = 0; i < stack.length; i++) { var sprite = stack[i]; if (sprite instanceof Board) continue; if (sprite.onTouchUp.handlers) { this._runtime.queueLocalEvent(sprite.onTouchUp, args); return true; } } } else { if (this.onTouchUp.handlers) { this._runtime.queueLocalEvent(this.onTouchUp, args); return true; } } return false; } private queueTap(stack: Sprite[], args): boolean { if (stack && stack.length > 0) { for (var i = 0; i < stack.length; i++) { var sprite = stack[i]; if (sprite instanceof Board) continue; if (sprite.onTap.handlers) { this._runtime.queueLocalEvent(sprite.onTap, args); return true; } } } if (this.onTap.handlers) { this._runtime.queueLocalEvent(this.onTap, args); return true; } return false; } private queueSwipe(stack: Sprite[], args): boolean { if (stack && stack.length > 0) { for (var i = 0; i < stack.length; i++) { var sprite = stack[i]; if (sprite instanceof Board) continue; if (sprite.onSwipe.handlers) { this._runtime.queueLocalEvent(sprite.onSwipe, args); return true; } } } else { if (this.onSwipe.handlers) { this._runtime.queueLocalEvent(this.onSwipe, args); return true; } } return false; } private findTouchedSprites(x:number, y:number) : Sprite[] { var candidates = this.orderedSprites() .filter(sp => !sp._hidden && sp.contains(x, y)) .reverse(); if (candidates.length == 0) return undefined; return candidates; } private applyBackground() { this.ctx.save(); this.ctx.clearRect(0, 0, this._width, this._height); if (!!this.backgroundCamera) { // TODO: display video element in div to start streaming } // it may not have a canvas when the picture is still loading and an resize event occurs else if (!!this.backgroundPicture && this.backgroundPicture.hasCanvas()) { this.ctx.drawImage(this.backgroundPicture.getCanvas(), 0, 0, this.backgroundPicture.widthSync(), this.backgroundPicture.heightSync(), 0, 0, this._width, this._height); } else if (!!this.backgroundColor) { this.ctx.fillStyle = this.backgroundColor.toHtml(); this.ctx.fillRect(0, 0, this._width, this._height); } if (this._backgroundScene) this._backgroundScene.render(this._width, this._height, this.ctx); this.ctx.restore(); } //? Gets the height in pixels public height() : number { return this._height; } //? Gets the sprite count //@ readsMutable public count(): number { return this.sprites.length; } public get_enumerator() { return this.sprites.slice(0); } //? Gets the width in pixels public width() : number { return this._width; } //? True if board is touched //@ tandre public touched() : boolean { return this._touched; } //? Last touch start point //@ tandre public touch_start() : Vector3 { return this._touchStart; } //? Current touch point //@ tandre public touch_current() : Vector3 { return this._touchCurrent; } //? Last touch end point //@ tandre public touch_end() : Vector3 { return this._touchEnd; } //? Final touch velocity after touch ended //@ tandre public touch_velocity() : Vector3 { return this._touchVelocity; } //? Create walls around the board at the given distance. //@ writesMutable public create_boundary(distance:number) : void { if (!isNaN(this._boundaryDistance)) return; this._boundaryDistance = distance; this.initializeCanvasBoundaries(distance); } /// <summary> /// Call only after canvasHeight has been determined (in deserialize) /// </summary> private initializeCanvasBoundaries(distance:number):void { if (isNaN(distance)) return; // add surrounding walls (orient counter-clock-wise) this._walls.push(WallSegment.mk(-distance, -distance, this.width() + 2 * distance, 0, 1, 0)); this._walls.push(WallSegment.mk(this.width() + distance, -distance, 0, this.height() + 2 * distance, 1, 0)); this._walls.push(WallSegment.mk(this.width() + distance, this.height() + distance, -(this.width() + 2 * distance), 0, 1, 0)); this._walls.push(WallSegment.mk(-distance, this.height() + distance, 0, -(this.height() + 2 * distance), 1, 0)); } private addObstacle(o : Obstacle): void { this._walls.push(WallSegment.mk(o.x, o.y, o.xextent, o.yextent, o.elasticity, o.friction, o)); this._walls.push(WallSegment.mk(o.x + o.xextent, o.y + o.yextent, -o.xextent, -o.yextent, o.elasticity, o.friction, o)); this._obstacles.push(o); } //? Create a new collection for sprites. public create_sprite_set() : SpriteSet { return new SpriteSet(); } public deleteSprite(sprite : Sprite) : void { var idx = this.sprites.indexOf(sprite); if (idx < 0) return; this.sprites.splice(idx, 1); this.spritesChanged(); } public spritesChanged() { this._orderedSprites = undefined; } //? gets the timer that fires for every display frame. public frame_timer(s : IStackFrame): Timer { if(!this._everyFrameTimer) this._everyFrameTimer = new Timer(s.rt, 0.02, false); return this._everyFrameTimer; } //? add an action that fires for every display frame. //@ ignoreReturnValue public add_on_every_frame(body: Action, s: IStackFrame): EventBinding { return this.on_every_frame(body, s); } //? add an action that fires for every display frame. //@ ignoreReturnValue public on_every_frame(body: Action, s: IStackFrame): EventBinding { return this.frame_timer(s).on_trigger(body); } //? Stops and clears all the `every frame` timers public clear_every_frame_timers() { if (this._everyFrameTimer) { this._everyFrameTimer.clear(); this._everyFrameTimer = undefined; this._everyFrameOnSprite = false; } } //? set the handler that is invoked when the board is tapped //@ ignoreReturnValue //@ writesMutable public on_tap(tapped: PositionAction) : EventBinding { return this.onTap.addHandler(tapped); } //? set the handler that is invoked when the board is swiped //@ ignoreReturnValue //@ writesMutable public on_swipe(swiped: VectorAction) : EventBinding { return this.onSwipe.addHandler(swiped); } //? set the handler that is invoked when the board is touched //@ writesMutable //@ ignoreReturnValue public on_touch_down(touch_down: PositionAction) : EventBinding { return this.onTouchDown.addHandler(touch_down); } //? set the handler that is invoked when the board touch is released //@ writesMutable //@ ignoreReturnValue public on_touch_up(touch_up: PositionAction) : EventBinding { return this.onTouchUp.addHandler(touch_up); } public tick: number = 0; //? Update positions of sprites on board. //@ timestamp //@ writesMutable public evolve() : void { Util.assert(!!this._runtime); if (!this._runtime) return; this.tick++; if (isNaN(this.tick)) this.tick = 0; var now = this._runtime.currentTime(); var newDelta = this._lastTimeDelta = (now - this._startTime) - this._lastUpdateMS; //if (newDelta === undefined || newDelta < 0) { // throw new Error("negative dt"); //} this._lastUpdateMS += newDelta; var dT = Math_.clamp(0, 0.2, newDelta / 1000); this.sprites.forEach(sprite => sprite.update(dT)); this.detectCollisions(dT); this.sprites.forEach(sprite => sprite.commitUpdate(this._runtime, dT)); } private detectCollisions(dT:number):void { // detect wall collisions for (var i = 0; i < this.sprites.length; i++) { var s = this.sprites[i]; if (!!s._location) continue; this.detectWallCollision(s, dT); } } private detectWallCollision(sprite:Sprite, dT:number):void { sprite.normalTouchPoints.clear(); // this means clear the array! for (var i = 0; i < this._walls.length; i++) { var wall = this._walls[i]; if(wall.processPotentialCollision(sprite, dT) && wall._obstacle) wall._obstacle.raiseCollision(this._runtime, sprite); } // do it twice to get corners right for (var i = 0; i < this._walls.length; i++) { var wall = this._walls[i]; if(wall.processPotentialCollision(sprite, dT) && wall._obstacle) wall._obstacle.raiseCollision(this._runtime, sprite); } } public updateViewCore(s: IStackFrame, b: BoxBase) { if (b instanceof WallBox) (<WallBox> b).fullScreen = this._full; this.redrawBoardAndContents(); } public getViewCore(s:IStackFrame, b:BoxBase) : HTMLElement { // called when board gets posted this._touched = false; // clear any past touches that were not lifted return this.container; } //? Checks if the board is the same instance as the other board. public equals(other_board: Board): boolean { return this == other_board; } //? Gets the background scene //@ readsMutable public background_scene(): BoardBackgroundScene { if (!this._backgroundScene) this._backgroundScene = new BoardBackgroundScene(this); return this._backgroundScene; } //? Sets the background color //@ writesMutable //@ [color].deflExpr('colors->random') public set_background(color:Color) : void { this.backgroundCamera = null; this.backgroundColor = color; this.backgroundPicture = null; } //? Sets the background camera //@ writesMutable //@ cap(camera) //@ [camera].deflExpr('senses->camera') public set_background_camera(camera: Camera): void { this.backgroundCamera = camera; this.backgroundColor = null; this.backgroundPicture = null; } //? Sets the background picture //@ writesMutable picAsync //@ embedsLink("Board", "Picture") public set_background_picture(picture:Picture, r:ResumeCtx) : void { this.backgroundCamera = null; this.backgroundColor = null; this.backgroundPicture = picture; picture.loadFirst(r, null); } //? In debug mode, board displays speed and other info of sprites //@ [debug].defl(true) public set_debug_mode(debug:boolean) : void { this._debugMode = debug; } //? Sets the default friction for sprites to a fraction of speed loss between 0 and 1 //@ writesMutable //@ [friction].defl(0.01) public set_friction(friction:number) : void { this._worldFriction = friction; } //? Gets a value indicating if the board is designed to be viewed in landscape mode public is_landscape(): boolean { return this._landscape; } //? Sets the uniform acceleration vector for objects on the board to pixels/sec^2 //@ writesMutable [y].defl(200) public set_gravity(x:number, y:number) : void { this._gravity = new Vector2(x, y); } public gravity() : Vector2 { return this._gravity; } //? Gets the sprite indexed by i //@ readsMutable public at(i:number) : Sprite { return this.sprites[i]; } private initialX() : number { return this.width() / 2; } private initialY() : number { return this.height() / 2; } private _everyFrameOnSprite = false; public enableEveryFrameOnSprite(s:IStackFrame) { if (this._everyFrameOnSprite) return; this._everyFrameOnSprite = true; var handler:any = (bot, prev) => { var q = this._runtime.eventQ var args = [] this.sprites.forEach(s => { if (s.onEveryFrame.pendinghandlers == 0) q.addLocalEvent(s.onEveryFrame, args) }) bot.entryAddr = prev return bot }; this.on_every_frame(handler, s); } //? Make updates visible. //@ writesMutable public update_on_wall() : void { this.redrawBoardAndContents(); } private orderedSprites() : Sprite[] { if (!this._orderedSprites) { this._orderedSprites = this.sprites.slice(0); this._orderedSprites.stableSort((a, b) => a.z_index() - b.z_index()); } return this._orderedSprites; } private redrawBoardAndContents() : void { var isDebugMode = this._debugMode && (this._runtime && !this._runtime.currentScriptId); this.ctx.save(); var scale = this.scaleFactor * SizeMgr.devicePixelRatio; this.ctx.scale(scale, scale); this.applyBackground(); this.orderedSprites().forEach(s => s.redraw(this.ctx, isDebugMode)); this.renderObstacles(); if (isDebugMode) { this.debugGrid(); this.debugSprings(); this.debugSegments(); } this.ctx.restore(); } public renderingContext() { return this.ctx; } private debugGrid() { this.ctx.save(); this.ctx.beginPath(); var w = this.width(); var h = this.height(); this.ctx.strokeStyle = "rgba(90, 90, 90, 0.7)"; this.ctx.fillStyle = "rgba(90, 90, 90, 0.7)"; this.ctx.lineWidth = 1; this.ctx.font = "12px sans-serif"; // this.ctx.globalAlpha = 0.8; for(var y = 0; y <= h; y += 100) { this.ctx.moveTo(0, y); this.ctx.lineTo(w, y); if (y > 0 && y % 100 == 0) this.ctx.fillText(y.toString(), 2, y - 5); this.ctx.stroke(); } for(var x = 0; x <= w; x += 100) { this.ctx.moveTo(x, 0); this.ctx.lineTo(x, h); if (x > 0 && x % 100 == 0) this.ctx.fillText(x.toString(), x - 15, 10); this.ctx.stroke(); } this.ctx.restore(); } private debugSegments(): void { this.ctx.save(); this.ctx.beginPath(); for (var i = 0; i < this._minSegments.length; ++i) { var seg = this._minSegments[i]; if ((<any>seg).overlap) { this.ctx.fillStyle = "green"; this.ctx.strokeStyle = "green"; } else { this.ctx.fillStyle = "red"; this.ctx.strokeStyle = "red"; } this.ctx.font = "20px sans-serif"; this.ctx.lineWidth = 4; this.ctx.moveTo(seg.x(), seg.y()); this.ctx.lineTo(seg.x() + seg.z(), seg.y() + seg.w()); this.ctx.fillText((<any>seg).from + "", seg.x() + seg.z(), seg.y() + seg.w()); } this.ctx.stroke(); this.ctx.restore(); if (this._minSegments.length > 0) { debugger; this._minSegments = []; } } private debugSprings(): void { this.ctx.save(); this.ctx.strokeStyle = "gray"; this.ctx.beginPath(); for (var i = 0; i < this._springs.length; i++) { var o = this._springs[i]; this.ctx.moveTo(o.sprite1.x(), o.sprite1.y()); this.ctx.lineTo(o.sprite2.x(), o.sprite2.y()); } this.ctx.stroke(); this.ctx.restore(); } private renderObstacles() : void { this.ctx.save(); for (var i = 0; i < this._obstacles.length; i++) { var o = this._obstacles[i]; if (!o.isValid()) continue; this.ctx.beginPath(); this.ctx.lineWidth = o._thickness; this.ctx.strokeStyle = o._color.toHtml(); this.ctx.moveTo(o.x, o.y); this.ctx.lineTo(o.x+o.xextent, o.y+o.yextent); this.ctx.stroke(); } this.ctx.restore(); } public mkSprite(tp:SpriteType, w:number, h:number) { var s = Sprite.mk(tp, this.initialX(), this.initialY(), w, h); this.addSprite(s); return s; } private addSprite(s:Sprite) { s._parent = this; s.set_z_index(0); this.sprites.push(s); s.changed(); this.spritesChanged(); } //? Create a new ellipse sprite. //@ readsMutable [result].writesMutable //@ [width].defl(20) [height].defl(20) //@ embedsLink("Board", "Sprite") public create_ellipse(width:number, height:number) : Sprite { return this.mkSprite(SpriteType.Ellipse, width, height); } //? Create a new rectangle sprite. //@ readsMutable [result].writesMutable //@ [width].defl(20) [height].defl(20) //@ embedsLink("Board", "Sprite") public create_rectangle(width:number, height:number) : Sprite { return this.mkSprite(SpriteType.Rectangle, width, height); } //? Create a new text sprite. //@ readsMutable [result].writesMutable //@ [width].defl(100) [height].defl(40) [fontSize].defl(20) //@ embedsLink("Board", "Sprite") public create_text(width:number, height:number, fontSize:number, text:string) : Sprite { var s = this.mkSprite(SpriteType.Text, width, height); s.fontSize = fontSize; s.set_text(text); return s; } //? Create a new picture sprite. //@ readsMutable [result].writesMutable picAsync //@ embedsLink("Board", "Sprite"), embedsLink("Sprite", "Picture") //@ returns(Sprite) public create_picture(picture:Picture, r:ResumeCtx) { var s = this.mkSprite(SpriteType.Picture, 1, 1); picture.loadFirst(r, () => { s.setPictureInternal(picture); return s; }); } //? Create a new sprite sheet. //@ readsMutable [result].writesMutable picAsync //@ embedsLink("Board", "SpriteSheet"), embedsLink("SpriteSheet", "Picture") //@ returns(SpriteSheet) public create_sprite_sheet(picture:Picture, r:ResumeCtx) { picture.loadFirst(r, () => { Util.log('board: new sprite sheet - ' + picture.widthSync() + 'x' + picture.heightSync()); var sheet = new SpriteSheet(this, picture); return sheet; }); } //? Create an anchor sprite. //@ readsMutable [result].writesMutable //@ [width].defl(20) [height].defl(20) //@ embedsLink("Board", "Sprite") public create_anchor(width:number, height:number) : Sprite { var anchor = this.mkSprite(SpriteType.Anchor, width, height); anchor.set_friction(1); // don't move anchor.hide(); return anchor; } //? Create a line obstacle with given start point, and given width and height. Elasticity is 0 for sticky, 1 for complete bounce. //@ writesMutable ignoreReturnValue //@ [elasticity].defl(1) public create_obstacle(x:number, y:number, width:number, height:number, elasticity:number) : Obstacle { if (width == 0 && height == 0) return; // avoid singularities var o = new Obstacle(this, x, y, width, height, elasticity, 1 - elasticity); this.addObstacle(o); return o; } public deleteObstacle(obstacle : Obstacle) { var idx = this._obstacles.indexOf(obstacle); if (idx > -1) { this._obstacles.splice(idx, 1); this._walls = this._walls.filter(wall => wall._obstacle != obstacle); } } //? Create a spring between the two sprites. //@ writesMutable ignoreReturnValue //@ [stiffness].defl(100) public create_spring(sprite1:Sprite, sprite2:Sprite, stiffness:number) : Spring { // TODO: check for invalid parents var spring = new Spring(this, sprite1, sprite2, stiffness); this._springs.push(spring); sprite1.addSpring(spring); sprite2.addSpring(spring); return spring; } public deleteSpring(spring : Spring) { spring.sprite1.removeSpring(spring); spring.sprite2.removeSpring(spring); var idx = this._springs.indexOf(spring); if (idx > -1) this._springs.splice(idx, 1); } //? Clear all queued events related to this board public clear_events() : void { } public overlapWithAny(sprite:Sprite, sprites:SpriteSet):SpriteSet { var result = new SpriteSet(); for (var i = 0; i < sprites.count(); i++) { var other = sprites.at(i); if (sprite === other) continue; if (sprite.overlaps_with(other)) { result.add(other); } } return result; } //? Clears the background camera //@ cap(camera) public clear_background_camera(): void { this.backgroundCamera = null; } //? Clear the background picture public clear_background_picture(): void { this.backgroundPicture = null; } //? Shows the board on the wall. public post_to_wall(s:IStackFrame) : void { super.post_to_wall(s) if (this._full) { if (this._landscape) Runtime.lockOrientation(false, true, false); else Runtime.lockOrientation(true, false, false); } } } //? An obstacle on a board //@ ctx(general,gckey) export class Obstacle extends RTValue { public _color : Color = Colors.gray(); public _thickness : number = 3; public _onCollision : Event_; constructor(public board : Board, public x:number, public y:number, public xextent:number, public yextent:number, public elasticity:number, public friction:number) { super() } //? Attaches a handler where a sprite bounces on the obstacle //@ ignoreReturnValue public on_collision(bounce : SpriteAction) : EventBinding { if (!this._onCollision) this._onCollision = new Event_(); return this._onCollision.addHandler(bounce); } public raiseCollision(rt : Runtime, sprite : Sprite) { if (this._onCollision && this._onCollision.handlers) rt.queueLocalEvent(this._onCollision, [sprite], false); } //? Sets the obstacle color //@ [color].deflExpr('colors->random') public set_color(color : Color) { this._color = color; } //? Sets the obstacle thickness //@ [thickness].defl(3) public set_thickness(thickness : number) { this._thickness = Math.max(1, thickness); } //? Delete the obstacle public delete_() { this.board.deleteObstacle(this); } public isValid() : boolean { if (!this.IsFinite(this.x)) return false; if (!this.IsFinite(this.y)) return false; if (!this.IsFinite(this.xextent)) return false; if (!this.IsFinite(this.yextent)) return false; return true; } private IsFinite(x:number) : boolean { if (isNaN(x)) return false; if (isFinite(x)) return true; return false; } } export class WallSegment { public _position:Vector2; public _unitExtent:Vector2; public _length:number; public _elasticity:number; public _friction:number; public _obstacle : Obstacle; static mk(x:number, y:number, xextent:number, yextent:number, elasticity:number, friction:number, obstacle : Obstacle = undefined) { var w = new WallSegment(); w._position = new Vector2(x,y); var segment = new Vector2(xextent, yextent); w._length = segment.length(); w._unitExtent = segment.normalize(); w._elasticity = elasticity; w._friction = friction; w._obstacle = obstacle; return w; } /// <summary> /// Find two points, p1 along wall and p2 along sprite path, such that their distance is the radius of the sprite. /// /// s = 0..length. P1(s) = pos + unitExtent * s /// t = 0..1 P2(t) = lastPosition + t*(newPosition - lastPosition); /// /// For now, we simplify this to just compute the time t at which the sprite is distance r from the wall. To avoid /// missing collisions on the end of the segment, we pretend that the segment extends by object radius on both sides. /// /// </summary> public processPotentialCollision(sprite:Sprite, dT:number):boolean { var unitNormal = this._unitExtent.rotate90Left(); var normalSpeedMag = -Vector2.dot(unitNormal, sprite.stepDisplacement()); if (normalSpeedMag <= 0) { // moving away return false; } var pq = sprite._position.subtract(this._position); var distance = Vector2.dot(pq, unitNormal); var normalRadius = sprite.radius(unitNormal); if (distance < normalRadius / 2) { // inside or behind the wall // check how much if (distance <= -normalRadius / 2) { // completely clear of other side return false; } // inside the wall. Check if we are overlapping it var unitRadius = sprite.radius(this._unitExtent); var segmentProj = Vector2.dot(sprite._position.subtract(this._position), this._unitExtent); if (segmentProj < -unitRadius / 2 || segmentProj > this._length + unitRadius / 2) { // outside wall segment return false; } //move it back. if (distance < 0) { return false; //sprite.newPosition = sprite.position + unitNormal * (sprite.RadiusX - distance); } else { sprite.newPosition = sprite._position.add(unitNormal.scale(normalRadius - distance)); } // reverse newSpeed normalSpeedMag = Math.abs(Vector2.dot(unitNormal, sprite.midSpeed)); var normalSpeed = unitNormal.scale(normalSpeedMag); var parallelSpeed = this._unitExtent.scale(Vector2.dot(this._unitExtent, sprite.midSpeed)); sprite.midSpeed = sprite.newSpeed = (normalSpeed.scale(sprite._elasticity * this._elasticity).add( parallelSpeed.scale(1 - this._friction))); sprite.normalTouchPoints.push(unitNormal); return true; } var t = (distance - normalRadius) / normalSpeedMag; // approximation of radius if (t > 1) { return false; } var impactPos = sprite._position.add(sprite.stepDisplacement().scale(((t < 0) ? (t * 1.01) : (t * 0.99)))); // check if impact Pos projected onto segment is within bounds var unitRadius2 = sprite.radius(this._unitExtent); var segmentIndex = Vector2.dot(impactPos.subtract(this._position), this._unitExtent); if (segmentIndex < -unitRadius2 / 2 || segmentIndex > this._length + unitRadius2 / 2) { // outside wall segment return false; } { // fixup position normalSpeedMag = Math.abs(Vector2.dot(unitNormal, sprite.midSpeed)); var normalSpeed = unitNormal.scale(normalSpeedMag); var stepParallelSpeed = this._unitExtent.scale(Vector2.dot(this._unitExtent, sprite.stepDisplacement())); sprite.newPosition = impactPos.add(stepParallelSpeed.scale(1 - t)); var parallelSpeed = this._unitExtent.scale(Vector2.dot(this._unitExtent, sprite.newSpeed)); sprite.midSpeed = sprite.newSpeed = (normalSpeed.scale(sprite._elasticity * this._elasticity).add(parallelSpeed.scale(1 - this._friction))); sprite.normalTouchPoints.push(unitNormal); return true; } } } } }
the_stack
import htmlKeyboardResponse from "@jspsych/plugin-html-keyboard-response"; import { pressKey, startTimeline } from "@jspsych/test-utils"; import { initJsPsych } from "../../src"; describe("loop function", () => { test("repeats a timeline when returns true", async () => { let count = 0; const trial = { timeline: [{ type: htmlKeyboardResponse, stimulus: "foo" }], loop_function: () => { if (count < 1) { count++; return true; } else { return false; } }, }; const { jsPsych } = await startTimeline([trial]); // first trial pressKey("a"); expect(jsPsych.data.get().count()).toBe(1); // second trial pressKey("a"); expect(jsPsych.data.get().count()).toBe(2); }); test("does not repeat when returns false", async () => { const { jsPsych } = await startTimeline([ { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", }, ], loop_function: () => false, }, ]); // first trial pressKey("a"); expect(jsPsych.data.get().count()).toBe(1); // second trial pressKey("a"); expect(jsPsych.data.get().count()).toBe(1); }); test("gets the data from the most recent iteration", async () => { let data_count = []; let count = 0; const { jsPsych } = await startTimeline([ { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", }, ], loop_function: (data) => { data_count.push(data.count()); if (count < 2) { count++; return true; } else { return false; } }, }, ]); // first trial pressKey("a"); // second trial pressKey("a"); // third trial pressKey("a"); expect(data_count).toEqual([1, 1, 1]); expect(jsPsych.data.get().count()).toBe(3); }); test("timeline variables from nested timelines are available in loop function", async () => { let counter = 0; const jsPsych = initJsPsych(); const { getHTML } = await startTimeline( [ { timeline: [ { type: htmlKeyboardResponse, stimulus: jsPsych.timelineVariable("word"), }, { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", }, ], loop_function: () => { if (jsPsych.timelineVariable("word") == "b" && counter < 2) { counter++; return true; } else { counter = 0; return false; } }, }, ], timeline_variables: [{ word: "a" }, { word: "b" }, { word: "c" }], }, ], jsPsych ); expect(getHTML()).toMatch("a"); pressKey("a"); expect(getHTML()).toMatch("foo"); pressKey("a"); expect(getHTML()).toMatch("b"); pressKey("a"); expect(getHTML()).toMatch("foo"); pressKey("a"); expect(getHTML()).toMatch("foo"); pressKey("a"); expect(getHTML()).toMatch("foo"); pressKey("a"); expect(getHTML()).toMatch("c"); pressKey("a"); expect(getHTML()).toMatch("foo"); pressKey("a"); }); test("only runs once when timeline variables are used", async () => { let count = 0; await startTimeline([ { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", }, ], timeline_variables: [{ a: 1 }, { a: 2 }], loop_function: () => { count++; return false; }, }, ]); // first trial pressKey("a"); expect(count).toBe(0); // second trial pressKey("a"); expect(count).toBe(1); }); }); describe("conditional function", () => { test("skips the timeline when returns false", async () => { const conditional = { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", }, ], conditional_function: () => false, }; const trial = { type: htmlKeyboardResponse, stimulus: "bar", }; const { getHTML } = await startTimeline([conditional, trial]); expect(getHTML()).toMatch("bar"); // clear pressKey("a"); }); test("completes the timeline when returns true", async () => { const conditional = { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", }, ], conditional_function: () => { return true; }, }; const trial = { type: htmlKeyboardResponse, stimulus: "bar", }; const { getHTML } = await startTimeline([conditional, trial]); expect(getHTML()).toMatch("foo"); // next pressKey("a"); expect(getHTML()).toMatch("bar"); // clear pressKey("a"); }); test("executes on every loop of the timeline", async () => { let count = 0; let conditional_count = 0; await startTimeline([ { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", }, ], loop_function: () => { if (count < 1) { count++; return true; } else { return false; } }, conditional_function: () => { conditional_count++; return true; }, }, ]); expect(conditional_count).toBe(1); // first trial pressKey("a"); expect(conditional_count).toBe(2); // second trial pressKey("a"); expect(conditional_count).toBe(2); }); test("executes only once even when repetitions is > 1", async () => { let conditional_count = 0; await startTimeline([ { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", }, ], repetitions: 2, conditional_function: () => { conditional_count++; return true; }, }, ]); expect(conditional_count).toBe(1); // first trial pressKey("a"); expect(conditional_count).toBe(1); // second trial pressKey("a"); expect(conditional_count).toBe(1); }); test("executes only once when timeline variables are used", async () => { let conditional_count = 0; await startTimeline([ { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", }, ], timeline_variables: [{ a: 1 }, { a: 2 }], conditional_function: () => { conditional_count++; return true; }, }, ]); expect(conditional_count).toBe(1); // first trial pressKey("a"); expect(conditional_count).toBe(1); // second trial pressKey("a"); expect(conditional_count).toBe(1); }); test("timeline variables from nested timelines are available", async () => { const jsPsych = initJsPsych(); const { getHTML } = await startTimeline( [ { timeline: [ { type: htmlKeyboardResponse, stimulus: jsPsych.timelineVariable("word"), }, { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", }, ], conditional_function: () => { if (jsPsych.timelineVariable("word") == "b") { return false; } else { return true; } }, }, ], timeline_variables: [{ word: "a" }, { word: "b" }, { word: "c" }], }, ], jsPsych ); expect(getHTML()).toMatch("a"); pressKey("a"); expect(getHTML()).toMatch("foo"); pressKey("a"); expect(getHTML()).toMatch("b"); pressKey("a"); expect(getHTML()).toMatch("c"); pressKey("a"); expect(getHTML()).toMatch("foo"); pressKey("a"); }); }); describe("endCurrentTimeline", () => { test("stops the current timeline, skipping to the end after the trial completes", async () => { const jsPsych = initJsPsych(); const { getHTML } = await startTimeline( [ { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", on_finish: () => { jsPsych.endCurrentTimeline(); }, }, { type: htmlKeyboardResponse, stimulus: "bar", }, ], }, { type: htmlKeyboardResponse, stimulus: "woo", }, ], jsPsych ); expect(getHTML()).toMatch("foo"); pressKey("a"); expect(getHTML()).toMatch("woo"); pressKey("a"); }); test("works inside nested timelines", async () => { const jsPsych = initJsPsych(); const { getHTML } = await startTimeline( [ { timeline: [ { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", on_finish: () => { jsPsych.endCurrentTimeline(); }, }, { type: htmlKeyboardResponse, stimulus: "skip me!", }, ], }, { type: htmlKeyboardResponse, stimulus: "bar", }, ], }, { type: htmlKeyboardResponse, stimulus: "woo", }, ], jsPsych ); expect(getHTML()).toMatch("foo"); pressKey("a"); expect(getHTML()).toMatch("bar"); pressKey("a"); expect(getHTML()).toMatch("woo"); pressKey("a"); }); }); describe("nested timelines", () => { test("works without other parameters", async () => { const { getHTML } = await startTimeline([ { timeline: [ { type: htmlKeyboardResponse, stimulus: "foo", }, { type: htmlKeyboardResponse, stimulus: "bar", }, ], }, ]); expect(getHTML()).toMatch("foo"); pressKey("a"); expect(getHTML()).toMatch("bar"); pressKey("a"); }); }); describe("add node to end of timeline", () => { test("adds node to end of timeline", async () => { const jsPsych = initJsPsych(); const { getHTML } = await startTimeline( [ { type: htmlKeyboardResponse, stimulus: "foo", on_start: () => { jsPsych.addNodeToEndOfTimeline({ timeline: [{ type: htmlKeyboardResponse, stimulus: "bar" }], }); }, }, ], jsPsych ); expect(getHTML()).toMatch("foo"); pressKey("a"); expect(getHTML()).toMatch("bar"); pressKey("a"); }); });
the_stack
import { loader_mgr } from "../loader/loader_mgr"; import { gen_handler } from "../util"; type DB_EVENT_HANDLER = (event:dragonBones.EventObject, state:dragonBones.AnimationState) => void; const EVENT_DB_ASSET_LOADED = "EVENT_DB_ASSET_LOADED"; const BasePathForSke = (path:string) => { return `dragonbones/${path}_ske`; }; const BasePathForTex = (path:string) => { return `dragonbones/${path}_tex`; }; export class DragonBoneFactory { private static _inst:DragonBoneFactory; private _loadingMap:Map<string, dragonBones.ArmatureDisplay[]> private _eventMap:Map<string, cc.EventTarget>; private _stateMap:Map<string, dragonBones.AnimationState>; private _compPool:dragonBones.ArmatureDisplay[]; private _refMap:Map<string, number>; private _resMap:Map<string, string>; private constructor() { this._compPool = []; this._loadingMap = new Map(); this._eventMap = new Map(); this._stateMap = new Map(); this._resMap = new Map(); this._refMap = new Map(); } static getInst() { if(!this._inst) { this._inst = new DragonBoneFactory(); } return this._inst; } buildDB(params:ArmatureDisplayParams) { let comp = this._compPool.pop(); let node:cc.Node; if(comp) { node = comp.node; } else { node = new cc.Node(); comp = node.addComponent(dragonBones.ArmatureDisplay); //save reference count for auto release const path = params.path; this._resMap.set(comp.uuid, path); const refCnt = (this._refMap.get(path) || 0) + 1; this._refMap.set(path, refCnt); cc.log(`DragonBoneFactory, increaseRef, path=${path}, ref=${refCnt}`); } if(params.parent) { node.parent = params.parent; node.x = params.x || 0; node.y = params.y || 0; } node.active = params.active != null ? params.active : true; // cc.log("buildArmatureDisplay", node.getContentSize(), node.getPosition(), node.getAnchorPoint()); const path = params.path; const skePath = BasePathForSke(path); const texPath = BasePathForTex(path); const dragonBonesAsset = cc.loader.getRes(skePath, dragonBones.DragonBonesAsset); const dragonBonesAtlasAsset = cc.loader.getRes(texPath, dragonBones.DragonBonesAtlasAsset); const texture2D = cc.loader.getRes(texPath, cc.Texture2D); if(dragonBonesAsset && dragonBonesAtlasAsset && texture2D) { this.attachAsset(comp, params, dragonBonesAsset, dragonBonesAtlasAsset, texture2D); } else { const assets:DBAsset[] = [ {path:skePath, alias:"dragonBonesAsset", type:dragonBones.DragonBonesAsset}, {path:texPath, alias:"dragonBonesAtlasAsset", type:dragonBones.DragonBonesAtlasAsset}, {path:texPath, alias:"texture2D", type:cc.Texture2D}, ]; this.loadAsset(comp, params, assets); } return comp; } private loadAsset(comp:dragonBones.ArmatureDisplay, params:ArmatureDisplayParams, assets:DBAsset[]) { const path = params.path; //同一路径龙骨资源只加载一次 let loadings = this._loadingMap.get(path); if(!loadings) { loadings = []; this._loadingMap.set(path, loadings); } loadings.push(comp) if(loadings.length > 1) { return; } // cc.log(`DragonBoneFactory, loadAsset, path=${path}`); loader_mgr.get_inst().loadResArray(assets.map(a => a.path), gen_handler(res => { const dragonBonesAsset = res[assets[0].alias]; const dragonBonesAtlasAsset = res[assets[1].alias]; const texture2D = res[assets[2].alias]; const lds = this._loadingMap.get(path); if(lds) { lds.forEach(p => { if(!p || !cc.isValid(p.node)) { return; } if(dragonBonesAsset && dragonBonesAtlasAsset && texture2D) { this.attachAsset(p, params, dragonBonesAsset, dragonBonesAtlasAsset, texture2D); p.node.emit(EVENT_DB_ASSET_LOADED); } }); lds.length = 0; this._loadingMap.delete(path); } }), assets.map(a => a.type), assets.map(a => a.alias)); } private attachAsset(comp:dragonBones.ArmatureDisplay, params:ArmatureDisplayParams, dragonBonesAsset:dragonBones.DragonBonesAsset, dragonBonesAtlasAsset:dragonBones.DragonBonesAtlasAsset, texture2D:cc.Texture2D) { comp.dragonAsset = dragonBonesAsset; dragonBonesAtlasAsset.texture = texture2D; comp.dragonAtlasAsset = dragonBonesAtlasAsset; comp.armatureName = params.armatureName; comp.addEventListener(dragonBones.EventObject.COMPLETE, event => { // cc.log("dragonbone complete event", event, comp.uuid); const state = this._stateMap.get(comp.uuid); if(params.onComplete) { params.onComplete(event, state); } else { this.invokeDBEvent(comp, dragonBones.EventObject.COMPLETE, event, state); } }); comp.addEventListener(dragonBones.EventObject.START, event => { // cc.log("dragonbone start event", event, comp.uuid); const state = this._stateMap.get(comp.uuid); if(params.onStart) { params.onStart(event, state); } else { this.invokeDBEvent(comp, dragonBones.EventObject.START, event, state); } }); } private decreaseRef(comp:dragonBones.ArmatureDisplay) { const path = this._resMap.get(comp.uuid); if(path) { this._resMap.delete(comp.uuid); const refCnt = (this._refMap.get(path) || 0) - 1; this._refMap.set(path, refCnt); cc.log(`DragonBoneFactory, decreaseRef, path=${path}, ref=${refCnt}`); if(refCnt == 0) { this._refMap.delete(path); this.releaseAsset(path); } } } releaseDB(comp:dragonBones.ArmatureDisplay, recycle = false) { const uuid = comp.uuid; this._stateMap.delete(uuid); comp.node.off(EVENT_DB_ASSET_LOADED); comp.removeEventListener(dragonBones.EventObject.COMPLETE); this.removeDBEvent(comp, dragonBones.EventObject.COMPLETE); comp.removeEventListener(dragonBones.EventObject.START); this.removeDBEvent(comp, dragonBones.EventObject.START); comp.stopAnimation(""); comp.dragonAtlasAsset = null; comp.dragonAsset = null; comp.armatureName = null; comp.animationName = null; const node = comp.node; if(recycle) { node.removeFromParent(); this._compPool.push(comp); } else { this.decreaseRef(comp); node.destroy(); } } playDB(comp:dragonBones.ArmatureDisplay, animationName:string, playTimes:number = 1, armatureName?:string) { const node = comp.node; if(!node) { cc.warn(`db has no associated node, animationName=${animationName}`); return; } if(!node.activeInHierarchy) { cc.warn(`db associated node is inactive, animationName=${animationName}`); return; } if(!comp.dragonAsset) { // cc.log(`DragonBoneFactory, playDB async, animationName=${animationName}`); //ArmatureDisplay资源加载完成后才能监听事件,所以这里必须要用node监听 comp.node.on(EVENT_DB_ASSET_LOADED, () => { if(armatureName) { comp.armatureName = armatureName; } const state = comp.playAnimation(animationName, playTimes); this._stateMap.set(comp.uuid, state); // cc.log(`DragonBoneFactory, onAssetLoaded, playDB, animationName=${animationName}`); }); // cc.log("dragonbone play before loaded"); return; } if(armatureName) { comp.armatureName = armatureName; } const state = comp.playAnimation(animationName, playTimes); this._stateMap.set(comp.uuid, state); // cc.log(`DragonBoneFactory, playDB, animationName=${animationName}`); } addStartEvent(comp:dragonBones.ArmatureDisplay, handler:DB_EVENT_HANDLER, target?:any) { this.addDBEvent(comp, dragonBones.EventObject.START, handler, target); } onceStartEvent(comp:dragonBones.ArmatureDisplay, handler:DB_EVENT_HANDLER, target?:any) { this.onceDBEvent(comp, dragonBones.EventObject.START, handler, target); } removeStartEvent(comp:dragonBones.ArmatureDisplay, handler?:DB_EVENT_HANDLER, target?:any) { this.removeDBEvent(comp, dragonBones.EventObject.START, handler, target); } addCompleteEvent(comp:dragonBones.ArmatureDisplay, handler:DB_EVENT_HANDLER, target?:any) { this.addDBEvent(comp, dragonBones.EventObject.COMPLETE, handler, target); } onceCompleteEvent(comp:dragonBones.ArmatureDisplay, handler:DB_EVENT_HANDLER, target?:any) { this.onceDBEvent(comp, dragonBones.EventObject.COMPLETE, handler, target); } removeCompleteEvent(comp:dragonBones.ArmatureDisplay, handler?:DB_EVENT_HANDLER, target?:any) { this.removeDBEvent(comp, dragonBones.EventObject.COMPLETE, handler, target); } //ArmatureDisplay资源加载完成前无法监听事件,用此方法可代替 addDBEvent(comp:dragonBones.ArmatureDisplay, eventType:string, handler:DB_EVENT_HANDLER, target?:any) { const key = comp.uuid + "_" + eventType; let eventTarget = this._eventMap.get(key); if(!eventTarget) { eventTarget = new cc.EventTarget(); this._eventMap.set(key, eventTarget); } return eventTarget.on(eventType, handler, target); } onceDBEvent(comp:dragonBones.ArmatureDisplay, eventType:string, handler:DB_EVENT_HANDLER, target?:any) { const key = comp.uuid + "_" + eventType; let eventTarget = this._eventMap.get(key); if(!eventTarget) { eventTarget = new cc.EventTarget(); this._eventMap.set(key, eventTarget); } return eventTarget.once(eventType, handler, target); } removeDBEvent(comp:dragonBones.ArmatureDisplay, eventType:string, handler?:DB_EVENT_HANDLER, target?:any) { const key = comp.uuid + "_" + eventType; const eventTarget = this._eventMap.get(key); if(!eventTarget) { return; } this._eventMap.delete(key); eventTarget.off(eventType, handler, target); } private invokeDBEvent(comp:dragonBones.ArmatureDisplay, eventType:string, ...params) { const key = comp.uuid + "_" + eventType; const eventTarget = this._eventMap.get(key); if(!eventTarget) { return; } eventTarget.emit(eventType, ...params); } releaseAsset(path:string) { const skePath = BasePathForSke(path); const texPath = BasePathForTex(path); cc.loader.releaseRes(skePath, dragonBones.DragonBonesAsset); cc.loader.releaseRes(texPath, dragonBones.DragonBonesAtlasAsset); cc.loader.releaseRes(texPath, cc.Texture2D); cc.log(`DragonBoneFactory, releaseAsset, path=${skePath}`); } releaseAll() { this._loadingMap.clear(); this._eventMap.clear(); this._stateMap.clear(); this._compPool.forEach(comp => { this.decreaseRef(comp); comp.destroy(); }); this._compPool.length = 0; } } interface ArmatureDisplayParams { path:string; //龙骨导出文件路径 armatureName:string; //骨架名称 onComplete?:DB_EVENT_HANDLER; onStart?:DB_EVENT_HANDLER; parent?:cc.Node; x?:number; y?:number; active?:boolean; } interface DBAsset { path:string; alias:string; type:typeof cc.Asset; }
the_stack
import { Ref, ref, computed } from '@vue/composition-api'; import { ScheduledElement } from '@/models'; import { addEventListeners } from '@/lib/events'; import { Keys, Disposer, Mouse } from '@/lib/std'; import { calculateSimpleSnap, slice, doSnap } from '@/utils'; import { SchedulablePrototype } from '@/models/schedulable'; import { getLogger } from '@/lib/log'; const logger = getLogger('grid'); // For more information see the following link: // https://stackoverflow.com/questions/4270485/drawing-lines-on-html-page function lineStyle( { x1, y1, x2, y2 }: { x1: number, y1: number, x2: number, y2: number }, ) { const a = x1 - x2; const b = y1 - y2; const c = Math.sqrt(a * a + b * b); const sx = (x1 + x2) / 2; const sy = (y1 + y2) / 2; const x = sx - c / 2; const y = sy; const alpha = Math.PI - Math.atan2(-b, a); return { border: '1px solid white', width: c + 'px', height: 0, transform: 'rotate(' + alpha + 'rad)', position: 'absolute', top: y + 'px', left: x + 'px', }; } type Line = ReturnType<typeof lineStyle>; type Element = ScheduledElement<any, any, any>; export type SequencerTool = 'pointer' | 'slicer'; export interface GridOpts<T extends Element> { sequence: T[]; pxPerBeat: Ref<number>; pxPerRow: Ref<number>; snap: Ref<number>; minSnap: Ref<number>; scrollLeft: Ref<number>; scrollTop: Ref<number>; beatsPerMeasure: Ref<number>; createElement: undefined | SchedulablePrototype<any, any, any>; getPosition: () => { left: number, top: number }; tool: Ref<SequencerTool>; } export const createGrid = <T extends Element>( opts: GridOpts<T>, ) => { const { pxPerBeat, pxPerRow, snap, minSnap, scrollLeft, scrollTop, beatsPerMeasure } = opts; let { sequence, createElement } = opts; // FIXME(Vue3) With Vue 3, we can move to a set I think const selected: T[] = []; const sDel = (el: T) => { const i = selected.indexOf(el); if (i === -1) { return; } selected.splice(i, 1); }; let holdingShift = false; const sequencerLoopEnd = ref(0); const disposers = new Set<Disposer>(); const mousedown = (e: MouseEvent) => { const generalDisposer = addEventListeners({ mousemove: () => { disposers.delete(generalDisposer); generalDisposer.dispose(); }, mouseup: () => { generalDisposer.dispose(); disposers.delete(generalDisposer); if (createElement) { addElement(e, createElement() as T); } }, }); disposers.add(generalDisposer); if (opts.tool.value === 'pointer') { selectStart.value = e; const disposer = addEventListeners({ mousemove: (event: MouseEvent) => { selectCurrent.value = event; }, mouseup: () => { selectStart.value = null; selectCurrent.value = null; disposers.delete(disposer); disposer.dispose(); }, }); disposers.add(disposer); } else if (opts.tool.value === 'slicer') { const rect = opts.getPosition(); const calculatePos = (event: MouseEvent) => { return { x: calculateSimpleSnap({ value: (event.clientX - rect.left) / pxPerBeat.value, altKey: event.altKey, minSnap: minSnap.value, snap: snap.value, }) * pxPerBeat.value, y: event.clientY - rect.top, }; }; const { x: x1, y: y1 } = calculatePos(e); const disposer = addEventListeners({ mousemove: (event) => { const { x: x2, y: y2 } = calculatePos(event); sliceStyle.value = { zIndex: 3, ...lineStyle({ x1, y1, x2, y2 }), }; }, mouseup: (event) => { const { x: x2, y: y2 } = calculatePos(event); const toAdd: T[] = []; sequence.forEach((element) => { const result = slice({ row: element.row.value, time: element.time.value, duration: element.duration.value, pxPerBeat: pxPerBeat.value, rowHeight: pxPerRow.value, x1, y1, x2, y2, }); if (result.result !== 'slice') { return; } const time = calculateSimpleSnap({ value: result.time, altKey: event.altKey, minSnap: minSnap.value, snap: snap.value, }); const newEl = element.slice(time); if (newEl) { toAdd.push(newEl as T); } }); sequence.push(...toAdd); sliceStyle.value = null; disposers.delete(disposer); disposer.dispose(); }, }); disposers.add(disposer); } }; const checkLoopEnd = () => { // Set the minimum to 1 measure! const maxTime = Math.max( ...sequence.map((item) => item.time.value + item.duration.value), beatsPerMeasure.value, ); const newLoopEnd = Math.ceil(maxTime / beatsPerMeasure.value) * beatsPerMeasure.value; if (newLoopEnd !== sequencerLoopEnd.value) { sequencerLoopEnd.value = newLoopEnd; } }; // Always call once at the start to initiate the loop end checkLoopEnd(); const displayBeats = computed(() => { return Math.max( 256, // 256 is completely random sequencerLoopEnd.value + beatsPerMeasure.value * 2, ); }); const addElement = (e: MouseEvent, el: T | undefined) => { if (!el) { return; } if (selected.length > 0) { selected.splice(0, selected.length); return; } const rect = opts.getPosition(); const time = doSnap({ position: e.clientX, minSnap: minSnap.value, snap: snap.value, pxPerBeat: pxPerBeat.value, offset: rect.left, scroll: scrollLeft.value, altKey: e.altKey, }); const row = doSnap({ position: e.clientY, minSnap: 1, snap: 1, pxPerBeat: pxPerRow.value, offset: rect.top, scroll: scrollTop.value, altKey: false, // irrelevant }); el.row.value = row; el.time.value = time; opts.sequence.push(el); checkLoopEnd(); return el; }; let initialMoveBeat: undefined | number; const move = (i: number, e: MouseEvent) => { if (initialMoveBeat === undefined) { return; } const el = sequence[i]; const rect = opts.getPosition(); const time = doSnap({ position: e.clientX, offset: rect.left, scroll: scrollLeft.value, altKey: e.altKey, snap: snap.value, minSnap: minSnap.value, pxPerBeat: pxPerBeat.value, }); const row = doSnap({ position: e.clientY, offset: rect.top, scroll: scrollTop.value, altKey: false, // irrelevant snap: 1, minSnap: 1, pxPerBeat: pxPerRow.value, }); const timeDiff = time - initialMoveBeat; const rowDiff = row - el.row.value; if (timeDiff === 0 && rowDiff === 0) { return; } let itemsToMove: readonly T[]; if (selected.includes(el)) { itemsToMove = selected; } else { itemsToMove = [el]; } const canMoveTime = itemsToMove.every((item) => item.time.value + timeDiff >= 0); const canMoveRow = itemsToMove.every((item) => item.row.value + rowDiff >= 0); if (!canMoveRow && !canMoveTime) { return; } if (canMoveTime) { initialMoveBeat = time; itemsToMove.forEach((item) => { item.time.value += timeDiff; }); checkLoopEnd(); } if (canMoveRow) { itemsToMove.forEach((item) => { item.row.value = item.row.value + rowDiff; }); } }; const updateAttr = (i: number, value: number, attr: 'offset' | 'duration') => { const el = sequence[i]; const diff = value - el[attr].value; let toUpdate: readonly T[]; if (selected.includes(el)) { toUpdate = selected; } else { toUpdate = [el]; } // If the diff is less than zero, make sure we aren't setting the offset of // any of the elements to < 0 if (diff < 0 && toUpdate.some((element) => (element[attr].value + diff) < 0)) { return; } toUpdate.forEach((element) => { element[attr].value += diff; }); }; const select = (e: MouseEvent, i: number) => { if (e.button !== Mouse.LEFT) { return; } const item = sequence[i]; const elIsSelected = selected.includes(item); if (!elIsSelected) { selected.splice(0, selected.length); } const createItem = (oldItem: T, addToSelected: boolean) => { const newItem = oldItem.copy(); // We set selected to true because `newNew` will have a higher z-index // Thus, it will be displayed on top (which we want) // Try copying selected files and you will notice the selected notes stay on top if (addToSelected) { selected.push(newItem as T); } sequence.push(newItem as T); }; if (holdingShift) { // If selected, copy all selected. If not, just copy the item that was clicked. if (elIsSelected) { const copy = selected.slice(); // First, clear the selected // We do this as the new elements will actually be the ones that are selected selected.splice(0, selected.length); // selected is all all selected except the element you pressed on copy.forEach((el) => { if (el === item) { // A copy of `item` will be created at this index which becomes the target for moving i = sequence.length; } createItem(el, true); }); } else { i = sequence.length; createItem(item, false); } } document.documentElement.style.cursor = 'move'; const rect = opts.getPosition(); initialMoveBeat = doSnap({ position: e.clientX, offset: rect.left, scroll: scrollLeft.value, altKey: e.altKey, snap: snap.value, minSnap: minSnap.value, pxPerBeat: pxPerBeat.value, }); const disposer = addEventListeners({ mousemove: (event) => move(i, event), mouseup: () => { document.documentElement.style.cursor = 'auto'; initialMoveBeat = undefined; disposer.dispose(); disposers.delete(disposer); }, }); disposers.add(disposer); }; const onMounted = () => { disposers.add(addEventListeners({ keydown: (e) => { if (e.keyCode === Keys.Shift) { holdingShift = true; } else if (e.keyCode === Keys.Delete || e.keyCode === Keys.Backspace) { for (const el of selected) { const i = sequence.indexOf(el); if (i === -1) { continue; } removeAtIndex(i); } } }, keyup: (e) => { if (e.keyCode === Keys.Shift) { holdingShift = false; } }, })); }; const removeAtIndex = (i: number) => { sequence.splice(i, 1); }; const remove = (i: number, e: MouseEvent) => { e.preventDefault(); removeAtIndex(i); }; const dispose = () => { disposers.forEach((disposer) => { disposer.dispose(); }); disposers.clear(); }; const selectStart = ref<MouseEvent>(null); const selectCurrent = ref<MouseEvent>(null); const sliceStyle = ref<Line & { zIndex: number }>(null); const selectStyle = computed(() => { if (!selectStart.value) { return; } if (!selectCurrent.value) { selected.splice(0, selected.length); return; } const rect = opts.getPosition(); const left = Math.min( selectStart.value.clientX - rect.left + scrollLeft.value, selectCurrent.value.clientX - rect.left + scrollLeft.value, ); const top = Math.min( selectStart.value.clientY - rect.top + scrollTop.value, selectCurrent.value.clientY - rect.top + scrollTop.value, ); const width = Math.abs(selectCurrent.value.clientX - selectStart.value.clientX); const height = Math.abs(selectCurrent.value.clientY - selectStart.value.clientY); // these are exact numbers BTW, not integers const minBeat = left / pxPerBeat.value; const minRow = top / pxPerRow.value; const maxBeat = (left + width) / pxPerBeat.value; const maxRow = (top + height) / pxPerRow.value; sequence.forEach((item) => { // Check if there is any overlap between the rectangles // https://www.geeksforgeeks.org/find-two-rectangles-overlap/ if (minRow > item.row.value + 1 || item.row.value > maxRow) { sDel(item); } else if (minBeat > item.time.value + item.duration.value || item.time.value > maxBeat) { sDel(item); } else { if (!selected.includes(item)) { selected.push(item); } } }); logger.debug('There are ' + selected.length + ' selected elements!'); return { borderRadius: '5px', border: 'solid 1px red', backgroundColor: 'rgba(255, 51, 51, 0.3)', left: `${left}px`, top: `${top}px`, height: `${height}px`, width: `${width}px`, zIndex: 3, }; }); return { selectStyle, sliceStyle, selected, move, updateOffset(i: number, value: number) { updateAttr(i, value, 'offset'); }, updateDuration(i: number, value: number) { updateAttr(i, value, 'duration'); // Make sure to check the loop end when the duration of an element has been changed!! checkLoopEnd(); }, remove, select, sequencerLoopEnd, displayBeats, onMounted, onUnmounted: dispose, dispose, add: (e: MouseEvent) => { if (createElement) { return addElement(e, createElement() as T); } }, mousedown, setSequence(s: T[]) { sequence = s; selected.splice(0, selected.length); checkLoopEnd(); }, setPrototype(s: SchedulablePrototype<any, any, any>) { createElement = s; }, }; };
the_stack
import shortid from 'shortid'; import AlarmEvents from './AlarmEvents'; import { checkIfProtected, showNumberOfCookiesInIcon, } from './BrowserActionService'; import { CADCOOKIENAME, cadLog, createPartialTabInfo, extractMainDomain, getAllCookiesForDomain, getHostname, getSetting, isAWebpage, isFirstPartyIsolate, returnOptionalCookieAPIAttributes, } from './Libs'; import StoreUser from './StoreUser'; export default class TabEvents extends StoreUser { public static onTabDiscarded( tabId: number, changeInfo: browser.tabs.TabChangeInfo, tab: browser.tabs.Tab, ): void { if (getSetting(StoreUser.store.getState(), SettingID.CLEAN_DISCARDED)) { const debug = getSetting( StoreUser.store.getState(), SettingID.DEBUG_MODE, ) as boolean; const partialTabInfo = createPartialTabInfo(tab); // Truncate ChangeInfo.favIconUrl as we have no use for it in debug. if (changeInfo.favIconUrl && debug) { changeInfo.favIconUrl = '***'; } if (changeInfo.discarded || tab.discarded) { cadLog( { msg: 'TabEvents.onTabDiscarded: Tab was discarded. Executing cleanFromTabEvents', x: { tabId, changeInfo, partialTabInfo }, }, debug, ); TabEvents.cleanFromTabEvents(); } else { cadLog( { msg: 'TabEvents.onTabDiscarded: Tab was not discarded.', x: { tabId, changeInfo, partialTabInfo }, }, debug, ); } } } public static onTabUpdate( tabId: number, changeInfo: browser.tabs.TabChangeInfo, tab: browser.tabs.Tab, ): void { if (tab.status === 'complete') { const debug = getSetting( StoreUser.store.getState(), SettingID.DEBUG_MODE, ) as boolean; const partialTabInfo = createPartialTabInfo(tab); // Truncate ChangeInfo.favIconUrl as we have no use for it in debug. if (changeInfo.favIconUrl && debug) { changeInfo.favIconUrl = '***'; } if (!TabEvents.onTabUpdateDelay) { TabEvents.onTabUpdateDelay = true; cadLog( { msg: 'TabEvents.onTabUpdate: action delay has been set for ~750 ms.', x: { tabId, changeInfo, partialTabInfo }, }, debug, ); setTimeout(() => { cadLog( { msg: 'TabEvents.onTabUpdate: actions will now commence.', x: { tabId, changeInfo, partialTabInfo }, }, debug, ); TabEvents.getAllCookieActions(tab); TabEvents.onTabUpdateDelay = false; cadLog( { msg: 'TabEvents.onTabUpdate: actions have been processed and flag cleared.', }, debug, ); }, 750); } else { cadLog( { msg: 'TabEvents.onTabUpdate: actions delay is pending already.', x: { tabId, changeInfo, partialTabInfo }, }, debug, ); } } } public static onDomainChange( tabId: number, changeInfo: browser.tabs.TabChangeInfo, tab: browser.tabs.Tab, ): void { const debug = getSetting( StoreUser.store.getState(), SettingID.DEBUG_MODE, ) as boolean; if (tab.status === 'complete') { const partialTabInfo = createPartialTabInfo(tab); const mainDomain = extractMainDomain(getHostname(tab.url)); // Truncate ChangeInfo.favIconUrl as we have no use for it in debug. if (changeInfo.favIconUrl && debug) { changeInfo.favIconUrl = '***'; } if (TabEvents.tabToDomain[tabId] === undefined && mainDomain !== '') { cadLog( { msg: 'TabEvents.onDomainChange: First mainDomain set.', x: { tabId, changeInfo, mainDomain, partialTabInfo }, }, debug, ); TabEvents.tabToDomain[tabId] = mainDomain; } else if ( TabEvents.tabToDomain[tabId] !== mainDomain && (mainDomain !== '' || tab.url === 'about:blank' || tab.url === 'about:home' || tab.url === 'about:newtab' || tab.url === 'chrome://newtab/') ) { const oldMainDomain = TabEvents.tabToDomain[tabId]; TabEvents.tabToDomain[tabId] = mainDomain; if ( getSetting(StoreUser.store.getState(), SettingID.CLEAN_DOMAIN_CHANGE) ) { if (oldMainDomain === '') { cadLog( { msg: 'TabEvents.onDomainChange: mainDomain has changed, but previous domain may have been a blank or new tab. Not executing domainChangeCleanup', x: { tabId, changeInfo, partialTabInfo }, }, debug, ); return; } cadLog( { msg: 'TabEvents.onDomainChange: mainDomain has changed. Executing domainChangeCleanup', x: { tabId, changeInfo, oldMainDomain, mainDomain, partialTabInfo, }, }, debug, ); TabEvents.cleanFromTabEvents(); } else { cadLog( { msg: 'TabEvents.onDomainChange: mainDomain has changed, but cleanOnDomainChange is not enabled. Not cleaning.', x: { tabId, changeInfo, oldMainDomain, mainDomain, partialTabInfo, }, }, debug, ); } } else { cadLog( { msg: 'TabEvents.onDomainChange: mainDomain has not changed yet.', x: { tabId, changeInfo, mainDomain, partialTabInfo }, }, debug, ); } } } public static onDomainChangeRemove( tabId: number, removeInfo: { windowId: number; isWindowClosing: boolean; }, ): void { cadLog( { msg: 'TabEvents.onDomainChangeRemove: Tab was closed. Removing old tabToDomain info.', x: { tabId, mainDomain: TabEvents.tabToDomain[tabId], removeInfo }, }, getSetting(StoreUser.store.getState(), SettingID.DEBUG_MODE) as boolean, ); delete TabEvents.tabToDomain[tabId]; } public static cleanFromTabEvents = async (): Promise<void> => { const debug = getSetting( StoreUser.store.getState(), SettingID.DEBUG_MODE, ) as boolean; if (getSetting(StoreUser.store.getState(), SettingID.ACTIVE_MODE)) { const alarm = await browser.alarms.get('activeModeAlarm'); if (!alarm || (alarm.name && alarm.name !== 'activeModeAlarm')) { cadLog( { msg: 'TabEvents.cleanFromTabEvents: No Alarms detected. Creating alarm for cleaning...', }, debug, ); await AlarmEvents.createActiveModeAlarm(); } else { cadLog( { msg: 'TabEvents.cleanFromTabEvents: An alarm for cleaning was created already. Cleaning will commence soon.', x: alarm, }, debug, ); } } }; public static getAllCookieActions = async ( tab: browser.tabs.Tab, ): Promise<void> => { if (!tab.url || tab.url === '') return; if (tab.url.startsWith('about:') || tab.url.startsWith('chrome:')) return; const debug = getSetting( StoreUser.store.getState(), SettingID.DEBUG_MODE, ) as boolean; const partialTabInfo = createPartialTabInfo(tab); const cookies = await getAllCookiesForDomain( StoreUser.store.getState(), tab, ); if (!cookies) { cadLog( { msg: 'TabEvents.getAllCookieActions: Libs.getAllCookiesForDomain returned undefined. Skipping Cookie Actions.', x: { partialTabInfo }, }, debug, ); return; } const internalCookies = cookies.filter((c) => { return c.name === CADCOOKIENAME; }); if ( internalCookies.length === 0 && (getSetting(StoreUser.store.getState(), SettingID.CLEANUP_CACHE) || getSetting(StoreUser.store.getState(), SettingID.CLEANUP_INDEXEDDB) || getSetting( StoreUser.store.getState(), SettingID.CLEANUP_LOCALSTORAGE, ) || getSetting(StoreUser.store.getState(), SettingID.CLEANUP_PLUGIN_DATA) || getSetting( StoreUser.store.getState(), SettingID.CLEANUP_SERVICE_WORKERS, )) && isAWebpage(tab.url) && !tab.url.startsWith('file:') ) { const cookiesAttributes = returnOptionalCookieAPIAttributes( StoreUser.store.getState(), { expirationDate: Math.floor(Date.now() / 1000 + 31557600), firstPartyDomain: (await isFirstPartyIsolate()) ? extractMainDomain(getHostname(tab.url)) : '', name: CADCOOKIENAME, path: `/${shortid.generate()}`, storeId: tab.cookieStoreId, url: tab.url, value: CADCOOKIENAME, }, ); await browser.cookies.set({ ...cookiesAttributes, url: tab.url }); cadLog( { msg: 'TabEvents.getAllCookieActions: A temporary cookie has been set for future BrowsingData cleaning as the site did not set any cookies yet.', x: { partialTabInfo, cadLSCookie: cookiesAttributes }, }, debug, ); } // Filter out cookie(s) that were set by this extension. const cookieLength = cookies.length - internalCookies.length; if (cookies.length !== cookieLength) { cadLog( { msg: 'TabEvents.getAllCookieActions: New Cookie Count after filtering out cookie set by extension', x: { preFilterCount: cookies.length, newCookieCount: cookieLength }, }, debug, ); } cadLog( { msg: 'TabEvents.getAllCookieActions: executing checkIfProtected to update Icons and Title.', }, debug, ); await checkIfProtected(StoreUser.store.getState(), tab, cookieLength); // Exclude Firefox Android for browser icons and badge texts if ( getSetting(StoreUser.store.getState(), SettingID.NUM_COOKIES_ICON) && (StoreUser.store.getState().cache.platformOs || '') !== 'android' ) { cadLog( { msg: 'TabEvents.getAllCookieActions: executing showNumberOfCookiesInIcon.', }, debug, ); showNumberOfCookiesInIcon(tab, cookieLength); } }; // Add a delay to prevent multiple spawns of the browsingDataCleanup cookie protected static onTabUpdateDelay = false; protected static tabToDomain: { [key: number]: string } = {}; }
the_stack
import * as vscode from "vscode"; import { executeCommand, ExpectedDocument, groupTestsByParentName } from "../utils"; suite("./test/suite/commands/seek.md", function () { // Set up document. let document: vscode.TextDocument, editor: vscode.TextEditor; this.beforeAll(async () => { document = await vscode.workspace.openTextDocument(); editor = await vscode.window.showTextDocument(document); editor.options.insertSpaces = true; editor.options.tabSize = 2; await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); }); this.afterAll(async () => { await executeCommand("workbench.action.closeActiveEditor"); }); test("1 > select-to-included", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcabc | 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "c", include: true }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:8:1", 6, String.raw` abcabc ^^^ 0 `); }); test("1 > select-to-included > select-to", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcabc ^^^ 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "c" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:18:1", 6, String.raw` abcabc ^^ 0 `); }); test("1 > select-to-included > select-to-character", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcabc ^^^ 0 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek", { input: "c" }); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:28:1", 6, String.raw` abcabc ^^^ 0 `); }); test("1 > select-to-c-2", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcabc | 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "c", count: 2 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:40:1", 6, String.raw` abcabc ^^^^^ 0 `); }); test("1 > select-to-c-2 > select-to-c", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcabc ^^^^^ 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "c", $expect: /^no selections remain$/ }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:50:1", 6, String.raw` abcabc ^^^^^ 0 `); }); test("1 > select-to-c-2 > select-to-c > select-to-b-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcabc ^^^^^ 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "b", direction: -1 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:60:1", 6, String.raw` abcabc | 0 `); }); test("1 > select-to-c-2 > select-to-c > select-to-b-backward > select-to-a-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcabc | 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "a", direction: -1 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:70:1", 6, String.raw` abcabc ^ 0 `); }); test("1 > select-to-c-2 > select-to-c-character", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcabc ^^^^^ 0 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek", { input: "c", $expect: /^no selections remain$/ }); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:80:1", 6, String.raw` abcabc ^^^^^ 0 `); }); test("1 > select-to-c-2 > select-to-c-character > select-to-b-character", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcabc ^^^^^ 0 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek", { input: "b", direction: -1 }); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:92:1", 6, String.raw` abcabc |^^ 0 `); }); test("2 > extend-to-e-included-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcdefghijk ^^^^ 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "e", direction: -1, shift: "extend", include: true }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:109:1", 6, String.raw` abcdefghijk ^^ 0 `); }); test("2 > extend-to-g-included-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcdefghijk ^^^^ 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "g", direction: -1, shift: "extend", include: true }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:119:1", 6, String.raw` abcdefghijk ^^^^ 0 `); }); test("2 > extend-to-d-included-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcdefghijk ^^^^ 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "d", direction: -1, shift: "extend", include: true }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:131:1", 6, String.raw` abcdefghijk ^ 0 `); }); test("2 > extend-to-b-included-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcdefghijk ^^^^ 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "b", direction: -1, shift: "extend", include: true }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:141:1", 6, String.raw` abcdefghijk |^ 0 `); }); test("2 > extend-to-b-backward-character", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcdefghijk ^^^^ 0 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek", { input: "b", direction: -1, shift: "extend", include: true }); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:151:1", 6, String.raw` abcdefghijk |^^ 0 `); }); test("2 > extend-to-g-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcdefghijk ^^^^ 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "g", direction: -1, shift: "extend" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:163:1", 6, String.raw` abcdefghijk ^^^^ 0 `); }); test("2 > extend-to-f-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcdefghijk ^^^^ 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "f", direction: -1, shift: "extend" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:175:1", 6, String.raw` abcdefghijk ^^^ 0 `); }); test("2 > extend-to-e-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcdefghijk ^^^^ 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "e", direction: -1, shift: "extend" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:185:1", 6, String.raw` abcdefghijk ^^ 0 `); }); test("2 > extend-to-c-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcdefghijk ^^^^ 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "c", direction: -1, shift: "extend" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:195:1", 6, String.raw` abcdefghijk | 0 `); }); test("2 > extend-to-b-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` abcdefghijk ^^^^ 0 `); // Perform all operations. await executeCommand("dance.seek", { input: "b", direction: -1, shift: "extend" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek.md:205:1", 6, String.raw` abcdefghijk ^ 0 `); }); groupTestsByParentName(this); });
the_stack
import * as path from 'path' import { Octokit } from 'probot' import { Maybe } from './data/maybe' import { Dict, mapEntriesAsync } from './data/dict' import { not, withDefault } from './utils' /** * Loads a file from Github. * * @param octokit * @param path */ export async function getFile( octokit: Octokit, { owner, repo, ref }: { owner: string; repo: string; ref: string }, path: string, ): Promise<Maybe<string>> { try { const res = await octokit.repos.getContents({ owner: owner, path: path, repo: repo, ref: ref, }) switch (res.status) { case 200: { // expect a single file /* istanbul ignore if */ if (Array.isArray(res.data) || !res.data.content) return null return Buffer.from(res.data.content, 'base64').toString() } /* istanbul ignore next */ default: { return null } } } catch (err) /* istanbul ignore next */ { return null } } export interface GithubLabel { /* Naming */ old_name?: string name: string /* Description */ old_description?: string description?: string /* Colors */ old_color?: string color: string default?: boolean } /** * Fetches labels in a repository. */ export async function getRepositoryLabels( github: Octokit, { repo, owner }: { repo: string; owner: string }, ): Promise<Octokit.IssuesListLabelsForRepoResponseItem[]> { let labels: Octokit.IssuesListLabelsForRepoResponseItem[] = [] /* Github paginates from page 1 */ await handler(1) return labels /* Paginates and performs changes. */ async function handler(page: number) { const repoLabels = await github.issues .listLabelsForRepo({ owner, repo, per_page: 100, page: page, }) .then((res) => res.data) labels.push(...repoLabels) /* Rerun handler if there are more labels available. */ /* istanbul ignore next */ if (repoLabels.length === 100) { await handler(page + 1) } } } /** * Create new labels in a repository. */ export async function addLabelsToRepository( github: Octokit, { repo, owner }: { repo: string; owner: string }, labels: Pick<GithubLabel, 'name' | 'color'>[], persist: boolean, ): Promise<GithubLabel[]> { /* Return immediately on non-persistent sync. */ if (!persist) return labels /* Perform sync on persist. */ const actions = labels.map((label) => addLabelToRepository(label)) await Promise.all(actions) return labels /** * Helper functions */ async function addLabelToRepository( label: GithubLabel, ): Promise<GithubLabel> { try { const ghLabel = await github.issues.createLabel({ owner: owner, repo: repo, name: label.name, description: label.description, color: label.color, }) return ghLabel.data } catch (err) /* istanbul ignore next */ { throw new Error( `Couldn't create ${label.name} in ${owner}/${repo}: ${err.message}`, ) } } } /** * * Updates labels in repository. * * When old_name is specified in the label, we try to rename the label. */ export async function updateLabelsInRepository( github: Octokit, { repo, owner }: { repo: string; owner: string }, labels: GithubLabel[], persist: boolean, ): Promise<GithubLabel[]> { /* Return immediately on non-persistent sync. */ if (!persist) return labels /* Update values on persist. */ const actions = labels.map((label) => updateLabelInRepository(label)) await Promise.all(actions) return labels /** * Helper functions */ async function updateLabelInRepository( label: GithubLabel, ): Promise<GithubLabel> { try { const ghLabel = await github.issues.updateLabel({ current_name: withDefault(label.name, label.old_name), owner: owner, repo: repo, name: label.name, description: label.description, color: label.color, }) return ghLabel.data } catch (err) /* istanbul ignore next */ { throw new Error( `Couldn't update ${label.name} in ${owner}/${repo}: ${err.message}`, ) } } } /** * Removes labels from repository. */ export async function removeLabelsFromRepository( github: Octokit, { repo, owner }: { repo: string; owner: string }, labels: GithubLabel[], persist: boolean, ): Promise<GithubLabel[]> { /* Return immediately on non-persistent sync. */ if (!persist) return labels const actions = labels.map((label) => removeLabelFromRepository(label)) await Promise.all(actions) return labels /** * Helper functions */ async function removeLabelFromRepository( label: GithubLabel, ): Promise<Octokit.IssuesDeleteLabelParams> { try { const ghLabel = await github.issues.deleteLabel({ owner: owner, repo: repo, name: label.name, }) return ghLabel.data } catch (err) /* istanbul ignore next */ { throw new Error( `Couldn't remove ${label.name} in ${owner}/${repo}: ${err.message}`, ) } } } /** * Aliases labels in a repository by adding them to labels. */ export async function aliasLabelsInRepository( github: Octokit, { repo, owner }: { repo: string; owner: string }, labels: GithubLabel[], persist: boolean, ): Promise<GithubLabel[]> { let page = 1 /* Skip on no labels */ if (labels.length === 0) return labels await handler() return labels /* Paginates and performs changes. */ async function handler() { const issues = await github.issues .listForRepo({ owner, repo, per_page: 100, page, }) .then((res) => res.data) /* Process all the issues. */ for (const issue of issues) { /* Filter labels that should be in this issue but are not. */ const missingLabels = labels.filter((label) => issue.labels.some((issueLabel) => issueLabel.name === label.old_name), ) if (missingLabels.length === 0) continue /* Add all the missing labels. */ await addLabelsToIssue( github, { repo, owner, issue: issue.number }, missingLabels, persist, ) } /* Rerun handler if there are more issues available. */ /* istanbul ignore next */ if (issues.length === 100) { page += 1 await handler() } } } /** * Adds labels to an issue. */ export async function addLabelsToIssue( github: Octokit, { repo, owner, issue }: { repo: string; owner: string; issue: number }, labels: Pick<GithubLabel, 'name'>[], persist: boolean, ): Promise<Pick<GithubLabel, 'name'>[]> { /* Return immediately on non-persistent sync. */ /* istanbul ignore next */ if (!persist) return labels const ghLabels = await github.issues .addLabels({ repo, owner, issue_number: issue, labels: labels.map((label) => label.name), }) .then((res) => res.data) return ghLabels } /** * Compares two labels by comparing all of their keys. */ export function isLabel(local: GithubLabel): (remote: GithubLabel) => boolean { return (remote) => local.name === remote.name && local.description === remote.description && local.color === remote.color } /** * Determines whether the two configurations configure the same label. */ export function isLabelDefinition( local: GithubLabel, ): (remote: GithubLabel) => boolean { return (remote) => local.name === remote.name } /** * Opens an issue with a prescribed title and body. */ export async function openIssue( octokit: Octokit, owner: string, repo: string, title: string, body: string, ): Promise<Octokit.IssuesCreateResponse> { return octokit.issues .create({ repo: repo, owner: owner, title: title, body: body, }) .then(({ data }) => data) } // /** // * Closes the issue openned by the LabelSync configuration. // * // * @param octokit // * @param owner // * @param repo // * @param title // */ // export async function closeIssue( // octokit: Octokit, // owner: string, // repo: string, // title: string, // ) { // const issues = await octokit.issues.listForRepo({ // owner: owner, // repo: repo, // creator: 'labelsync-manager', // }) // } /** * Creates a comment on a dedicated pull request. */ export async function createPRComment( octokit: Octokit, owner: string, repo: string, number: number, message: string, ): Promise<Octokit.IssuesCreateCommentResponse> { return octokit.issues .createComment({ owner: owner, repo: repo, body: message, issue_number: number, }) .then(({ data }) => data) } /** * Tries to fetch a repository. */ export async function getRepo( github: Octokit, owner: string, repo: string, ): Promise< { status: 'Exists'; repo: Octokit.ReposGetResponse } | { status: 'Unknown' } > { return github.repos .get({ owner: owner, repo: repo, }) .then((res) => { switch (res.status) { case 200: { return { status: 'Exists' as const, repo: res.data } } /* istanbul ignore next */ default: { return { status: 'Unknown' as const } } } }) .catch(() => { return { status: 'Unknown' as const } }) } type GHRepo = { owner: string; repo: string } /** * Represents a Github file/folder structure. * * Files should be utf-8 strings. */ export type GHTree = { [path: string]: string } /** * Returns the files that are not nested. */ function getTreeFiles(tree: GHTree): Dict<string> { return Object.fromEntries( Object.keys(tree) .filter(isFileInThisFolder) .map((name) => [name, tree[name]]), ) } /** * Returns a dictionary of remaining subtrees. */ function getTreeSubTrees(tree: GHTree): Dict<GHTree> { return Object.keys(tree) .filter(not(isFileInThisFolder)) .reduce<Dict<GHTree>>((acc, filepath) => { const [subTree, newFilepath] = shiftPath(filepath) if (!acc.hasOwnProperty(subTree)) { acc[subTree] = {} } acc[subTree][newFilepath] = tree[filepath] return acc }, {}) } /** * Shifts path by one. * Returns the shifted part as first argument and remaining part as second. */ function shiftPath(filepath: string): [string, string] { const [dir, ...dirs] = filepath.split('/').filter(Boolean) return [dir, dirs.join('/')] } /** * Determines whether a path references a direct file * or a file in the nested folder. * * "/src/index.ts" -> false * "/index.ts" -> true * "index.ts" -> true */ function isFileInThisFolder(filePath: string): boolean { return ['.', '/'].includes(path.dirname(filePath)) } /** * Recursively creates a tree commit by creating blobs and generating * trees on folders. */ async function createGhTree( github: Octokit, { owner, repo }: GHRepo, tree: GHTree, ): Promise<{ sha: string }> { /** * Uploads blobs and creates subtrees. */ const blobs = await mapEntriesAsync(getTreeFiles(tree), (content) => createGhBlob(github, { owner, repo }, content), ) const trees = await mapEntriesAsync(getTreeSubTrees(tree), (subTree) => createGhTree(github, { owner, repo }, subTree), ) return github.git .createTree({ owner, repo, tree: [ ...Object.entries(trees).map(([treePath, { sha }]) => ({ mode: '040000' as const, type: 'tree' as const, path: treePath, sha, })), ...Object.entries(blobs).map(([filePath, { sha }]) => ({ mode: '100644' as const, type: 'blob' as const, path: filePath, sha, })), ], }) .then((res) => res.data) } /** * Creates a Github Blob from a File. */ async function createGhBlob( github: Octokit, { owner, repo }: GHRepo, content: string, ): Promise<Octokit.GitCreateBlobResponse> { return github.git.createBlob({ owner, repo, content }).then((res) => res.data) } /** * Bootstraps a configuration repository to a prescribed destination. * * Assumes repository is empty. * * @param github * @param owner * @param repo */ export async function bootstrapConfigRepository( github: Octokit, { owner, repo }: GHRepo, tree: GHTree, ): Promise<Octokit.GitUpdateRefResponse> { await github.repos .createInOrg({ org: owner, name: repo, description: 'LabelSync configuration repository.', auto_init: true, }) .then((res) => res.data) const gitTree = await createGhTree(github, { owner, repo }, tree) const masterRef = await github.git .getRef({ owner, repo, ref: 'heads/master', }) .then((res) => res.data) const commit = await github.git .createCommit({ owner, repo, message: ':sparkles: Scaffold configuration', tree: gitTree.sha, parents: [masterRef.object.sha], }) .then((res) => res.data) const ref = await github.git.updateRef({ owner, repo, ref: 'heads/master', sha: commit.sha, }) return ref.data } export type InstallationAccess = | { status: 'Sufficient' } | { status: 'Insufficient'; missing: string[]; accessible: string[] } /** * Determines whether LabelSync can access all requested repositories. * @param github * @param repos */ export async function checkInstallationAccess( github: Octokit, configRepos: string[], ): Promise<InstallationAccess> { /* istanbul ignore if */ if (configRepos.length === 0) return { status: 'Sufficient' } /* Paginate through repos. */ let accessRepos: string[] = [] let page = 1 await handler() const missing = configRepos.filter((repo) => !accessRepos.includes(repo)) if (missing.length === 0) { return { status: 'Sufficient' } } return { status: 'Insufficient', missing: missing, accessible: accessRepos, } async function handler() { const res = await github.apps .listRepos({ per_page: 100, page }) .then((res) => res.data) /* Push to collection */ accessRepos.push(...res.repositories.map((repo) => repo.name.toLowerCase())) /* istanbul ignore if */ if (res.repositories.length === 100) { page += 1 await handler() } } }
the_stack
type PrimitiveTime = string | number; type PrimitiveTicks = number; declare module 'tone' { var context: Context; class Tone { constructor(inputs?: number, outputs?: number); context: Context; toFrequency(freq: any): number; toSeconds(time?: _TimeArg): number; toTicks(time: _TimeArg): number; now(): number; sampleTime: number; static connectSeries(...args: any[]): Tone; static dbToGain(db: number): number; static defaultArg(given: any, fallback: any): any; static defaults(): object; static isFunction(arg: any): boolean; static isArray(arg: any): boolean; static isNumber(arg: any): boolean; static isString(arg: any): boolean; static isObject(arg: any): boolean; static now(): number; static isDefined(arg: any): boolean; protected _readOnly(property: keyof this & string): void; } class Abs extends SignalBase { dispose(): this; } class Add extends Signal { constructor(value?: number); dispose(): this; } class AmplitudeEnvelope extends Envelope { constructor(attack?: any, decay?: _TimeArg, sustain?: number, release?: _TimeArg); //FIXME: Change 'any' to '_TimeArg | Object' dispose(): this; } class AMSynth extends Monophonic { constructor(options?: Object); carrier: MonoSynth; frequency: Signal; harmonicity: number; modulator: MonoSynth; dispose(): this; triggerEnvelopeAttack(time?: _TimeArg, velocity?: number): AMSynth; triggerEnvelopeRelease(time?: _TimeArg): AMSynth; } class AND extends SignalBase { constructor(inputCount?: number); dispose(): this; } class AudioToGain extends SignalBase { constructor(); dispose(): this; } class AudioNode { // toMaster(): this; disconnect(output: number | AudioNode): this; // chain(...nodes: AudioNode[]): this; connect(unit: Tone | AudioParam | AudioNode, outputNum?: number, inputNum?: number): this; // dispose(): this; } class AutoPanner extends Effect { constructor(frequency?: any); //FIXME: Number || Object amount: Signal; frequency: Signal; type: string; dispose(): this; start(time?: Time): AutoPanner; stop(time?: _TimeArg): AutoPanner; sync(): AutoPanner; unsync(): AutoPanner; } class AutoWah extends Effect { constructor(baseFrequency?: any, octaves?: number, sensitivity?: number); //Todo number | Object baseFrequency: Frequency; gain: Signal; octaves: number; Q: Signal; sensitivity: number; dispose(): this; } class BitCrusher extends Effect { constructor(bits?: number); bits: number; dispose(): this; } class Buffer extends Tone { constructor(url: AudioBuffer | string); MAX_SIMULTANEOUS_DOWNLOADS: number; duration: number; // Readonly loaded: boolean; // Readonly onload: (e: any) => any; url: string; // Readonly static load(url: string, onload: (buff: AudioBuffer) => void, onerror: (e: Error) => void): void; load(url: string, callback?: (e: any) => any): Buffer; onerror(): void; onprogress(): void; dispose(): this; get(): AudioBuffer; set(buffer: any): Buffer; //FIXME: change any to AudioBuffer | Buffer } interface BufferSourceOptions { onended?: (source: BufferSource) => void; onload?: () => void; loop?: boolean; loopStart?: number; loopEnd?: number; fadeIn?: number; fadeOut?: number; playbackRate?: number; buffer: AudioBuffer; } class BufferSource extends AudioNode { constructor(options: BufferSourceOptions) start(startTime?: _TimeArg, offset?: _TimeArg, duration?: _TimeArg): this; stop(time?: _TimeArg): void; } class Chebyshev extends Effect { constructor(order: any); //FIXME: Number || Object order: number; oversample: string; dispose(): this; } class Chorus extends StereoXFeedbackEffect { constructor(rate?: any, delayTime?: number, depth?: number); delayTime: number depth: number; frequency: Signal; type: string; dispose(): this; } class Clip extends SignalBase { constructor(min: number, max: number); max: Signal; min: Signal; dispose(): this; } interface _Clock { callback: (tickTime: number, ticks: number) => void, frequency: number, } class Clock extends Emitter<{ start: [number, number], stop: [number], pause: [number] }> { constructor(options: _Clock); frequency: TickSignal; seconds: number; ticks: number; state: TransportState; setTicksAtTime(ticks: number, time: _TimeArg): void; getSecondsAtTime(time: _TimeArg): number; getStateAtTime(time: _TimeArg): TransportState; getTicksAtTime(time: PrimitiveTime): PrimitiveTicks; start(time?: PrimitiveTime, offset?: PrimitiveTicks): void; stop(time?: PrimitiveTime): void; pause(time?: PrimitiveTime): void; } class Compressor extends AudioNode { constructor(threshold?: any, ratio?: number); //FIXME: Number || Object attack: Signal; knee: AudioParam; ratio: AudioParam; release: Signal; threshold: AudioParam; dispose(): this; } class Context extends Emitter<{ tick: any }> { resume(): Promise<void>; now(): number; decodeAudioData(audioData: ArrayBuffer): Promise<AudioBuffer>; createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; createStereoPanner(): StereoPannerNode; } class Convolver extends Effect { constructor(url: any); //FIXME: Change any to 'string | AudioBuffer' when available buffer: AudioBuffer; load(url: string, callback?: (e: any) => any): Convolver; dispose(): this; } class CrossFade extends Tone { constructor(initialFade?: number); a: Gain; b: Gain; fade: Signal; dispose(): this; } class Distortion extends Effect { constructor(distortion?: number); distortion: number; oversample: string; dispose(): this; } class DuoSynth extends Monophonic { constructor(options?: any); frequency: Signal; harmonicity: number; vibratoAmount: Signal; vibratoRate: Signal; voice0: MonoSynth; voice1: MonoSynth; triggerEnvelopeAttack(time?: _TimeArg, velocity?: number): DuoSynth; triggerEnvelopeRelease(time?: _TimeArg): DuoSynth; } class Effect extends AudioNode { constructor(initialWet?: number); wet: Signal; bypass(): Effect; dispose(): this; } class Emitter<T extends { [k: string]: any[] }, V extends keyof T = keyof T> extends Tone { emit<Z extends V>(event: Z, ...args: T[Z]): this; on<Z extends V>(event: Z, callback: (...args: T[Z]) => void): this; once<Z extends V>(event: Z, callback: (...arg: T[Z]) => void): this; off<Z extends V>(event: Z, callback: (...arg: T[Z]) => void): this; } class Envelope extends Tone { constructor(attack: any, decay?: _TimeArg, sustain?: number, release?: _TimeArg); //FIXME: Change 'any' to '_TimeArg | Object' attack: _TimeArg; decay: _TimeArg; release: _TimeArg; sustain: number; dispose(): this; triggerAttack(time?: _TimeArg, velocity?: number): Envelope; triggerAttackRelease(duration: _TimeArg, time?: _TimeArg, velocity?: number): Envelope; triggerRelease(time?: _TimeArg): Envelope; } class EQ3 extends AudioNode { constructor(lowLevel?: any, midLevel?: number, highLevel?: number); //FIXME: Change 'any' to 'number | Object' highFrequency: Signal; high: Gain; lowFrequency: Signal; low: Gain; mid: Gain; dispose(): this; } class Equal extends SignalBase { constructor(value: number); value: number; dispose(): this; } class EqualPowerGain extends SignalBase { constructor(); dispose(): this; } class EqualZero extends SignalBase { constructor(); dispose(): this; } class Expr extends SignalBase { constructor(expr: string); input: any; //todo: any[] output: any; // todo: tone dispose(): this; } class FeedbackCombFilter extends Tone { constructor(minDelay?: number, maxDelay?: number); delayTime: _TimeArg; resonance: Signal; dispose(): this; } class FeedbackDelay extends FeedbackEffect { constructor(delayTime: any); delayTime: Signal; dispose(): this; } class FeedbackEffect extends Effect { constructor(initialFeedback?: any) feedback: Signal; dispose(): this; } class FFT extends AudioNode { size: Number; getValue(): Float32Array; } class Filter extends Tone { constructor(freq?: any, type?: string, rolloff?: number); //FIXME: Number || Object detune: Signal; frequency: Signal; gain: AudioParam; Q: Signal; rolloff: number; type: string; dispose(): this; } class FMSynth extends Monophonic { constructor(options?: any); carrier: MonoSynth; frequency: Signal; harmonicity: number; modulationIndex: number; modulator: MonoSynth; dispose(): this; triggerEnvelopeAttack(time?: _TimeArg, velocity?: number): FMSynth; triggerEnvelopeRelease(time?: _TimeArg): FMSynth; } class Follower extends Tone { constructor(attack?: _TimeArg, release?: _TimeArg); attack: _TimeArg; release: _TimeArg; dispose(): this; } class Freeverb extends Effect { constructor(roomSize?: any, dampening?: number); dampening: Signal; roomSize: Signal; dispose(): this; } class TimeBase { valueOf(): number; // returns seconds dispose(): TimeBase; } class Frequency extends TimeBase { constructor(val: string | number, units?: string); toMidi(): number; toNote(): string; transpose(interval: number): Frequency; harmonize(intervals: number[]): Frequency; toSeconds(): number; toTicks(): number; midiToFrequency(midi: string): Frequency; frequencyToMidi(frequency: Frequency): string; } class Gate extends Tone { constructor(thresh?: number, attackTime?: _TimeArg, releaseTime?: _TimeArg); attack: _TimeArg; release: _TimeArg; threshold: _TimeArg; dispose(): this; } class Gain extends AudioNode { gain: Signal; } class GreaterThan extends Signal { constructor(value?: number); dispose(): this; } class GreaterThanZero extends SignalBase { dispose(): this; } class IfThenElse extends SignalBase { dispose(): this; } class Instrument extends AudioNode { volume: Signal; triggerAttackRelease(note: any, duration: _TimeArg, time?: _TimeArg, velocity?: number): Instrument; //Todo: string | number dispose(): this; } class IntervalTimeline extends Tone { } class JCReverb extends Effect { constructor(roomSize: number); //FIXME: Number || Object roomSize: Signal; dispose(): this; } class LessThan extends Signal { constructor(value?: number); dispose(): this; } class LFO extends Oscillator { constructor(frequency?: _TimeArg, outputMin?: number, outputMax?: number); //FIXME: Number || Object amplitude: Signal; frequency: Signal; max: number; min: number; oscillator: Oscillator; phase: number; type: string; dispose(): this; start(time?: _TimeArg): LFO; stop(time?: _TimeArg): LFO; sync(delay?: _TimeArg): LFO; unsync(): LFO; } class Limiter extends AudioNode { constructor(threshold?: AudioParam); dispose(): this; } class LowpassCombFilter extends Tone { constructor(minDelay?: number, maxDelay?: number) dampening: Signal; delayTime: _TimeArg; resonance: Signal; dispose(): this; setDelayTimeAtTime(delayAmount: _TimeArg, time?: _TimeArg): LowpassCombFilter; } var Master: MasterClass; class MasterClass extends AudioNode { volume: Signal; mute: boolean; // receive(node: any): MasterClass; //todo: AudioNode | tone // send(node: any): MasterClass; //todo: AudioNode | tone } class Max extends Signal { constructor(max?: number); dispose(): this; } class Merge extends AudioNode { constructor(); left: Gain; right: Gain; dispose(): this; } class Meter extends AudioNode { constructor(channels?: number, smoothing?: number, clipMemory?: number); dispose(): this; getDb(channel?: number): number; getLevel(channel?: number): number; getValue(channel?: number): number; isClipped(): boolean; } class Microphone extends Source { constructor(inputNum?: number); dispose(): this; } class MidSideEffect extends StereoEffect { midReturn: Gain; midSend: Expr; sideReturn: Gain; sideSend: Expr; dispose(): this; } class Min extends Signal { constructor(min: number); dispose(): this; } class Modulo extends SignalBase { constructor(modulus: number, bits?: number); value: number; dispose(): this; } class Mono extends Tone { constructor(); dispose(): this; } class Monophonic extends Instrument { constructor(); portamento: _TimeArg; setNote(note: any): Monophonic; //Todo: number | string triggerAttack(note: any, time?: PrimitiveTime, velocity?: number): void; triggerRelease(time?: PrimitiveTime): void; } class MonoSynth extends Monophonic { constructor(options?: any); detune: Signal; envelope: Envelope; filter: Filter; filterEnvelope: Envelope; frequency: Signal; oscillator: OmniOscillator; dispose(): this; triggerEnvelopeAttack(time?: _TimeArg, velocity?: number): MonoSynth; triggerEnvelopeRelease(time?: _TimeArg): MonoSynth; } class MultibandCompressor extends Tone { constructor(options: Object); high: Compressor; highFrequency: Signal; low: Compressor; lowFrequency: Signal; mid: Compressor; dispose(): this; } class MultibandEQ extends Tone { constructor(options?: any); //set(params: Object): void; setType(type: string, band: number): void; getType(band: number): string; setFrequency(freq: number, band: number): void; getFrequency(band: number): number; setQ(Q: number, band: number): void; getQ(band: number): number; getGain(band: number): number; setGain(gain: number, band: number): void; } class MultibandSplit extends Tone { constructor(lowFrequency: number, highFrequency: number); high: Filter; highFrequency: Signal; low: Filter; lowFrequency: Signal; mid: Filter; dispose(): this; } class Multiply extends Signal { constructor(value?: number); dispose(): this; } class Negate extends SignalBase { constructor(); dispose(): this; } class Noise extends Source { constructor(type: string); type: string; dispose(): this; } class NoiseSynth extends Instrument { constructor(options?: Object); envelope: Envelope; filter: Filter; filterEnvelope: Envelope; noise: Noise; dispose(): this; triggerAttack(time?: _TimeArg, velocity?: number): NoiseSynth; triggerAttackRelease(duration: _TimeArg, time?: _TimeArg, velocity?: number): NoiseSynth; triggerRelease(time?: _TimeArg): NoiseSynth; } class Normalize extends SignalBase { constructor(min?: number, max?: number); max: number; min: number; dispose(): this; } class Note { constructor(channel: any, time: _TimeArg, value: any); //todo: channel: number|string, value: string|number|Object|Array value: any; //todo: string | number | Object parseScore(score: Object): Note[]; route(channel: any, callback?: (e: any) => any): void; //todo: string | number unroute(channel: any, callback?: (e: any) => any): void; //todo: string | number; dispose(): this; } class OfflineContext extends Context { constructor(channels: number, duration: number, sampleRate: number); render(): Promise<void>; } class OmniOscillator extends Source { constructor(frequency?: Frequency, type?: string); //FIXME: Number || Object detune: Signal; frequency: Signal; modulationFrequency: Signal; phase: number; type: string; width: Signal; dispose(): this; } class OR extends SignalBase { constructor(inputCount?: number); dispose(): this; } class Oscillator extends Source { constructor(frequency?: any, type?: string); //todo: number | string detune: Signal; frequency: Signal; phase: number; type: string; dispose(): this; syncFrequency(): Oscillator; unsyncFrequency(): Oscillator; } class Panner extends AudioNode { constructor(initialPan?: number); pan: Signal; dispose(): this; } class PanVol extends Tone { constructor(pan: number, volume: number); output: Gain; volume: Signal; dispose(): this; } type AutomationType = 'linearRampToValueAtTime' | 'exponentialRampToValueAtTime' | 'setTargetAtTime' | 'setValueAtTime' | 'cancelScheduledValues' class Param extends AudioNode { value: number; minValue: number; maxValue: number; getValueAtTime(time: _TimeArg): number; } class Part<T> extends Event { constructor(callback?: (time: string, value: T) => void, events?: Event[]) start(time: number, offset?: _TimeArg): void; loop: boolean readonly progress: number; mute: boolean; readonly state: 'started' | 'stopped'; humanize: boolean loopEnd: _TimeArg loopStart: _TimeArg add(time: _TimeArg, value: T): void // FIXME remove(time: _TimeArg, value: T): void // FIXME } class Phaser extends StereoEffect { constructor(rate?: any, depth?: number, baseFrequency?: number); //FIXME: change 'any' to 'number | Object' baseFrequency: number; depth: number; frequency: Signal; dispose(): this; } class PingPongDelay extends StereoXFeedbackEffect { constructor(delayTime?: any, feedback?: number); //FIXME: _TimeArg || Object delayTime: Signal; dispose(): this; } class Player extends Source { constructor(url?: string | AudioBuffer, onload?: (e: any) => any); //todo: string | AudioBuffer buffer: Buffer; duration: number; loop: boolean; loopEnd: _TimeArg; loopStart: _TimeArg; playbackRate: number; retrigger: boolean; autostart: boolean; dispose(): this; load(url: string, callback?: (e: any) => any): Player; setLoopPoints(loopStart: _TimeArg, loopEnd: _TimeArg): Player; } class PluckSynth extends Instrument { constructor(options?: Object); attackNoise: number; dampening: Signal; resonance: Signal; dispose(): this; triggerAttack(note: any, time?: _TimeArg): PluckSynth; //todo: string | number } // @ts-ignore class PolySynth extends Instrument { constructor(voicesAmount?: number, voice?: { new(): Synth }); // number | Object voices: any[]; dispose(): this; get(params?: any[]): any; set(params: Object): void; setPreset(presetName: string): this; triggerAttack(notes: any, time?: _TimeArg, velocity?: number): this; //todo: string | number | Object| string[] | number[] triggerAttackRelease(notes: any, duration: _TimeArg, time?: _TimeArg, velocity?: number): this; //todo: string | number | Object | string[] | number[] triggerRelease(value: string | string[], time?: _TimeArg): this; //todo: string | number | Object | string[] | number[] } class Pow extends SignalBase { constructor(exp: number); value: number; dispose(): this; } class PulseOscillator extends Oscillator { constructor(frequency?: number, width?: number); detune: Signal; frequency: Signal; phase: number; width: Signal; dispose(): this; } class PWMOscillator extends Oscillator { constructor(frequency?: Frequency, modulationFrequency?: number); detune: Signal; frequency: Signal; modulationFrequency: Signal; phase: number; width: Signal; dispose(): this; } class Reverb extends Effect { decay: Signal; preDelay: Signal; } class Route extends SignalBase { constructor(outputCount?: number); gate: Signal; dispose(): this; select(which?: number, time?: _TimeArg): Route; } class Sampler extends Instrument { constructor(urls: any, options?: Object); //todo: Object | string envelope: Envelope; filter: BiquadFilterNode; filterEnvelope: Envelope; pitch: number; player: Player; sample: any; //todo: number | string dispose(): this; triggerAttack(sample?: string, time?: _TimeArg, velocity?: number): Sampler; triggerRelease(time?: _TimeArg): Sampler; } class Scale extends SignalBase { constructor(outputMin?: number, outputMax?: number); max: number; min: number; dispose(): this; } class ScaledEnvelope extends Envelope { constructor(attack?: any, decay?: _TimeArg, sustain?: number, release?: _TimeArg); //FIXME: Change 'any' to '_TimeArg | Object' exponent: number; max: number; min: number; dispose(): this; } class ScaleExp extends SignalBase { constructor(outputMin?: number, outputMax?: number, exponent?: number); exponent: number; max: number; min: number; dispose(): this; } class Select extends SignalBase { constructor(sourceCount?: number); gate: Signal; dispose(): this; select(which: number, time?: _TimeArg): Select; } module Sig { class Unit { } class Type { } } class Signal extends Param { constructor(value?: any, units?: Sig.Unit); //todo: number | AudioParam units: Sig.Type; cancelScheduledValues(startTime: _TimeArg): this; dispose(): this; exponentialRampToValueAtTime(value: number, endTime: _TimeArg): this; exponentialRampToValueNow(value: number, rampTime: _TimeArg): this; linearRampToValueAtTime(value: number, endTime: _TimeArg): this; linearRampToValueNow(value: number, rampTime: _TimeArg): this; rampTo(value: number, rampTime: _TimeArg): this; setCurrentValueNow(now?: number): this; setTargetAtTime(value: number, startTime: _TimeArg, timeConstant: number): this; getValueAtTime(time: _TimeArg): number; setValueAtTime(value: number, time: _TimeArg): this; setValueCurveAtTime(values: number[], startTime: _TimeArg, duration: _TimeArg): this; } class Analyser extends AudioNode { getValue(): Float32Array; } class SignalBase extends AudioNode { // @ts-ignore connect(node: AudioParam | AudioNode | Signal | Tone, outputNumber?: number, inputNumber?: number): SignalBase; } class Source extends AudioNode { State: string; onended: () => any; state: Source.State; volume: Signal; dispose(): this; start(startTime?: _TimeArg, offset?: _TimeArg, duration?: _TimeArg): Source; stop(time?: _TimeArg): Source; sync(delay?: _TimeArg): Source; unsync(): Source; } module Source { class State { } } class Split extends AudioNode { left: Gain; right: Gain; dispose(): this; } class StereoEffect extends Effect { effectReturnL: Gain; effectReturnR: Gain; dispose(): this; } class StereoFeedbackEffect extends FeedbackEffect { feedback: Signal; dispose(): this; } class StereoWidener extends MidSideEffect { constructor(width?: any); //FIXME change 'any' to 'number | Object' width: Signal; dispose(): this; } class StereoXFeedbackEffect extends FeedbackEffect { feedback: Signal; dispose(): this; } class Switch extends SignalBase { gate: Signal; close(time: _TimeArg): Switch; dispose(): this; open(time: _TimeArg): Switch } class Synth extends Monophonic { constructor(options?: any) // FIXME fix any } class Ticks extends TransportTime { constructor(val: string | number, units?: string); } class TickSignal extends Signal { _toUnits(value: number): number; _fromUnits(value: number): number; getDurationOfTicks(ticks: number, time: _TimeArg): number; timeToTicks(duration: PrimitiveTime, when?: PrimitiveTime): Ticks; getTicksAtTime(time: PrimitiveTime): PrimitiveTicks; getTimeOfTick(tick: PrimitiveTicks): number; } class TickSource extends Tone { frequency: TickSignal; ticks: number; seconds: number; start(time?: PrimitiveTime, offset?: PrimitiveTicks): this; pause(time?: PrimitiveTime): void; stop(time: PrimitiveTime): this; getTicksAtTime(time: PrimitiveTime): PrimitiveTicks; setTicksAtTime(time: PrimitiveTime, offset: PrimitiveTicks): this; forEachTickBetween(startTime: PrimitiveTime, endTime: PrimitiveTime, callback: (time: number, ticks: number) => void): this; dispose(): void; } class Time extends TimeBase { constructor(val: string | number, units?: string); toSeconds(): number; toTicks(): number; toBarsBeatsSixteenths(): string; } class Timeline<T extends { time: Time | number }> extends Tone { length: number; memory: number; cancel(time: number): this; add(event: T): void; get(time: number, comparator?: keyof T): T; forEach(callback: (event: T) => void): void; forEachAtTime(time: number, callback: (event: T) => void): void; forEachBetween(startTime: number, endTime: number, callback: (e: T) => void): this; forEachFrom(time: number, callback: (event: T) => void): void; remove(event: T): void; dispose(): void; } class TimelineState<T extends { state: TransportState, time: number }> extends Timeline<T> { constructor(initial: TransportState); cancel(time: number): this; getLastState(state: TransportState, time: number): T; setStateAtTime(state: TransportState, time: number): this; getValueAtTime(time: number): TransportState; } type _TimeArg = string | number | Time; class _TransportConstructor extends Tone { bpm: Signal; seconds: number; loop: boolean; loopEnd: _TimeArg; loopStart: _TimeArg; position: string; progress: number; state: TransportState; swing: number; swingSubdivision: _TimeArg; timeSignature: number; PPQ: number; getTicksAtTime(time: _TimeArg): number; clearInterval(rmInterval: number): boolean; clearIntervals(): void; clearTimeline(timelineID: number): boolean; clearTimelines(): void; clearTimeout(timeoutID: number): boolean; clearTimeouts(): void; clear(eventId: string): void; dispose(): this; nextBeat(subdivision?: string): number; pause(time: _TimeArg): Transport; schedule(callback: (time: number) => void, time: _TimeArg): string; setInterval(callback: (e: any) => any, interval: _TimeArg): number; setLoopPoints(startPosition: _TimeArg, endPosition: _TimeArg): Transport; setTimeline(callback: (e: any) => any, timeout: _TimeArg): number; setTimeout(callback: (e: any) => any, time: _TimeArg): number; start(time?: _TimeArg, offset?: _TimeArg): Transport; stop(time?: _TimeArg): Transport; pause(time?: _TimeArg): Transport; syncSignal(signal: Signal, ratio?: number): Transport; syncSource(source: Source, delay: _TimeArg): Transport; unsyncSignal(signal: Signal): Transport; unsyncSource(source: Source): Transport; } var Transport: _TransportConstructor; type TransportCallback = (exact: number, ticks: number) => void; // FIXME callback ^^ is wrong class TransportEvent extends Tone { constructor(transport: _TransportConstructor, options: { time: TransportTime, callback: TransportCallback }) id: string; Transport: _TransportConstructor; time: Ticks | number; _once: boolean; callback: TransportCallback; invoke(exact: number, ticks: number): void; dispose(): void; } class _TransportRepeatEventOptions { callback: TransportCallback; interval: Time; time: Time; duration: Time; } class TransportRepeatEvent extends TransportEvent { constructor(transport: _TransportConstructor, options: _TransportRepeatEventOptions); duration: Ticks; _createEvents(time: _TimeArg): void; } type TransportState = 'started' | 'stopped' | 'paused'; class TransportTime extends Time { toTicks(): number; } class TransportTimelineSignal extends Signal { // } class Tremolo extends StereoEffect { } class Type { static BPM: 'bpm'; } class Volume extends AudioNode { constructor(volume: number) volume: Signal; mute: boolean; } class WaveShaper extends SignalBase { constructor(mapping: any, bufferLen?: number); //FIXME: change 'any' to 'Function | Array | number' curve: number[]; oversample: string; } class Waveform extends AudioNode { constructor(size?: number); readonly channelCount: number; readonly numberOfInputs: number; readonly numberOfOutputs: number; getValue(): Float32Array; } }
the_stack
import Dimensions = Utils.Measurements.Dimensions; import DisplayObject = etch.drawing.DisplayObject; import Size = minerva.Size; import {IApp} from '../IApp'; import Point = minerva.Point; declare var App: IApp; export class CreateNew extends DisplayObject{ private _RollOvers: boolean[] = []; public BlockCount: number; public Hover: boolean; public IconPos: Point; public IconOffset: Point; public Message: string; public MessagePos: Point; public Open: boolean; public PanelOffset: Point; public PanelOffset2: Point; public Selected: number; //public ShowMessage: boolean = false; public Tweens: any[]; public Verify: string; public TickX: number; public CrossX: number; Init(drawTo: IDisplayContext): void { super.Init(drawTo); this.BlockCount = 0; this.Hover = false; this.IconPos = new Point(25, App.Metrics.HeaderHeight*0.5); this.IconOffset = new Point(-1,0); this.Open = false; this.PanelOffset = new Point(0,-1); this.PanelOffset2 = new Point(0,1); this.Selected = 0; this.Tweens = []; this.Verify = App.L10n.UI.CreateNew.Verify.toUpperCase(); this.Message = App.L10n.UI.CreateNew.NewMessage.toUpperCase(); this.MessagePos = new Point(100, 30); this.TickX = 130; this.CrossX = this.TickX+60; } CheckState() { if (App.Blocks.length>1) { if (this.IconOffset.x<0 && (App.Blocks.length!==this.BlockCount)) { this.StopAllTweens(); this.DelayTo(this.IconOffset,0,0.6,0,"x"); this.DelayTo(App.MainScene.Header,30,0.6,0,"CreateNewMargin"); } } else { if (this.IconOffset.x>-1) { this.StopAllTweens(); if (this.Open) { this.Open = false; this.DelayTo(this,0,0.3,0,"Selected"); this.DelayTo(this.PanelOffset,-1,0.3,0,"y"); } if (this.PanelOffset2.y===0) { this.CloseMessage(); } this.DelayTo(this.IconOffset,-1,0.6,0,"x"); this.DelayTo(App.MainScene.Header,0,0.6,0,"CreateNewMargin"); } } this.BlockCount = App.Blocks.length; } //------------------------------------------------------------------------------------------- // DRAW //------------------------------------------------------------------------------------------- Draw() { var ctx = this.Ctx; var units = App.Unit; var midType = App.Metrics.TxtMid; var italicType = App.Metrics.TxtItalic2; var x = this.IconPos.x; var y = this.IconPos.y; var yx = this.TickX*units; var nx = this.CrossX*units; var xOffset = this.IconOffset.x*((this.IconPos.x*units)*2); var header = App.MainScene.Header; var height = header.Height*units; var width = 50*units; var panelOffset = this.PanelOffset.y * ((header.Height*2)*units); var panelOffset2 = this.PanelOffset2.y * (500*units); if (this.PanelOffset.y > -1) { // draw if on screen var ym = 1; if (this._RollOvers[1]) { ym = 1.2; } var nm = 1; if (this._RollOvers[2]) { nm = 1.2; } ctx.textAlign = "left"; ctx.font = midType; // CLIPPING BOX // ctx.save(); ctx.beginPath(); ctx.moveTo(0, Math.round((header.Height * header.Rows)*units)); ctx.lineTo((App.Width), Math.round((header.Height * header.Rows)*units)); ctx.lineTo((App.Width), App.Height*0.5); ctx.lineTo(0, (App.Height*0.5)); ctx.closePath(); ctx.clip(); // BG // App.FillColor(ctx,App.Palette[2]); ctx.globalAlpha = 0.16; ctx.fillRect(0,Math.round(((header.Height * header.Rows)*units) + panelOffset),nx + (30*units),height + (5*units)); ctx.globalAlpha = 0.9; ctx.fillRect(0,Math.round(((header.Height * header.Rows)*units) + panelOffset),nx + (30*units),height); // VERIFY // var sy = Math.round(((header.Height * (header.Rows+0.5))*units) + panelOffset); ctx.globalAlpha = 1; App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.fillText(this.Verify, x ,sy + ((10*units) * 0.38)); App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.lineWidth = 2; // TICK // ctx.beginPath(); ctx.moveTo(yx - ((12*ym)*units), sy); ctx.lineTo(yx - ((4*ym)*units), sy + ((8*ym)*units)); ctx.lineTo(yx + ((12*ym)*units), sy - ((8*ym)*units)); // CROSS // ctx.moveTo(nx - ((8*nm)*units), sy - ((8*nm)*units)); ctx.lineTo(nx + ((8*nm)*units), sy + ((8*nm)*units)); ctx.moveTo(nx + ((8*nm)*units), sy - ((8*nm)*units)); ctx.lineTo(nx - ((8*nm)*units), sy + ((8*nm)*units)); ctx.stroke(); App.StrokeColor(ctx,App.Palette[1]); ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(yx + (30*units), sy - (16*units)); ctx.lineTo(yx + (30*units), sy + (16*units)); ctx.stroke(); // END CLIPPING // ctx.restore(); // DIVIDE // App.StrokeColor(ctx,App.Palette[1]); ctx.lineWidth = 1; if (this.PanelOffset.y>-0.5) { ctx.beginPath(); ctx.moveTo(20*units, Math.round(((header.Height * header.Rows)*units))); ctx.lineTo(nx + (10*units), Math.round(((header.Height * header.Rows)*units))); ctx.stroke(); } } // SELECTION COLOR // if (this.Selected) { // draw if on screen App.FillColor(ctx,App.Palette[App.ThemeManager.MenuOrder[1]]); ctx.beginPath(); ctx.moveTo(0,0); ctx.lineTo(width , 0); ctx.lineTo(width,(height*this.Selected)); ctx.lineTo((width*0.5) + (10*units),(height*this.Selected)); ctx.lineTo((width*0.5),((height + (10*units))*this.Selected)); ctx.lineTo((width*0.5) - (10*units),(height*this.Selected)); ctx.lineTo(0,(height*this.Selected)); ctx.closePath(); ctx.fill(); } // ICON // var m = 1; if (this._RollOvers[0]) { m = 1.2; } ctx.globalAlpha = 1; App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(((x-(2*m))*units) + xOffset, (y-(2*m))*units); ctx.lineTo(((x+(8*m))*units) + xOffset, (y-(2*m))*units); ctx.moveTo(((x+(3*m))*units) + xOffset, (y-(7*m))*units); ctx.lineTo(((x+(3*m))*units) + xOffset, (y+(3*m))*units); ctx.moveTo(((x-(5*m))*units) + xOffset, (y-(2*m))*units); ctx.lineTo(((x-(5*m))*units) + xOffset, (y+(6*m))*units); ctx.lineTo(((x+(3*m))*units) + xOffset, (y+(6*m))*units); ctx.stroke(); // MESSAGE BUTTON // if (this.PanelOffset2.y < 0.5) { // draw if on screen var mm = 1; if (this._RollOvers[3]) { mm = 1.01; } var w = this.MessagePos.x; y = this.MessagePos.y; ctx.beginPath(); ctx.moveTo((App.Width*0.5)-((w*mm)*units), (App.Height - (y*units)) - ((16*mm)*units) + panelOffset2); ctx.lineTo((App.Width*0.5)+((w*mm)*units), (App.Height - (y*units)) - ((16*mm)*units) + panelOffset2); ctx.lineTo((App.Width*0.5)+((w*mm)*units), (App.Height - (y*units)) + ((16*mm)*units) + panelOffset2); ctx.lineTo((App.Width*0.5)-((w*mm)*units), (App.Height - (y*units)) + ((16*mm)*units) + panelOffset2); ctx.closePath(); ctx.stroke(); ctx.beginPath(); ctx.moveTo((App.Width*0.5)+((w+6)*units), (App.Height - ((y+19)*units)) + panelOffset2); ctx.lineTo((App.Width*0.5)+((w+14)*units), (App.Height - ((y+11)*units)) + panelOffset2); ctx.moveTo((App.Width*0.5)+((w+14)*units), (App.Height - ((y+19)*units)) + panelOffset2); ctx.lineTo((App.Width*0.5)+((w+6)*units), (App.Height - ((y+11)*units)) + panelOffset2); ctx.stroke(); ctx.textAlign = "center"; //ctx.font = italicType; App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.fillText(this.Message, (App.Width*0.5), (App.Height - (30*units)) + ((10*units) * 0.38) + panelOffset2); } } //------------------------------------------------------------------------------------------- // TWEEN //------------------------------------------------------------------------------------------- DelayTo(panel,destination,t,delay,v){ var offsetTween = new window.TWEEN.Tween({x: panel[""+v]}); offsetTween.to({x: destination}, t*1000); offsetTween.onUpdate(function () { panel[""+v] = this.x; }); offsetTween.onComplete(function() { if (v=="OffsetY") { if (destination!==0) { panel.Open = false; } } }); offsetTween.easing(window.TWEEN.Easing.Exponential.InOut); offsetTween.delay(delay); offsetTween.start(this.LastVisualTick); this.Tweens.push(offsetTween); } StopAllTweens() { if (this.Tweens.length) { for (var j=0; j<this.Tweens.length; j++) { this.Tweens[j].stop(); } this.Tweens = []; } } //------------------------------------------------------------------------------------------- // INTERACTION //------------------------------------------------------------------------------------------- OpenPanel() { this.Open = true; App.MainScene.Header.ClosePanel(); this.DelayTo(this,1,0.3,0,"Selected"); this.DelayTo(this.PanelOffset,0,0.5,0.1,"y"); this.DelayTo(App.MainScene.Header,50,0.3,0,"CreateNewMargin"); } ClosePanel() { this.Open = false; this.DelayTo(this,0,0.3,0,"Selected"); this.DelayTo(this.PanelOffset,-1,0.3,0,"y"); this.DelayTo(App.MainScene.Header,30,0.3,0,"CreateNewMargin"); } ShowMessage() { this.PanelOffset2.y = 0; } CloseMessage() { this.DelayTo(this.PanelOffset2,1,0.6,0,"y"); } MouseDown(point) { this.HitTests(point); // ICON // if (this._RollOvers[0]) { this.OpenPanel(); return; } // Y | N // if (this.Open) { if (this._RollOvers[1]) { this.CreateNewScene(); return; } else { this.ClosePanel(); return; } } // CREATE YOUR OWN // if (this._RollOvers[3]) { this.CreateNewScene(); App.MainScene.Tutorial.CheckLaunch(); return; } // CLOSE MESSAGE // if (this._RollOvers[4]) { this.CloseMessage(); } } MouseUp(point) { } MouseMove(point) { this.HitTests(point); } HitTests(point) { this.Hover = false; var ctx = this.Ctx; var units = App.Unit; var xOffset = this.IconOffset.x*((this.IconPos.x*units)*2); var yx = this.TickX*units; var nx = this.CrossX*units; var header = App.MainScene.Header; var height = header.Height*units; var panelOffset = this.PanelOffset.y * ((header.Height*2)*units); var panelOffset2 = this.PanelOffset2.y * (500*units); this._RollOvers[0] = Dimensions.hitRect(((this.IconPos.x - 20)*units) + xOffset, (this.IconPos.y - 20)*units, 40*units, 40*units, point.x, point.y); // verify this._RollOvers[1] = Dimensions.hitRect(yx - (20*units), (height * (header.Rows+0.5)) - (20*units) + panelOffset, 40*units, 40*units, point.x, point.y); // y this._RollOvers[2] = Dimensions.hitRect(nx - (20*units), (height * (header.Rows+0.5)) - (20*units) + panelOffset, 40*units, 40*units, point.x, point.y); // n this._RollOvers[3] = Dimensions.hitRect((App.Width*0.5) - (this.MessagePos.x*units), (App.Height - ((this.MessagePos.y+20)*units)) + panelOffset2, (this.MessagePos.x*2)*units, 40*units, point.x, point.y); // message this._RollOvers[4] = Dimensions.hitRect((App.Width*0.5) + (this.MessagePos.x*units), (App.Height - ((this.MessagePos.y+31)*units)) + panelOffset2, 30*units, 30*units, point.x, point.y); // close if (this._RollOvers[0]||this._RollOvers[1]||this._RollOvers[2]||this._RollOvers[3]||this._RollOvers[4]) { this.Hover = true; } } CreateNewScene() { this.BlockCount = 0; App.Stage.MainScene.ResetScene(); } }
the_stack
import React from 'react'; import { Components } from '../lib/vulcan-lib/components'; import { Posts } from '../lib/collections/posts/collection'; import { postGetPageUrl, postGetAuthorName } from '../lib/collections/posts/helpers'; import { Comments } from '../lib/collections/comments/collection'; import { Localgroups } from '../lib/collections/localgroups/collection'; import { Messages } from '../lib/collections/messages/collection'; import { TagRels } from '../lib/collections/tagRels/collection'; import { Conversations } from '../lib/collections/conversations/collection'; import { accessFilterMultiple } from '../lib/utils/schemaUtils'; import keyBy from 'lodash/keyBy'; import Users from '../lib/collections/users/collection'; import { userGetDisplayName } from '../lib/collections/users/helpers'; import * as _ from 'underscore'; import './emailComponents/EmailComment'; import './emailComponents/PrivateMessagesEmail'; import './emailComponents/EventUpdatedEmail'; import { taggedPostMessage } from '../lib/notificationTypes'; import { commentGetPageUrlFromIds } from "../lib/collections/comments/helpers"; import { REVIEW_NAME_TITLE } from '../lib/reviewUtils'; import { ForumOptions, forumSelect } from '../lib/forumTypeUtils'; import { capitalize, getSiteUrl } from '../lib/vulcan-lib/utils'; import { forumTitleSetting, siteNameWithArticleSetting } from '../lib/instanceSettings'; interface ServerNotificationType { name: string, from?: string, canCombineEmails?: boolean, loadData?: ({user, notifications}: {user: DbUser, notifications: DbNotification[]}) => Promise<any>, emailSubject: ({user, notifications}: {user: DbUser, notifications: DbNotification[]}) => Promise<string>, emailBody: ({user, notifications}: {user: DbUser, notifications: DbNotification[]}) => Promise<React.ReactNode>, } const notificationTypes: {string?: ServerNotificationType} = {}; export const getNotificationTypeByNameServer = (name: string): ServerNotificationType => { if (name in notificationTypes) return notificationTypes[name]; else throw new Error(`Invalid notification type: ${name}`); } const serverRegisterNotificationType = (notificationTypeClass: ServerNotificationType): ServerNotificationType => { const name = notificationTypeClass.name; notificationTypes[name] = notificationTypeClass; return notificationTypeClass; } export const NewPostNotification = serverRegisterNotificationType({ name: "newPost", canCombineEmails: false, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const postId = notifications[0].documentId; const post = await Posts.findOne({_id: postId}); if (!post) throw Error(`Can't find post to generate subject-line for: ${postId}`) return post.title; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const postId = notifications[0].documentId; return <Components.NewPostEmail documentId={postId}/> }, }); // Vulcan notification that we don't really use export const PostApprovedNotification = serverRegisterNotificationType({ name: "postApproved", emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { return "LessWrong notification"; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => null }); export const NewEventNotification = serverRegisterNotificationType({ name: "newEvent", canCombineEmails: false, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const post = await Posts.findOne(notifications[0].documentId); if (!post) throw Error(`Can't find post to generate subject-line for: ${notifications}`) return `New event: ${post.title}`; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const postId = notifications[0].documentId; return <Components.NewPostEmail documentId={postId} hideRecommendations={true} reason="you are subscribed to this group"/> }, }); export const NewGroupPostNotification = serverRegisterNotificationType({ name: "newGroupPost", canCombineEmails: false, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const post = await Posts.findOne(notifications[0].documentId); const group = await Localgroups.findOne(post?.groupId); return `New post in group ${group?.name}`; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const postId = notifications[0].documentId; return <Components.NewPostEmail documentId={postId} hideRecommendations={true} reason="you are subscribed to this group"/> }, }); export const NominatedPostNotification = serverRegisterNotificationType({ name: "postNominated", canCombineEmails: false, emailSubject: async ({user, notifications}: {user: DbUser, notifications: DbNotification[]}) => { return `Your post was nominated for the ${REVIEW_NAME_TITLE}` }, emailBody: async ({user, notifications}: {user: DbUser, notifications: DbNotification[]}) => { const postId = notifications[0].documentId; return <Components.PostNominatedEmail documentId={postId} /> } }) export const NewShortformNotification = serverRegisterNotificationType({ name: "newShortform", canCombineEmails: false, emailSubject: async ({user, notifications}: {user: DbUser, notifications: DbNotification[]}) => { const comment = await Comments.findOne(notifications[0].documentId) const post = comment?.postId && await Posts.findOne(comment.postId) // This notification type should never be triggered on tag-comments, so we just throw an error here if (!post) throw Error(`Can't find post to generate subject-line for: ${comment}`) return 'New comment on "' + post.title + '"'; }, emailBody: async ({user, notifications}: {user: DbUser, notifications: DbNotification[]}) => { const comment = await Comments.findOne(notifications[0].documentId) if (!comment) throw Error(`Can't find comment for comment email notification: ${notifications[0]}`) return <Components.EmailCommentBatch comments={[comment]}/>; } }) export const NewTagPostsNotification = serverRegisterNotificationType({ name: "newTagPosts", canCombineEmails: false, emailSubject: async ({user, notifications}: {user: DbUser, notifications: DbNotification[]}) => { const {documentId, documentType} = notifications[0] return await taggedPostMessage({documentId, documentType}) }, emailBody: async ({user, notifications}: {user: DbUser, notifications: DbNotification[]}) => { const {documentId, documentType} = notifications[0] const tagRel = await TagRels.findOne({_id: documentId}) if (tagRel) { return <Components.NewPostEmail documentId={ tagRel.postId}/> } } }) export const NewCommentNotification = serverRegisterNotificationType({ name: "newComment", canCombineEmails: true, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { if (notifications.length > 1) { return `${notifications.length} comments on posts you subscribed to`; } else { const comment = await Comments.findOne(notifications[0].documentId); if (!comment) throw Error(`Can't find comment for notification: ${notifications[0]}`) const author = await Users.findOne(comment.userId); if (!author) throw Error(`Can't find author for new comment notification: ${notifications[0]}`) return `${author.displayName} commented on a post you subscribed to`; } }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const commentIds = notifications.map(n => n.documentId); const commentsRaw = await Comments.find({_id: {$in: commentIds}}).fetch(); const comments = await accessFilterMultiple(user, Comments, commentsRaw, null); return <Components.EmailCommentBatch comments={comments}/>; }, }); export const NewReplyNotification = serverRegisterNotificationType({ name: "newReply", canCombineEmails: true, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { if (notifications.length > 1) { return `${notifications.length} replies to comments you're subscribed to`; } else { const comment = await Comments.findOne(notifications[0].documentId); if (!comment) throw Error(`Can't find comment for notification: ${notifications[0]}`) const author = await Users.findOne(comment.userId); if (!author) throw Error(`Can't find author for new comment notification: ${notifications[0]}`) return `${userGetDisplayName(author)} replied to a comment you're subscribed to`; } }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const commentIds = notifications.map(n => n.documentId); const commentsRaw = await Comments.find({_id: {$in: commentIds}}).fetch(); const comments = await accessFilterMultiple(user, Comments, commentsRaw, null); return <Components.EmailCommentBatch comments={comments}/>; }, }); export const NewReplyToYouNotification = serverRegisterNotificationType({ name: "newReplyToYou", canCombineEmails: true, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { if (notifications.length > 1) { return `${notifications.length} replies to your comments`; } else { const comment = await Comments.findOne(notifications[0].documentId); if (!comment) throw Error(`Can't find comment for notification: ${notifications[0]}`) const author = await Users.findOne(comment.userId); if (!author) throw Error(`Can't find author for new comment notification: ${notifications[0]}`) return `${userGetDisplayName(author)} replied to your comment`; } }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const commentIds = notifications.map(n => n.documentId); const commentsRaw = await Comments.find({_id: {$in: commentIds}}).fetch(); const comments = await accessFilterMultiple(user, Comments, commentsRaw, null); return <Components.EmailCommentBatch comments={comments}/>; }, }); // Vulcan notification that we don't really use export const NewUserNotification = serverRegisterNotificationType({ name: "newUser", emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { return "LessWrong notification"; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => null, }); const newMessageEmails: ForumOptions<string | null> = { EAForum: 'forum-noreply@effectivealtruism.org', default: null, } const forumNewMessageEmail = forumSelect(newMessageEmails) ?? undefined export const NewMessageNotification = serverRegisterNotificationType({ name: "newMessage", from: forumNewMessageEmail, // passing in undefined will lead to default behavior loadData: async function({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) { // Load messages const messageIds = notifications.map(notification => notification.documentId); const messagesRaw = await Messages.find({ _id: {$in: messageIds} }).fetch(); const messages = await accessFilterMultiple(user, Messages, messagesRaw, null); // Load conversations const messagesByConversationId = keyBy(messages, message=>message.conversationId); const conversationIds = _.keys(messagesByConversationId); const conversationsRaw = await Conversations.find({ _id: {$in: conversationIds} }).fetch(); const conversations = await accessFilterMultiple(user, Conversations, conversationsRaw, null); // Load participant users const participantIds = _.uniq(_.flatten(conversations.map(conversation => conversation.participantIds), true)); const participantsRaw = await Users.find({ _id: {$in: participantIds} }).fetch(); const participants = await accessFilterMultiple(user, Users, participantsRaw, null); const participantsById = keyBy(participants, u=>u._id); const otherParticipants = _.filter(participants, participant=>participant._id!=user._id); return { conversations, messages, participantsById, otherParticipants }; }, emailSubject: async function({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) { const { conversations, otherParticipants } = await this.loadData!({ user, notifications }); const otherParticipantNames = otherParticipants.map((u: DbUser)=>userGetDisplayName(u)).join(', '); return `Private message conversation${conversations.length>1 ? 's' : ''} with ${otherParticipantNames}`; }, emailBody: async function({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) { const { conversations, messages, participantsById } = await this.loadData!({ user, notifications }); return <Components.PrivateMessagesEmail conversations={conversations} messages={messages} participantsById={participantsById} /> }, }); // This notification type should never be emailed (but is displayed in the // on-site UI). export const EmailVerificationRequiredNotification = serverRegisterNotificationType({ name: "emailVerificationRequired", canCombineEmails: false, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { throw new Error("emailVerificationRequired notification should never be emailed"); }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { throw new Error("emailVerificationRequired notification should never be emailed"); }, }); export const PostSharedWithUserNotification = serverRegisterNotificationType({ name: "postSharedWithUser", canCombineEmails: false, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { let post = await Posts.findOne(notifications[0].documentId); if (!post) throw Error(`Can't find post for notification: ${notifications[0]}`) return `You have been shared on the ${post.draft ? "draft" : "post"} ${post.title}`; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const post = await Posts.findOne(notifications[0].documentId); if (!post) throw Error(`Can't find post for notification: ${notifications[0]}`) const link = postGetPageUrl(post, true); return <p> You have been shared on the {post.draft ? "draft" : "post"} <a href={link}>{post.title}</a>. </p> }, }); export const isComment = (document: DbPost | DbComment) : document is DbComment => { if (document.hasOwnProperty("answer")) return true //only comments can be answers return false } export const AlignmentSubmissionApprovalNotification = serverRegisterNotificationType({ name: "alignmentSubmissionApproved", canCombineEmails: false, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { return "Your submission to the Alignment Forum has been approved!"; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { let document: DbPost|DbComment|null document = await Posts.findOne(notifications[0].documentId); if (!document) { document = await Comments.findOne(notifications[0].documentId) } if (!document) throw Error(`Can't find document for notification: ${notifications[0]}`) if (isComment(document)) { const link = commentGetPageUrlFromIds({postId: document.postId, commentId: document._id, isAbsolute: true}) return <p> Your <a href={link}>comment submission</a> to the Alignment Forum has been approved. </p> } else { const link = postGetPageUrl(document, true) return <p> Your post, <a href={link}>{document.title}</a>, has been accepted to the Alignment Forum. </p> } }, }); export const NewEventInRadiusNotification = serverRegisterNotificationType({ name: "newEventInRadius", canCombineEmails: false, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { let post = await Posts.findOne(notifications[0].documentId); if (!post) throw Error(`Can't find post for notification: ${notifications[0]}`) return `New event in your area: ${post.title}`; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const postId = notifications[0].documentId; return <Components.NewPostEmail documentId={postId} hideRecommendations={true} reason="you are subscribed to nearby events notifications"/> }, }); export const EditedEventInRadiusNotification = serverRegisterNotificationType({ name: "editedEventInRadius", canCombineEmails: false, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { let post = await Posts.findOne(notifications[0].documentId); if (!post) throw Error(`Can't find post for notification: ${notifications[0]}`) return `Event in your area updated: ${post.title}`; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { return <Components.EventUpdatedEmail postId={notifications[0].documentId} /> }, }); export const NewRSVPNotification = serverRegisterNotificationType({ name: "newRSVP", canCombineEmails: false, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { let post = await Posts.findOne(notifications[0].documentId); if (!post) throw Error(`Can't find post for notification: ${notifications[0]}`) return `New RSVP for your event: ${post.title}`; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { let post = await Posts.findOne(notifications[0].documentId); if (!post) throw Error(`Can't find post for notification: ${notifications[0]}`) return <div> <p> {notifications[0].message} </p> <p> <a href={postGetPageUrl(post,true)}>Event Link</a> </p> </div> }, }); export const NewGroupOrganizerNotification = serverRegisterNotificationType({ name: "newGroupOrganizer", canCombineEmails: false, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const localGroup = await Localgroups.findOne(notifications[0].documentId) if (!localGroup) throw new Error("Cannot find local group for which this notification is being sent") return `You've been added as an organizer of ${localGroup.name}`; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const localGroup = await Localgroups.findOne(notifications[0].documentId) if (!localGroup) throw new Error("Cannot find local group for which this notification is being sent") const groupLink = `${getSiteUrl().slice(0,-1)}/groups/${localGroup._id}` return <div> <p> Hi {user.displayName}, </p> <p> You've been assigned as a group organizer for <a href={groupLink}>{localGroup.name}</a> on {siteNameWithArticleSetting.get()}. </p> <p> We recommend you check the group's info and update it if necessary. You can also post your group's events on the forum, which get advertised to users based on relevance. </p> <p> - The {forumTitleSetting.get()} Team </p> </div> }, }); export const PostCoauthorRequestNotification = serverRegisterNotificationType({ name: "coauthorRequestNotification", canCombineEmails: false, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { let post = await Posts.findOne(notifications[0].documentId); if (!post) { throw Error(`Can't find post for notification: ${notifications[0]}`); } return `${user.displayName} requested that you co-author their post: ${post.title}`; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const post = await Posts.findOne(notifications[0].documentId); if (!post) { throw Error(`Can't find post for notification: ${notifications[0]}`); } const link = postGetPageUrl(post, true); const name = await postGetAuthorName(post); return ( <p> {name} requested that you co-author their post <a href={link}>{post.title}</a>. </p> ); }, }); export const PostCoauthorAcceptNotification = serverRegisterNotificationType({ name: "coauthorAcceptNotification", canCombineEmails: false, emailSubject: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { let post = await Posts.findOne(notifications[0].documentId); if (!post) { throw Error(`Can't find post for notification: ${notifications[0]}`); } return `Your co-author request for '${post.title}' was accepted`; }, emailBody: async ({ user, notifications }: {user: DbUser, notifications: DbNotification[]}) => { const post = await Posts.findOne(notifications[0].documentId); if (!post) { throw Error(`Can't find post for notification: ${notifications[0]}`); } const link = postGetPageUrl(post, true); return ( <p> Your co-author request for <a href={link}>{post.title}</a> was accepted. </p> ); }, });
the_stack
import {descriptor2typestr} from './util'; import ByteStream from './ByteStream'; import {ConstantPool, ClassReference, ConstUTF8, IConstantPoolItem, MethodHandle, NameAndTypeInfo} from './ConstantPool'; import {StackMapTableEntryType, ConstantPoolItemType} from './enums'; import assert from './assert'; import global from './global'; declare var RELEASE: boolean; export interface IAttributeClass { parse(byteStream: ByteStream, constantPool: ConstantPool, attrLen: number, name: string): IAttribute; } export interface IAttribute { getName(): string; } export interface IInnerClassInfo { innerInfoIndex: number; outerInfoIndex: number; innerNameIndex: number; innerAccessFlags: number; } export class ExceptionHandler implements IAttribute { public startPC: number; public endPC: number; public handlerPC: number; public catchType: string; constructor(startPC: number, endPC: number, handlerPC: number, catchType: string) { this.startPC = startPC; this.endPC = endPC; this.handlerPC = handlerPC; this.catchType = catchType; } public getName() { return 'ExceptionHandler'; } public static parse(bytesArray: ByteStream, constantPool: ConstantPool): IAttribute { var startPC = bytesArray.getUint16(), endPC = bytesArray.getUint16(), handlerPC = bytesArray.getUint16(), cti = bytesArray.getUint16(), catchType = cti === 0 ? "<any>" : (<ClassReference> constantPool.get(cti)).name; return new this(startPC, endPC, handlerPC, catchType); } } export class Code implements IAttribute { private maxStack: number; private maxLocals: number; public exceptionHandlers: ExceptionHandler[]; private attrs: IAttribute[]; private code: Buffer; constructor(maxStack: number, maxLocals: number, exceptionHandlers: ExceptionHandler[], attrs: IAttribute[], code: Buffer) { this.maxStack = maxStack; this.maxLocals = maxLocals; this.exceptionHandlers = exceptionHandlers; this.attrs = attrs; this.code = code; } public getName() { return 'Code'; } public getMaxStack(): number { return this.maxStack; } public static parse(byteStream: ByteStream, constantPool: ConstantPool): IAttribute { var maxStack = byteStream.getUint16(), maxLocals = byteStream.getUint16(), codeLen = byteStream.getUint32(); if (codeLen === 0) { throw "Error parsing code: Code length is zero"; } var code = byteStream.slice(codeLen).getBuffer(), exceptLen = byteStream.getUint16(), exceptionHandlers: ExceptionHandler[] = []; for (var i = 0; i < exceptLen; i++) { exceptionHandlers.push(<ExceptionHandler> ExceptionHandler.parse(byteStream, constantPool)); } // yes, there are even attrs on attrs. BWOM... BWOM... var attrs = makeAttributes(byteStream, constantPool); return new this(maxStack, maxLocals, exceptionHandlers, attrs, code); } public getCode(): NodeBuffer { return this.code; } public getAttribute(name: string): IAttribute { for (var i = 0; i < this.attrs.length; i++) { var attr = this.attrs[i]; if (attr.getName() === name) { return attr; } } return null; } } export interface ILineNumberTableEntry { startPC: number; lineNumber: number; } export class LineNumberTable implements IAttribute { private entries: ILineNumberTableEntry[]; constructor(entries: ILineNumberTableEntry[]) { this.entries = entries; } public getName() { return 'LineNumberTable'; } /** * Returns the relevant source code line number for the specified program * counter. */ public getLineNumber(pc: number): number { var j: number, lineNumber = -1; // get the last line number before the stack frame's pc for (j = 0; j < this.entries.length; j++) { var entry = this.entries[j]; if (entry.startPC <= pc) { lineNumber = entry.lineNumber; } else { // Further entries are past the PC. break; } } return lineNumber; } public static parse(byteStream: ByteStream, constantPool: ConstantPool): IAttribute { var entries: ILineNumberTableEntry[] = []; var lntLen = byteStream.getUint16(); for (var i = 0; i < lntLen; i++) { var spc = byteStream.getUint16(); var ln = byteStream.getUint16(); entries.push({ 'startPC': spc, 'lineNumber': ln }); } return new this(entries); } } export class SourceFile implements IAttribute { public filename: string; constructor(filename: string) { this.filename = filename; } public getName() { return 'SourceFile'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool): IAttribute { return new this((<ConstUTF8> constantPool.get(byteStream.getUint16())).value); } } export interface IStackMapTableEntry { type: StackMapTableEntryType; offsetDelta: number; numLocals?: number; locals?: string[]; numStackItems?: number; stack?: string[]; k?: number; } export class StackMapTable implements IAttribute { private entries: IStackMapTableEntry[]; constructor(entries: IStackMapTableEntry[]) { this.entries = entries; } public getName() { return 'StackMapTable'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool): IAttribute { var numEntries = byteStream.getUint16(), entries: IStackMapTableEntry[] = []; for (var i = 0; i < numEntries; i++) { entries.push(this.parseEntry(byteStream, constantPool)); } return new this(entries); } private static parseEntry(byteStream: ByteStream, constantPool: ConstantPool): IStackMapTableEntry { var frameType = byteStream.getUint8(), locals: string[], offsetDelta: number, i: number; if (frameType < 64) { return { type: StackMapTableEntryType.SAME_FRAME, offsetDelta: frameType }; } else if (frameType < 128) { return { type: StackMapTableEntryType.SAME_LOCALS_1_STACK_ITEM_FRAME, offsetDelta: frameType - 64, stack: [this.parseVerificationTypeInfo(byteStream, constantPool)] }; } else if (frameType < 247) { // reserved for future use } else if (frameType === 247) { return { type: StackMapTableEntryType.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED, offsetDelta: byteStream.getUint16(), stack: [this.parseVerificationTypeInfo(byteStream, constantPool)] }; } else if (frameType < 251) { return { type: StackMapTableEntryType.CHOP_FRAME, offsetDelta: byteStream.getUint16(), k: 251 - frameType }; } else if (frameType === 251) { return { type: StackMapTableEntryType.SAME_FRAME_EXTENDED, offsetDelta: byteStream.getUint16() }; } else if (frameType < 255) { offsetDelta = byteStream.getUint16(); locals = []; for (i = 0; i < frameType - 251; i++) { locals.push(this.parseVerificationTypeInfo(byteStream, constantPool)); } return { type: StackMapTableEntryType.APPEND_FRAME, offsetDelta: offsetDelta, locals: locals }; } else if (frameType === 255) { offsetDelta = byteStream.getUint16(); var numLocals = byteStream.getUint16(); locals = []; for (i = 0; i < numLocals; i++) { locals.push(this.parseVerificationTypeInfo(byteStream, constantPool)); } var numStackItems = byteStream.getUint16(); var stack: string[] = []; for (i = 0; i < numStackItems; i++) { stack.push(this.parseVerificationTypeInfo(byteStream, constantPool)); } return { type: StackMapTableEntryType.FULL_FRAME, offsetDelta: offsetDelta, numLocals: numLocals, locals: locals, numStackItems: numStackItems, stack: stack }; } } private static parseVerificationTypeInfo(byteStream: ByteStream, constantPool: ConstantPool): string { var tag = byteStream.getUint8(); if (tag === 7) { var cls = (<ClassReference> constantPool.get(byteStream.getUint16())).name; return 'class ' + (/\w/.test(cls[0]) ? descriptor2typestr(cls) : "\"" + cls + "\""); } else if (tag === 8) { return 'uninitialized ' + byteStream.getUint16(); } else { var tagToType = ['bogus', 'int', 'float', 'double', 'long', 'null', 'this', 'object', 'uninitialized']; return tagToType[tag]; } } } export interface ILocalVariableTableEntry { startPC: number; length: number; name: string; descriptor: string; ref: number; } export class LocalVariableTable implements IAttribute { private entries: ILocalVariableTableEntry[]; constructor(entries: ILocalVariableTableEntry[]) { this.entries = entries; } public getName() { return 'LocalVariableTable'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool): IAttribute { var numEntries = byteStream.getUint16(), entries: ILocalVariableTableEntry[] = []; for (var i = 0; i < numEntries; i++) { entries.push(this.parseEntries(byteStream, constantPool)); } return new this(entries); } private static parseEntries(bytes_array: ByteStream, constant_pool: ConstantPool): ILocalVariableTableEntry { return { startPC: bytes_array.getUint16(), length: bytes_array.getUint16(), name: (<ConstUTF8> constant_pool.get(bytes_array.getUint16())).value, descriptor: (<ConstUTF8> constant_pool.get(bytes_array.getUint16())).value, ref: bytes_array.getUint16() }; } } export interface ILocalVariableTypeTableEntry { startPC: number; length: number; name: string; signature: string; index: number; } export class LocalVariableTypeTable implements IAttribute { public entries: ILocalVariableTypeTableEntry[]; constructor(entries: ILocalVariableTypeTableEntry[]) { this.entries = entries; } public getName(): string { return 'LocalVariableTypeTable'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool): IAttribute { var numEntries = byteStream.getUint16(), i: number, entries: ILocalVariableTypeTableEntry[] = []; for (i = 0; i < numEntries; i++) { entries.push(this.parseTableEntry(byteStream, constantPool)); } return new this(entries); } private static parseTableEntry(byteStream: ByteStream, constantPool: ConstantPool): ILocalVariableTypeTableEntry { return { startPC: byteStream.getUint16(), length: byteStream.getUint16(), name: (<ConstUTF8> constantPool.get(byteStream.getUint16())).value, signature: (<ConstUTF8> constantPool.get(byteStream.getUint16())).value, index: byteStream.getUint16() }; } } export class Exceptions implements IAttribute { public exceptions: string[]; constructor(exceptions: string[]) { this.exceptions = exceptions; } public getName() { return 'Exceptions'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool): IAttribute { var numExceptions = byteStream.getUint16(); var excRefs: number[] = []; for (var i = 0; i < numExceptions; i++) { excRefs.push(byteStream.getUint16()); } return new this(excRefs.map((ref: number) => (<ClassReference> constantPool.get(ref)).name)); } } export class InnerClasses implements IAttribute { public classes: IInnerClassInfo[]; constructor(classes: IInnerClassInfo[]) { this.classes = classes; } public getName() { return 'InnerClasses'; } public static parse(bytes_array: ByteStream, constant_pool: ConstantPool): IAttribute { var numClasses = bytes_array.getUint16(), classes: IInnerClassInfo[] = []; for (var i = 0; i < numClasses; i++) { classes.push(this.parseClass(bytes_array, constant_pool)); } return new this(classes); } public static parseClass(byteStream: ByteStream, constantPool: ConstantPool): IInnerClassInfo { return { innerInfoIndex: byteStream.getUint16(), outerInfoIndex: byteStream.getUint16(), innerNameIndex: byteStream.getUint16(), innerAccessFlags: byteStream.getUint16() }; } } export class ConstantValue implements IAttribute { public value: IConstantPoolItem; constructor(value: IConstantPoolItem) { this.value = value; } public getName() { return 'ConstantValue'; } public static parse(bytes_array: ByteStream, constant_pool: ConstantPool): IAttribute { var ref = bytes_array.getUint16(); return new this(constant_pool.get(ref)); } } export class Synthetic implements IAttribute { public getName() { return 'Synthetic'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool): IAttribute { return new this(); } } export class Deprecated implements IAttribute { public getName() { return 'Deprecated'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool): IAttribute { return new this(); } } export class Signature implements IAttribute { public sig: string; constructor(sig: string) { this.sig = sig; } public getName() { return 'Signature'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool): IAttribute { return new this((<ConstUTF8> constantPool.get(byteStream.getUint16())).value); } } export class RuntimeVisibleAnnotations implements IAttribute { public rawBytes: Buffer; public isHidden: boolean; public isCallerSensitive: boolean; public isCompiled: boolean; constructor(rawBytes: Buffer, isHidden: boolean, isCallerSensitive: boolean, isCompiled: boolean) { this.rawBytes = rawBytes; this.isHidden = isHidden; this.isCallerSensitive = isCallerSensitive; this.isCompiled = isCompiled; } public getName() { return 'RuntimeVisibleAnnotations'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool, attrLen: number): IAttribute { // No need to parse; OpenJDK parses these from within Java code from // the raw bytes. // ...but we need to look for the 'Hidden' annotation, which specifies if // the method should be omitted from stack frames. // And the 'compiled' annotation, which specifies if the method was // compiled. // And the 'CallerSensitive' annotation, which specifies that the function's // behavior differs depending on the caller. /** * Skip the current RuntimeVisibleAnnotation. */ function skipAnnotation() { byteStream.skip(2); // type index var numValuePairs = byteStream.getUint16(), i: number; for (i = 0; i < numValuePairs; i++) { byteStream.skip(2); // element name index skipElementValue(); } } /** * Skip this particular element value. */ function skipElementValue() { var tag = String.fromCharCode(byteStream.getUint8()); switch(tag) { case 'e': // Fall-through. byteStream.skip(2); case 'Z': case 'B': case 'C': case 'S': case 'I': case 'F': case 'J': case 'D': case 's': case 'c': byteStream.skip(2); break; case '@': skipAnnotation(); break; case '[': var numValues = byteStream.getUint16(), i: number; for (i = 0; i < numValues; i++) { skipElementValue(); } break; } } var rawBytes = byteStream.read(attrLen), isHidden = false, isCompiled = false, isCallerSensitive = false; byteStream.seek(byteStream.pos() - rawBytes.length); var numAttributes = byteStream.getUint16(), i: number; for (i = 0; i < numAttributes; i++) { var typeName = (<ConstUTF8> constantPool.get(byteStream.getUint16())); // Rewind. byteStream.seek(byteStream.pos() - 2); skipAnnotation(); switch (typeName.value) { case 'Ljava/lang/invoke/LambdaForm$Hidden;': isHidden = true; break; case 'Lsig/sun/reflect/CallerSensitive;': isCallerSensitive = true; break; case 'Lsig/java/lang/invoke/LambdaForm$Compiled': isCompiled = true; break; } } return new this(rawBytes, isHidden, isCallerSensitive, isCompiled); } } export class AnnotationDefault implements IAttribute { public rawBytes: Buffer; constructor(rawBytes: Buffer) { this.rawBytes = rawBytes; } public getName() { return 'AnnotationDefault'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool, attrLen?: number): IAttribute { return new this(byteStream.read(attrLen)); } } export class EnclosingMethod implements IAttribute { public encClass: ClassReference; /** * Note: Is NULL if the current class is not immediately enclosed by a method * or a constructor. */ public encMethod: NameAndTypeInfo; constructor(encClass: ClassReference, encMethod: NameAndTypeInfo) { this.encClass = encClass; this.encMethod = encMethod; } public getName() { return 'EnclosingMethod'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool): IAttribute { var encClass = (<ClassReference> constantPool.get(byteStream.getUint16())), methodRef = byteStream.getUint16(), encMethod: NameAndTypeInfo = null; if (methodRef > 0) { encMethod = <NameAndTypeInfo> constantPool.get(methodRef); assert(encMethod.getType() === ConstantPoolItemType.NAME_AND_TYPE, "Enclosing method must be a name and type info."); } return new this(encClass, encMethod); } } export class BootstrapMethods implements IAttribute { public bootstrapMethods: Array<[MethodHandle, IConstantPoolItem[]]>; constructor(bootstrapMethods: Array<[MethodHandle, IConstantPoolItem[]]>) { this.bootstrapMethods = bootstrapMethods; } public getName() { return 'BootstrapMethods'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool): IAttribute { var numBootstrapMethods = byteStream.getUint16(), bootstrapMethods: Array<[MethodHandle, IConstantPoolItem[]]> = []; for (var i = 0; i < numBootstrapMethods; i++) { var methodHandle = <MethodHandle> constantPool.get(byteStream.getUint16()); var numArgs = byteStream.getUint16(); var args: IConstantPoolItem[] = []; for (var j = 0; j < numArgs; j++) { args.push(constantPool.get(byteStream.getUint16())); } bootstrapMethods.push([methodHandle, args]); } return new this(bootstrapMethods); } } export class RuntimeVisibleParameterAnnotations implements IAttribute { public rawBytes: Buffer; constructor(rawBytes: Buffer) { this.rawBytes = rawBytes; } public getName() { return 'RuntimeVisibleParameterAnnotations'; } public static parse(byteStream: ByteStream, constantPool: ConstantPool, attrLen: number): IAttribute { return new this(byteStream.read(attrLen)); } } export function makeAttributes(byteStream: ByteStream, constantPool: ConstantPool): IAttribute[]{ var attrTypes: { [name: string]: IAttributeClass } = { 'Code': Code, 'LineNumberTable': LineNumberTable, 'SourceFile': SourceFile, 'StackMapTable': StackMapTable, 'LocalVariableTable': LocalVariableTable, 'LocalVariableTypeTable': LocalVariableTypeTable, 'ConstantValue': ConstantValue, 'Exceptions': Exceptions, 'InnerClasses': InnerClasses, 'Synthetic': Synthetic, 'Deprecated': Deprecated, 'Signature': Signature, 'RuntimeVisibleAnnotations': RuntimeVisibleAnnotations, 'AnnotationDefault': AnnotationDefault, 'EnclosingMethod': EnclosingMethod, 'BootstrapMethods': BootstrapMethods, 'RuntimeVisibleParameterAnnotations': RuntimeVisibleParameterAnnotations }; var numAttrs = byteStream.getUint16(); var attrs : IAttribute[] = []; for (var i = 0; i < numAttrs; i++) { var name = (<ConstUTF8> constantPool.get(byteStream.getUint16())).value; var attrLen = byteStream.getUint32(); if (attrTypes[name] != null) { var oldLen = byteStream.size(); var attr = attrTypes[name].parse(byteStream, constantPool, attrLen, name); var newLen = byteStream.size(); assert((oldLen - newLen) <= attrLen, `A parsed attribute read beyond its data! ${name}`); if (oldLen - newLen !== attrLen) { byteStream.skip(attrLen - oldLen + newLen); } attrs.push(attr); } else { // we must silently ignore other attrs byteStream.skip(attrLen); } } return attrs; }
the_stack
import {action, observable} from "mobx"; import {provideSingleton} from "../../common/utils/IOC"; import Pagination from "../../common/model/Pagination"; import {asyncAction} from "mobx-utils"; import { addClusterAlarmUser, addClusterSubmit, checkClusterNameExist, createZnode, deleteAlarmUser, deleteZnode, getClusterDetail, getClusterInfo, getClusterRootZnodes, getClusterUsers, getClusterZnodesChildren, getMonitorTaskByClusterId, modifyCluster, searchZnodeData, updateMonitorStatus, updateZnode } from "../service/cluster"; // 集群信息查询条件 export class ClusterSearchVo { clusterName?: string; officer?: string; status?: number; deployType?: number; serviceLine?: number; version?: string; } // 页面显示的集群信息 export class ClusterVo { id: number; clusterId: number; clusterName: string; intro: string; znodeCount: number; requestCount: number; connections: number; collectTime: string; version: string; status: number; serviceLine: number; clusterInfo: ClusterInfoVo; } // 集群状态信息 export class ClusterStateVo { clusterId: number; instanceNumber: number; avgLatencyMax: number; maxLatencyMax: number; minLatencyMax: number; receivedTotal: number; sentTotal: number; connectionTotal: number; znodeCount: number; watcherTotal: number; ephemerals: number; outstandingTotal: number; approximateDataSize: number; openFileDescriptorCountTotal: number; modifyTime: Date; modifyTimeStr: string; } // 集群基本信息 export class ClusterInfoVo { id: number; clusterName: string; officer: string; instanceNumber: number; status: number; deployType: number; serviceLine: number; version: string; intro: string; createTime: Date; createTimeStr: string; modifyTime: Date; modifyTimestr: string; } // 集群基本信息+集群状态信息 export class ClusterDetailVo { clusterInfo: ClusterInfoVo; clusterState: ClusterStateVo; } // 集群报警用户对应关系 export class ClusterAlarmUserVo { id: number; clusterId: number; userId: number; userName: string; mobile: string; email: string; } // 集群统计信息查询条件,包含集群id、起始时间以及结束时间 export class ClusterStatSearchVo { id: number; start: string; end: string; } // 新建集群信息,除基本信息外,包含集群实例基本配置 export class NewClusterVo extends ClusterInfoVo { constructor() { super(); } newClusterServers: string; } // 节点信息 export class ClusterZnode { title: string; key: string; isLeaf: boolean; } // 节点详细信息 export class ZnodeDetailInfoVo { data: string; czxid: string; mzxid: string; ctime: string; mtime: string; version: number; cversion: number; aversion: number; ephemeralOwner: string; dataLength: number; numChildren: number; pzxid: string; } @provideSingleton(ClusterModel) export class ClusterModel extends Pagination { /** * 数据加载标志 * @type {boolean} */ @observable loading: boolean = false; /** * 集群列表信息 * @type {Array} */ @observable clusters: Array<ClusterVo> = []; /** * 集群基本信息 * @type {any} */ @observable clusterInfo: ClusterVo = null; /** * 集群详细信息,包含集群的状态信息 * @type {any} */ @observable clusterDetailVo: ClusterDetailVo = null; /** * 集群下对应的报警用户列表信息 * @type {Array} */ @observable alarmUsers: Array<ClusterAlarmUserVo> = []; /** * 集群名称是否已经存在的标志位 TODO 后续优化 * @type {boolean} */ @observable clusterNameExist: boolean = false; /** * 新建集群,提交结果 * @type {boolean} */ @observable addClusterSubmitResult: boolean = false; /** * 根节点列表 * @type {Array} */ @observable znodeRoots: Array<ClusterZnode> = []; /** * 节点children列表 * @type {Array} */ @observable znodeChildren: Array<ClusterZnode> = []; /** * 节点详细信息 * @type {any} */ @observable znodeDataDetail: ZnodeDetailInfoVo = null; constructor() { super(); this.path = '/cluster/query'; } @action queryCallBack(success: boolean, list: Array<any>): void { if (success) { this.clusters = list as Array<ClusterVo>; } this.loading = false; } @action query(vo: ClusterSearchVo) { this.loading = true; this.queryData(vo); } /** * 重置新建集群结果信息 */ @action resetAddClusterSubmitResult() { this.addClusterSubmitResult = false; } /** * 获取集群基本信息 * @param clusterId 集群id */ @asyncAction * getClusterInfo(clusterId: number) { const result = yield getClusterInfo(clusterId); if (result.success) { this.clusterInfo = result.data; } } /** * 获取集群详细信息,包含集群基本信息以及集群的状态信息 * @param clusterId 集群id */ @asyncAction * getClusterDetail(clusterId: number) { const result = yield getClusterDetail(clusterId); if (result.success) { this.clusterDetailVo = result.data; } } /** * 获取集群下的报警用户列表 * @param clusterId 集群id */ @asyncAction * getClusterUsers(clusterId: number) { const result = yield getClusterUsers(clusterId); if (result.success) { this.alarmUsers = result.data; } } /** * 删除某个报警用户信息 * @param item 集群与用户的对应关系 */ @asyncAction * deleteAlarmUser(item: ClusterAlarmUserVo) { this.loading = true; const result = yield deleteAlarmUser({clusterId: item.clusterId, userId: item.id}); if (result.success) { const newList = this.alarmUsers.filter(bean => bean.id !== item.id); this.alarmUsers = newList; } this.loading = false; } /** * 新增报警用户信息 * @param item 集群与用户的对应关系 */ @asyncAction * addClusterAlarmUser(item: ClusterAlarmUserVo) { const result = yield addClusterAlarmUser(item); if (result.success) { this.getClusterUsers(item.clusterId) } } /** * 修改集群基本信息 * @param vo 集群基本信息 * @param callback 回调处理结果 */ @asyncAction * editClusterInfo(vo: any, callback) { this.loading = true; const result = yield modifyCluster(vo); if (result.success) { const newList = this.clusters.map(bean => { if (bean.clusterId === vo.id) { bean.clusterInfo = vo; bean.clusterName = vo.clusterName; bean.intro = vo.intro; bean.version = vo.version; bean.serviceLine = vo.serviceLine; return bean; } return bean; }); this.clusters = newList; callback && callback(result.message); } this.loading = false; } /** * 校验集群名称是否已经存在 * @param clusterName 集群名称 * @param callback 回调处理结果 */ @asyncAction * checkClusterNameExist(clusterName, callback: any) { const result = yield checkClusterNameExist(clusterName); if (result.success) { this.clusterNameExist = result.data; if (this.clusterNameExist == true) { // 如果集群名称已经存在,则回调处理显示 callback && callback(); } } } /** * 新建集群 * @param vo 新集群基本信息 */ @asyncAction * addClusterSubmit(vo: NewClusterVo) { this.loading = true; const result = yield addClusterSubmit(vo); if (result.success) { this.addClusterSubmitResult = true; } this.loading = false; } /** * 更新集群监控状态 * @param clusterId 集群id * @param status 集群监控状态 */ @asyncAction * updateMonitorStatus(clusterId: number, status: boolean) { this.loading = true; const result = yield updateMonitorStatus({clusterId: clusterId, status: status}); if (result.success) { const newClusters = this.clusters.map(bean => { let clusterStatus = status ? 2 : 1; if (bean.clusterId === clusterId) { return {...bean, status: clusterStatus}; } return bean; }); this.clusters = newClusters; } this.loading = false; } /** * 获取zk根节点/下的所有节点信息 * @param clusterId 集群id */ @asyncAction * getClusterRootZnodes(clusterId: number) { const result = yield getClusterRootZnodes(clusterId); if (result.success) { this.znodeRoots = result.data; } } /** * 获取某个节点下的所有子节点信息 * @param id 集群id * @param znode 待获取子节点的节点信息 * @param callback 回调处理结果 */ @asyncAction * getClusterZnodesChildren(id: number, znode: string, callback: any) { const result = yield getClusterZnodesChildren(id, znode); if (result.success) { this.znodeChildren = result.data; // 回调渲染子节点数据 callback && callback(result.data); } } /** * 删除某个节点信息 * @param id 集群id * @param znode 待删除节点信息 * @param callback 回调处理结果 */ @asyncAction * deleteZnode(id: number, znode: string, callback: any) { const result = yield deleteZnode(id, znode); if (result.success) { // 回调显示处理成功结果 callback && callback(result.message); } } /** * 查询某个节点的数据信息 * @param id 集群id * @param znode 待查询数据的节点路径 * @param serializable 序列化方式 */ @asyncAction * searchZnodeData(id: number, znode: string, serializable: string) { const result = yield searchZnodeData(id, znode, serializable); if (result.success) { this.znodeDataDetail = result.data; } } /** * 更新节点数据信息 * @param item 更新所需数据信息 * @param callback 回调处理结果 */ @asyncAction * updateZnode(item, callback: any) { const result = yield updateZnode(item); if (result.success) { // 回调显示处理成功结果 callback && callback(result.message); } } /** * 创建节点 * @param item 创建节点信息 * @param callback 回调处理结果 */ @asyncAction * createZnode(item, callback: any) { const result = yield createZnode(item); if (result.success) { // 回调显示处理成功结果 callback && callback(result.message); } } /** * 根据集群ID获取该集群下的所有监控任务信息 * @param clusterId 集群id */ @asyncAction * getMonitorTaskByClusterId(clusterId: number) { const result = yield getMonitorTaskByClusterId(clusterId); if (result.success) { this.znodeRoots = result.data; } } }
the_stack
import * as amf from 'amf-client-js'; /** Custom BaseUnit subclass which implements utility methods. */ export abstract class WebApiBaseUnit extends amf.model.document.BaseUnit { /** Gets declaration by name. * * @param name String name of declaration to look for. * @return Found declaration as NodeShape. */ getDeclarationByName(name: string): amf.model.domain.AnyShape } export abstract class WebApiBaseUnitWithDeclaresModel extends WebApiBaseUnit implements amf.model.document.DeclaresModel { /* DeclaresModel methods */ declares: amf.model.domain.DomainElement[] withDeclaredElement(declared: amf.model.domain.DomainElement): this withDeclares(declares: amf.model.domain.DomainElement[]): this } export abstract class WebApiBaseUnitWithEncodesModel extends WebApiBaseUnit implements amf.model.document.EncodesModel { /* EncodesModel methods */ encodes: amf.model.domain.DomainElement withEncodes(enocdes: amf.model.domain.DomainElement): this } export abstract class WebApiBaseUnitWithDeclaresModelAndEncodesModel extends WebApiBaseUnit implements amf.model.document.DeclaresModel, amf.model.document.EncodesModel { /* DeclaresModel methods */ declares: amf.model.domain.DomainElement[] withDeclaredElement(declared: amf.model.domain.DomainElement): this withDeclares(declares: amf.model.domain.DomainElement[]): this /* EncodesModel methods */ encodes: amf.model.domain.DomainElement withEncodes(enocdes: amf.model.domain.DomainElement): this } export namespace webapi { /** Subclass of Document inheriting WebApiBaseUnit utility methods. */ export class WebApiDocument extends WebApiBaseUnitWithDeclaresModelAndEncodesModel { } /** Subclass of Module inheriting WebApiBaseUnit utility methods. */ export class WebApiModule extends WebApiBaseUnitWithDeclaresModel { } /** Subclass of ExternalFragment inheriting WebApiBaseUnit utility methods. */ export class WebApiExternalFragment extends WebApiBaseUnitWithEncodesModel { } /** Subclass of Extension inheriting WebApiBaseUnit utility methods. */ export class WebApiExtension extends WebApiBaseUnitWithEncodesModel { } /** Subclass of Overlay inheriting WebApiBaseUnit utility methods. */ export class WebApiOverlay extends WebApiBaseUnitWithEncodesModel { } /** Subclass of DocumentationItem inheriting WebApiBaseUnit utility methods. */ export class WebApiDocumentationItem extends WebApiBaseUnitWithEncodesModel { } /** Subclass of DataType inheriting WebApiBaseUnit utility methods. */ export class WebApiDataType extends WebApiBaseUnitWithEncodesModel { } /** Subclass of NamedExample inheriting WebApiBaseUnit utility methods. */ export class WebApiNamedExample extends WebApiBaseUnitWithEncodesModel { } /** Subclass of ResourceTypeFragment inheriting WebApiBaseUnit utility methods. */ export class WebApiResourceTypeFragment extends WebApiBaseUnitWithEncodesModel { } /** Subclass of TraitFragment inheriting WebApiBaseUnit utility methods. */ export class WebApiTraitFragment extends WebApiBaseUnitWithEncodesModel { } /** Subclass of AnnotationTypeDeclaration inheriting WebApiBaseUnit utility methods. */ export class WebApiAnnotationTypeDeclaration extends WebApiBaseUnitWithEncodesModel { } /** Subclass of SecuritySchemeFragment inheriting WebApiBaseUnit utility methods. */ export class WebApiSecuritySchemeFragment extends WebApiBaseUnitWithEncodesModel { } /** Subclass of PayloadFragment inheriting WebApiBaseUnit utility methods. */ export class WebApiPayloadFragment extends WebApiBaseUnitWithEncodesModel { } /** Subclass of Vocabulary inheriting WebApiBaseUnit utility methods. */ export class WebApiVocabulary extends WebApiBaseUnit { name: amf.model.StrField description: amf.model.StrField base: amf.model.StrField imports: amf.model.domain.VocabularyReference[] externals: amf.model.domain.External[] withName(name: string): WebApiVocabulary withBase(base: string): WebApiVocabulary withExternals(externals: amf.model.domain.External[]): WebApiVocabulary withImports(vocabularies: amf.model.domain.VocabularyReference[]): WebApiVocabulary objectPropertyTerms(): amf.model.domain.ObjectPropertyTerm[] datatypePropertyTerms(): amf.model.domain.DatatypePropertyTerm[] classTerms(): amf.model.domain.ClassTerm[] } } /** Utility object that hosts initialization logic and * classes with syntax-specific methods. */ export namespace WebApiParser { /** * Initializes necessary plugins. Is automatically run when * syntax-specific methods are called. Must be called explicitly * when constructing API by hand. */ export function init(): Promise<void> /** Provides methods for RAML 1.0 processing */ export class raml10 { /** Parses RAML 1.0 content from string or url. * * @param urlOrContent File url/path or content string to be parsed. * @return Parsed WebApi Model. */ static parse(urlOrContent: string): Promise<WebApiBaseUnit> /** Parses RAML 1.0 content from string with a custom API Doc location. * * @param content Content string to be parsed. * @param baseUrl Location to assign to a doc parsed from a content string. * References are resolved relative to this location. * @return Parsed WebApi Model (future). */ static parse(content: string, baseUrl: string): Promise<WebApiBaseUnit> /** Generates file with RAML 1.0 content. * * @param model Parsed WebApi Model to generate content from. * @param url Path to the generated file. */ static generateFile(model: WebApiBaseUnit, url: string): Promise<void> /** Generates string with RAML 1.0 content. * * @param model Parsed WebApi Model to generate content from. * @return Generated string. */ static generateString(model: WebApiBaseUnit): Promise<string> /** Validates parsed RAML 1.0 amf.model. * * @param model Parsed WebApi Model to be validated. * @return Validation report. */ static validate(model: WebApiBaseUnit): Promise<amf.client.validate.ValidationReport> /** Resolves parsed RAML 1.0 amf.model. * * Resolution process includes resolving references to all types, libraries, etc. * * @param model Parsed WebApi Model to be resolved. * @return Resolved parsed WebApi Model. */ static resolve(model: WebApiBaseUnit): Promise<WebApiBaseUnit> } /** Provides methods for RAML 0.8 processing */ export class raml08 { /** Parses RAML 0.8 content from string or url. * * @param urlOrContent File url/path or content string. * @return Parsed WebApi Model. */ static parse(urlOrContent: string): Promise<WebApiBaseUnit> /** Parses RAML 0.8 content from string with a custom API Doc location. * * @param content Content string to be parsed. * @param baseUrl Location to assign to a doc parsed from a content string. * References are resolved relative to this location. * @return Parsed WebApi Model (future). */ static parse(content: string, baseUrl: string): Promise<WebApiBaseUnit> /** Generates file with RAML 0.8 content. * * @param model Parsed WebApi Model to generate content from. * @param url Path to the generated file. */ static generateFile(model: WebApiBaseUnit, url: string): Promise<void> /** Generates string with RAML 0.8 content. * * @param model Parsed WebApi Model to generate content from. * @return Generated string. */ static generateString(model: WebApiBaseUnit): Promise<string> /** Validates parsed RAML 0.8 amf.model. * * @param model Parsed WebApi Model to be validated. * @return Validation report. */ static validate(model: WebApiBaseUnit): Promise<amf.client.validate.ValidationReport> /** Resolves parsed RAML 0.8 amf.model. * * Resolution process includes resolving references to all types, libraries, etc. * * @param model Parsed WebApi Model to be resolved. * @return Resolved parsed WebApi Model. */ static resolve(model: WebApiBaseUnit): Promise<WebApiBaseUnit> } /** Provides methods for OAS 2.0 processing */ export class oas20 { /** Parses OAS 2.0 JSON content from string or url. * * @param urlOrContent File url/path or content string. * @return Parsed WebApi Model. */ static parse(urlOrContent: string): Promise<WebApiBaseUnit> /** Parses OAS 2.0 JSON content from string with a custom API Doc location. * * @param content Content string to be parsed. * @param baseUrl Location to assign to a doc parsed from a content string. * References are resolved relative to this location. * @return Parsed WebApi Model (future). */ static parse(content: string, baseUrl: string): Promise<WebApiBaseUnit> /** Generates file with OAS 2.0 JSON content. * * @param model Parsed WebApi Model to generate content from. * @param url Path to the generated file. */ static generateFile(model: WebApiBaseUnit, url: string): Promise<void> /** Generates string with OAS 2.0 JSON content. * * @param model Parsed WebApi Model to generate content from. * @return Generated string. */ static generateString(model: WebApiBaseUnit): Promise<string> /** Validates parsed OAS 2.0 amf.model. * * @param model Parsed WebApi Model to be validated. * @return Validation report. */ static validate(model: WebApiBaseUnit): Promise<amf.client.validate.ValidationReport> /** Resolves parsed OAS 2.0 amf.model. * * Resolution process includes resolving references to all types, libraries, etc. * * @param model Parsed WebApi Model to be resolved. * @return Resolved parsed WebApi Model. */ static resolve(model: WebApiBaseUnit): Promise<WebApiBaseUnit> /** Parses OAS 2.0 YAML content from string or url. * * @param urlOrContent File url/path or content string. * @return Parsed WebApi Model. */ static parseYaml(urlOrContent: string): Promise<WebApiBaseUnit> /** Parses OAS 2.0 YAML content from string with a custom API Doc location. * * @param content Content string to be parsed. * @param baseUrl Location to assign to a doc parsed from a content string. * References are resolved relative to this location. * @return Parsed WebApi Model (future). */ static parseYaml(content: string, baseUrl: string): Promise<WebApiBaseUnit> /** Generates file with OAS 2.0 YAML content. * * @param model Parsed WebApi Model to generate content from. * @param url Path to the generated file. */ static generateYamlFile(model: WebApiBaseUnit, url: string): Promise<void> /** Generates string with OAS 2.0 YAML content. * * @param model Parsed WebApi Model to generate content from. * @return Generated string. */ static generateYamlString(model: WebApiBaseUnit): Promise<string> } /** BETA! Provides methods for OAS 3.0 processing */ export class oas30 { /** BETA! Parses OAS 3.0 JSON content from string or url. * * @param urlOrContent File url/path or content string. * @return Parsed WebApi Model. */ static parse(urlOrContent: string): Promise<WebApiBaseUnit> /** BETA! Parses OAS 3.0 JSON content from string with a custom API Doc location. * * @param content Content string to be parsed. * @param baseUrl Location to assign to a doc parsed from a content string. * References are resolved relative to this location. * @return Parsed WebApi Model (future). */ static parse(content: string, baseUrl: string): Promise<WebApiBaseUnit> /** BETA! Generates file with OAS 3.0 JSON content. * * @param model Parsed WebApi Model to generate content from. * @param url Path to the generated file. */ static generateFile(model: WebApiBaseUnit, url: string): Promise<void> /** BETA! Generates string with OAS 3.0 JSON content. * * @param model Parsed WebApi Model to generate content from. * @return Generated string. */ static generateString(model: WebApiBaseUnit): Promise<string> /** BETA! Validates parsed OAS 3.0 model. * * @param model Parsed WebApi Model to be validated. * @return Validation report. */ static validate(model: WebApiBaseUnit): Promise<client.validate.ValidationReport> /** BETA! Resolves parsed OAS 3.0 model. * * Resolution process includes resolving references to all types, libraries, etc. * * @param model Parsed WebApi Model to be resolved. * @return Resolved parsed WebApi Model. */ static resolve(model: WebApiBaseUnit): Promise<WebApiBaseUnit> /** BETA! Parses OAS 3.0 YAML content from string or url. * * @param urlOrContent File url/path or content string. * @return Parsed WebApi Model. */ static parseYaml(urlOrContent: string): Promise<WebApiBaseUnit> /** BETA! Parses OAS 3.0 YAML content from string with a custom API Doc location. * * @param content Content string to be parsed. * @param baseUrl Location to assign to a doc parsed from a content string. * References are resolved relative to this location. * @return Parsed WebApi Model (future). */ static parseYaml(content: string, baseUrl: string): Promise<WebApiBaseUnit> /** BETA! Generates file with OAS 3.0 YAML content. * * @param model Parsed WebApi Model to generate content from. * @param url Path to the generated file. */ static generateYamlFile(model: WebApiBaseUnit, url: string): Promise<void> /** BETA! Generates string with OAS 3.0 YAML content. * * @param model Parsed WebApi Model to generate content from. * @return Generated string. */ static generateYamlString(model: WebApiBaseUnit): Promise<string> } /** Provides methods for AMF Graph processing */ export class amfGraph { /** Parses AMF Graph content from string or url. * * @param urlOrContent File url/path or content string. * @return Parsed WebApi Model. */ static parse(urlOrContent: string): Promise<WebApiBaseUnit> /** Parses AMF Graph content from string with a custom API Doc location. * * @param content Content string to be parsed. * @param baseUrl Location to assign to a doc parsed from a content string. * References are resolved relative to this location. * @return Parsed WebApi Model (future). */ static parse(content: string, baseUrl: string): Promise<WebApiBaseUnit> /** Generates file with AMF Graph content. * * @param model Parsed WebApi Model to generate content from. * @param url Path to the generated file. */ static generateFile(model: WebApiBaseUnit, url: string): Promise<void> /** Generates string with AMF Graph content. * * @param model Parsed WebApi Model to generate content from. * @return Generated string. */ static generateString(model: WebApiBaseUnit): Promise<string> /** Validates parsed AMF Graph amf.model. * * @param model Parsed WebApi Model to be validated. * @return Validation report. */ static validate(model: WebApiBaseUnit): Promise<amf.client.validate.ValidationReport> /** Resolves parsed AMF Graph amf.model. * * Resolution process includes resolving references to all types, libraries, etc. * * @param model Parsed WebApi Model to be resolved. * @return Resolved parsed WebApi Model. */ static resolve(model: WebApiBaseUnit): Promise<WebApiBaseUnit> } } /* Re-export types that fell-through from 'amf-client-js' so they are visible by Typescript. Commented exports are exposed in JS but not declared in amf-client-js typings definition (.d.ts). */ export import AmfGraphParser = amf.parse.AmfGraphParser; export import AmfGraphRenderer = amf.AmfGraphRenderer; export import AmfGraphResolver = amf.AmfGraphResolver; export import JsBrowserHttpResourceLoader = amf.JsBrowserHttpResourceLoader; export import JsonPayloadParser = amf.JsonPayloadParser; export import JsonldRenderer = amf.JsonldRenderer; export import MessageStyles = amf.MessageStyles; export import Oas20Parser = amf.Oas20Parser; export import Oas20Renderer = amf.Oas20Renderer; export import Oas20Resolver = amf.Oas20Resolver; export import Oas20YamlParser = amf.Oas20YamlParser; export import Oas30Parser = amf.Oas30Parser; export import Oas30Renderer = amf.Oas30Renderer; // export import Oas30Resolver = amf.Oas30Resolver; export import Oas30YamlParser = amf.Oas30YamlParser; export import ProfileName = amf.ProfileName; export import ProfileNames = amf.ProfileNames; export import Raml08Parser = amf.Raml08Parser; export import Raml08Renderer = amf.Raml08Renderer; export import Raml08Resolver = amf.Raml08Resolver; export import Raml10Parser = amf.Raml10Parser; export import Raml10Renderer = amf.Raml10Renderer; export import Raml10Resolver = amf.Raml10Resolver; export import RamlParser = amf.RamlParser; export import ResolutionPipeline = amf.core.resolution.pipelines.ResolutionPipeline; export import Resolver = amf.resolve.Resolver; export import ResourceNotFound = amf.ResourceNotFound; export import ValidationMode = amf.ValidationMode; export import YamlPayloadParser = amf.YamlPayloadParser; export import client = amf.client; export import core = amf.core; export import model = amf.model; export import parser = amf.core.parser; export import render = amf.render; // export import Aml10Parser = amf.parse.Aml10Parser; // export import Aml10Renderer = amf.Aml10Renderer; // export import ErrorHandler = amf.ErrorHandler; // export import ExecutionLog = amf.ExecutionLog; // export import JsServerFileResourceLoader = amf.JsServerFileResourceLoader; // export import JsServerHttpResourceLoader = amf.JsServerHttpResourceLoader; // export import JsonPayloadRenderer = amf.JsonPayloadRenderer; // export import SHACLValidator = amf.SHACLValidator; // export import YamlPayloadRenderer = amf.YamlPayloadRenderer;
the_stack
var exports = {}, _dewExec = false; var module = { exports: exports }; var _global = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : global; export function dew() { if (_dewExec) return module.exports; _dewExec = true; /** * @license * Lodash <https://lodash.com/> * Copyright OpenJS Foundation and other contributors <https://openjsf.org/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ; (function () { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.17.15'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Error message constants. */ var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG]]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', domExcTag = '[object DOMException]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = ['Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout']; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 's' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'" }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof _global == 'object' && _global && _global.Object === Object && _global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && true && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = function () { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }(); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function (value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while (fromRight ? index-- : ++index < length) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? baseSum(array, iteratee) / length : NAN; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function (object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function (key) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function (value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : result + current; } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function (key) { return [key, object[key]]; }); } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function (value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function (key) { return object[key]; }); } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function (value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function (arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function (value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function (value) { result[++index] = [value, value]; }); return result; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * A specialized version of `_.lastIndexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index; } } return index; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ var runInContext = function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to detect methods masquerading as native. */ var maskSrcKey = function () { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? 'Symbol(src)_1.' + uid : ''; }(); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; var defineProperty = function () { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }(); /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap(); /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = function () { function object() {} return function (proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object(); object.prototype = undefined; return result; }; }(); /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() {} // No operation performed. /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { (this || _global).__wrapped__ = value; (this || _global).__actions__ = []; (this || _global).__chain__ = !!chainAll; (this || _global).__index__ = 0; (this || _global).__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB) as well as ES2015 template strings. Change the * following template settings to use alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { (this || _global).__wrapped__ = value; (this || _global).__actions__ = []; (this || _global).__dir__ = 1; (this || _global).__filtered__ = false; (this || _global).__iteratees__ = []; (this || _global).__takeCount__ = MAX_ARRAY_LENGTH; (this || _global).__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper((this || _global).__wrapped__); result.__actions__ = copyArray((this || _global).__actions__); result.__dir__ = (this || _global).__dir__; result.__filtered__ = (this || _global).__filtered__; result.__iteratees__ = copyArray((this || _global).__iteratees__); result.__takeCount__ = (this || _global).__takeCount__; result.__views__ = copyArray((this || _global).__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if ((this || _global).__filtered__) { var result = new LazyWrapper(this || _global); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = (this || _global).__wrapped__.value(), dir = (this || _global).__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, (this || _global).__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : start - 1, iteratees = (this || _global).__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, (this || _global).__takeCount__); if (!isArr || !isRight && arrLength == length && takeCount == length) { return baseWrapperValue(array, (this || _global).__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { (this || _global).__data__ = nativeCreate ? nativeCreate(null) : {}; (this || _global).size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete (this || _global).__data__[key]; (this || _global).size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = (this || _global).__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = (this || _global).__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = (this || _global).__data__; (this || _global).size += this.has(key) ? 0 : 1; data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value; return this || _global; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { (this || _global).__data__ = []; (this || _global).size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = (this || _global).__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --(this || _global).size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = (this || _global).__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf((this || _global).__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = (this || _global).__data__, index = assocIndexOf(data, key); if (index < 0) { ++(this || _global).size; data.push([key, value]); } else { data[index][1] = value; } return this || _global; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { (this || _global).size = 0; (this || _global).__data__ = { 'hash': new Hash(), 'map': new (Map || ListCache)(), 'string': new Hash() }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this || _global, key)['delete'](key); (this || _global).size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this || _global, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this || _global, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this || _global, key), size = data.size; data.set(key, value); (this || _global).size += data.size == size ? 0 : 1; return this || _global; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; (this || _global).__data__ = new MapCache(); while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { (this || _global).__data__.set(value, HASH_UNDEFINED); return this || _global; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return (this || _global).__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = (this || _global).__data__ = new ListCache(entries); (this || _global).size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { (this || _global).__data__ = new ListCache(); (this || _global).size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = (this || _global).__data__, result = data['delete'](key); (this || _global).size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return (this || _global).__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return (this || _global).__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = (this || _global).__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) { pairs.push([key, value]); (this || _global).size = ++data.size; return this || _global; } data = (this || _global).__data__ = new MapCache(pairs); } data.set(key, value); (this || _global).size = data.size; return this || _global; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays. isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties. isIndex(key, length)))) { result.push(key); } } return result; } /** * A specialized version of `_.sample` for arrays. * * @private * @param {Array} array The array to sample. * @returns {*} Returns the random element. */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined; } /** * A specialized version of `_.sampleSize` for arrays. * * @private * @param {Array} array The array to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if (value !== undefined && !eq(object[key], value) || value === undefined && !(key in object)) { baseAssignValue(object, key, value); } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || value === undefined && !(key in object)) { baseAssignValue(object, key, value); } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function (value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || isFunc && !object) { result = isFlat || isFunc ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack()); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet(value)) { value.forEach(function (subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); } else if (isMap(value)) { value.forEach(function (subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); } var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys; var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function (subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function (object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if (value === undefined && !(key in object) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function () { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = comparator || value !== 0 ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function (value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? current === current && !isSymbol(current) : comparator(current, computed))) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : length + start; } end = end === undefined || end > length ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function (value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function (key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return index && index == length ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || length >= 120 && array.length >= 120) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = comparator || value !== 0 ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator))) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator))) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function (value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack()); return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack()); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack()); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack(); if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result)) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function (value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function (object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function (object) { var objValue = get(object, path); return objValue === undefined && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function (srcValue, key) { stack || (stack = new Stack()); if (isObject(srcValue)) { baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, key + '', object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, key + '', object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || isFunction(objValue)) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); var result = baseMap(collection, function (value, key, collection) { var criteria = arrayMap(iteratees, function (iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function (object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function (value, path) { return hasIn(object, path); }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function (object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else { baseUnset(array, index); } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } /** * The base implementation of `_.sample`. * * @private * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. */ function baseSample(collection) { return arraySample(values(collection)); } /** * The base implementation of `_.sampleSize` without param guards. * * @private * @param {Array|Object} collection The collection to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {}; } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function (func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function (func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** * The base implementation of `_.shuffle`. * * @private * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. */ function baseShuffle(collection) { return shuffleSelf(values(collection)); } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : length + start; } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : end - start >>> 0; start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function (value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = low + high >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? computed <= value : computed < value)) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array == null ? 0 : array.length, valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? computed <= value : computed < value; } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = value + ''; return result == '0' && 1 / value == -INFINITY ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache(); } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = comparator || value !== 0 ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, fromRight ? 0 : index, fromRight ? index + 1 : length) : baseSlice(array, fromRight ? index + 1 : 0, fromRight ? length : index); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function (result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** * A `baseRest` alias which can be replaced with `identity` by module * replacement plugins. * * @private * @type {Function} * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ var castRest = baseRest; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return !start && end >= length ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function (id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) { return 1; } if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function (collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function (object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = assigner.length > 3 && typeof customizer == 'function' ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function (collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while (fromRight ? index-- : ++index < length) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function (object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this || _global) && (this || _global) !== root && (this || _global) instanceof wrapper ? Ctor : func; return fn.apply(isBind ? thisArg : this || _global, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function (string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function (string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function () { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor(); case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this || _global) && (this || _global) !== root && (this || _global) instanceof wrapper ? Ctor : func; return apply(fn, this || _global, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function (collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function (key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return flatRest(function (funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func); } } return function () { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value)) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this || _global, args) : value; while (++index < length) { result = funcs[index].call(this || _global, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length); } var thisBinding = isBind ? thisArg : this || _global, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if ((this || _global) && (this || _global) !== root && (this || _global) instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function (object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function (value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return flatRest(function (iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function (args) { var thisArg = this || _global; return arrayFunc(iteratees, function (iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this || _global) && (this || _global) !== root && (this || _global) instanceof wrapper ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this || _global, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function (start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? start < end ? 1 : -1 : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function (value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG; bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function (number, precision) { number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); if (precision && nativeIsFinite(number)) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && 1 / setToArray(new Set([, -0]))[1] == INFINITY) ? noop : function (values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function (object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? isBindKey ? 0 : func.length : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key)) { return srcValue; } return objValue; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source * objects into destination objects that are passed thru. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); stack['delete'](srcValue); } return objValue; } /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function (othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == other + ''; case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function (func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = func.name + '', array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function (object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function (symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function (object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) { getTag = function (value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return typeof object.constructor == 'function' && !isPrototype(object) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return new Ctor(); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return new Ctor(); case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length; } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? isArrayLike(object) && isIndex(index, object.length) : type == 'string' && index in object) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null; } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && maskSrcKey in func; } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = typeof Ctor == 'function' && Ctor.prototype || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function (object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || key in Object(object)); }; } /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function (key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data[7].length <= source[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source[7].length <= source[8] && bitmask == WRAP_CURRY_FLAG; // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? func.length - 1 : start, 0); return function () { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this || _global, otherArgs); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { if (key === 'constructor' && typeof object[key] === 'function') { return; } if (key == '__proto__') { return; } return object[key]; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function (func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = reference + ''; return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function () { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } /** * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private * @param {Array} array The array to shuffle. * @param {number} [size=array.length] The size of `array`. * @returns {Array} Returns `array`. */ function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function (string) { var result = []; if (string.charCodeAt(0) === 46 /* . */ ) { result.push(''); } string.replace(rePropName, function (match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = value + ''; return result == '0' && 1 / value == -INFINITY ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return func + ''; } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function (pair) { var value = '_.' + pair[0]; if (bitmask & pair[1] && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if (guard ? isIterateeCall(array, size, guard) : size === undefined) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, index += size); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length; if (!length) { return []; } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function (array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function (array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function (array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = guard || n === undefined ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = guard || n === undefined ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return array && array.length ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function (arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function (arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The order and references * of result values are determined by the first array. The comparator is * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function (arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == 'function' ? comparator : undefined; if (comparator) { mapped.pop(); } return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array == null ? '' : nativeJoin.call(array, separator); } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return array && array.length ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return array && array.length && values && values.length ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return array && array.length && values && values.length ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return array && array.length && values && values.length ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = flatRest(function (array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function (index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array == null ? array : nativeReverse.call(array); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return array && array.length ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return array && array.length ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = guard || n === undefined ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = guard || n === undefined ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return array && array.length ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return array && array.length ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function (arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function (arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function (arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. The order of result values is determined by the order they occur * in the array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return array && array.length ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return array && array.length ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { comparator = typeof comparator == 'function' ? comparator : undefined; return array && array.length ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function (group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function (index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function (group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function (array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function (arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The order of result values is determined * by the order they occur in the arrays. The iteratee is invoked with one * argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function (arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The order of result values is * determined by the order they occur in the arrays. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function (arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine * grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function (arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = flatRest(function (paths) { var length = paths.length, start = length ? paths[0] : 0, value = (this || _global).__wrapped__, interceptor = function (object) { return baseAt(object, paths); }; if (length > 1 || (this || _global).__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, (this || _global).__chain__).thru(function (array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this || _global); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), (this || _global).__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if ((this || _global).__values__ === undefined) { (this || _global).__values__ = toArray(this.value()); } var done = (this || _global).__index__ >= (this || _global).__values__.length, value = done ? undefined : (this || _global).__values__[(this || _global).__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this || _global; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this || _global; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = (this || _global).__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if ((this || _global).__actions__.length) { wrapped = new LazyWrapper(this || _global); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, (this || _global).__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue((this || _global).__wrapped__, (this || _global).__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function (result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { baseAssignValue(result, key, 1); } }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function (result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1; } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function (collection, path, args) { var index = -1, isFunc = typeof path == 'function', result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function (value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function (result, value, key) { baseAssignValue(result, key, value); }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function (result, value, key) { result[key ? 0 : 1].push(value); }, function () { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection); } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { if (guard ? isIterateeCall(collection, n, guard) : n === undefined) { n = 1; } else { n = toInteger(n); } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] */ var sortBy = baseRest(function (collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function () { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function () { if (--n < 1) { return func.apply(this || _global, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = func && n == null ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function () { if (--n > 0) { result = func.apply(this || _global, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function (func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function (object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this || _global; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. clearTimeout(timerId); timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ var defer = baseRest(function (func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function (func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, WRAP_FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || resolver != null && typeof resolver != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function () { var args = arguments, key = resolver ? resolver.apply(this || _global, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this || _global, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache)(); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function () { var args = arguments; switch (args.length) { case 0: return !predicate.call(this || _global); case 1: return !predicate.call(this || _global, args[0]); case 2: return !predicate.call(this || _global, args[0], args[1]); case 3: return !predicate.call(this || _global, args[0], args[1], args[2]); } return !predicate.apply(this || _global, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = castRest(function (func, transforms) { transforms = transforms.length == 1 && isArray(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function (args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this || _global, args[index]); } return apply(func, this || _global, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function (func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function (func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function (func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function (args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this || _global, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('fred, barney, & pebbles'); * // => '<p>fred, barney, &amp; pebbles</p>' */ function wrap(value, wrapper) { return partial(castFunction(wrapper), value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || value !== value && other !== other; } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function (value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function () { return arguments; }()) ? baseIsArguments : function (value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || isObjectLike(value) && baseGetTag(value) == boolTag; } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement('<body>'); * // => false */ function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || isObjectLike(value) && baseGetTag(value) == numberTag; } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || !isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || isObjectLike(value) && baseGetTag(value) == symbolTag; } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function (value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : tag == setTag ? setToArray : values; return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = value < 0 ? -1 : 1; return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? remainder ? result - remainder : result : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? other + '' : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : value === 0 ? value : 0; } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function (object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function (object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function (object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function (object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = flatRest(baseAt); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties == null ? result : baseAssign(result, properties); } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function (object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || eq(value, objectProto[key]) && !hasOwnProperty.call(object, key)) { object[key] = source[key]; } } } return object; }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function (args) { args.push(undefined, customDefaultsMerge); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function (result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function (result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function (value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function (value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function (object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with six arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function (object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function (object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function (path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function (object, paths) { return object == null ? {} : basePick(object, paths); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function (prop) { return [prop]; }); predicate = getIteratee(predicate); return basePickBy(object, props, function (value, path) { return predicate(value, path[0]); }); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { length = 1; object = undefined; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor() : []; } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } (isArrLike ? arrayEach : baseForOwn)(object, function (value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function (result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', and "'" in `string` to their * corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, &amp; pebbles' */ function escape(string) { string = toString(string); return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function (result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function (result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return length && strLength < length ? string + createPadding(length - strLength, chars) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return length && strLength < length ? createPadding(length - strLength, chars) + string : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if (guard ? isIterateeCall(string, n, guard) : n === undefined) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function (result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && (typeof separator == 'string' || separator != null && !isRegExp(separator))) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function (result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<b><%- value %></b>'); * compiled({ 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the internal `print` function in "evaluate" delimiters. * var compiled = _.template('<% print("hello " + user); %>!'); * compiled({ 'user': 'barney' }); * // => 'hello barney!' * * // Use the ES template literal delimiter as an "interpolate" delimiter. * // Disable support by replacing the "interpolate" delimiter. * var compiled = _.template('hello ${ user }!'); * compiled({ 'user': 'pebbles' }); * // => 'hello pebbles!' * * // Use backslashes to treat delimiters as plain text. * var compiled = _.template('<%= "\\<%- value %\\>" %>'); * compiled({ 'value': 'ignored' }); * // => '<%- value %>' * * // Use the `imports` option to import `jQuery` as `jq`. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the `sourceURL` option to specify a custom sourceURL for the template. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. * * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); * compiled.source; * // => function(data) { * // var __t, __p = ''; * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; * // return __p; * // } * * // Use custom template delimiters. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; * var compiled = _.template('hello {{ user }}!'); * compiled({ 'user': 'mustache' }); * // => 'hello mustache!' * * // Use the `source` property to inline compiled templates for meaningful * // line numbers in error messages and stack traces. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined; } string = toString(string); options = assignInWith({}, options, settings, customDefaultsAssignIn); var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp((options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$', 'g'); // Use a sourceURL for easier debugging. // The sourceURL gets injected into the source that's eval-ed, so be careful // with lookup (in case of e.g. prototype pollution), and strip newlines if any. // A newline wouldn't be a valid sourceURL anyway, and it'd enable code injection. var sourceURL = '//# sourceURL=' + (hasOwnProperty.call(options, 'sourceURL') ? (options.sourceURL + '').replace(/[\r\n]/g, ' ') : 'lodash.templateSources[' + ++templateCounter + ']') + '\n'; string.replace(reDelimiters, function (match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. // Like with sourceURL, we take care to not check the option's prototype, // as this configuration is a code injection vector. var variable = hasOwnProperty.call(options, 'variable') && options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source).replace(reEmptyStringMiddle, '$1').replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n') + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '') + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n') + source + 'return __p\n}'; var result = attempt(function () { return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; } /** * Converts `string`, as a whole, to lower case just like * [String#toLowerCase](https://mdn.io/toLowerCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.toLower('--Foo-Bar--'); * // => '--foo-bar--' * * _.toLower('fooBar'); * // => 'foobar' * * _.toLower('__FOO_BAR__'); * // => '__foo_bar__' */ function toLower(value) { return toString(value).toLowerCase(); } /** * Converts `string`, as a whole, to upper case just like * [String#toUpperCase](https://mdn.io/toUpperCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.toUpper('--foo-bar--'); * // => '--FOO-BAR--' * * _.toUpper('fooBar'); * // => 'FOOBAR' * * _.toUpper('__foo_bar__'); * // => '__FOO_BAR__' */ function toUpper(value) { return toString(value).toUpperCase(); } /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } /** * Removes trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimEnd(' abc '); * // => ' abc' * * _.trimEnd('-_-abc-_-', '_-'); * // => '-_-abc' */ function trimEnd(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimEnd, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; return castSlice(strSymbols, 0, end).join(''); } /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimStart(' abc '); * // => 'abc ' * * _.trimStart('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimStart(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimStart, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); return castSlice(strSymbols, start).join(''); } /** * Truncates `string` if it's longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to truncate. * @param {Object} [options={}] The options object. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @returns {string} Returns the truncated string. * @example * * _.truncate('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? toInteger(options.length) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } string = toString(string); var strLength = string.length; if (hasUnicode(string)) { var strSymbols = stringToArray(string); strLength = strSymbols.length; } if (length >= strLength) { return string; } var end = length - stringSize(omission); if (end < 1) { return omission; } var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end); if (separator === undefined) { return result + omission; } if (strSymbols) { end += result.length - end; } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, substring = result; if (!separator.global) { separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); } separator.lastIndex = 0; while (match = separator.exec(substring)) { var newEnd = match.index; } result = result.slice(0, newEnd === undefined ? end : newEnd); } } else if (string.indexOf(baseToString(separator), end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } /** * The inverse of `_.escape`; this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to * their corresponding characters. * * **Note:** No other HTML entities are unescaped. To unescape additional * HTML entities use a third-party library like [_he_](https://mths.be/he). * * @static * @memberOf _ * @since 0.6.0 * @category String * @param {string} [string=''] The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('fred, barney, &amp; pebbles'); * // => 'fred, barney, & pebbles' */ function unescape(string) { string = toString(string); return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } /** * Converts `string`, as space separated words, to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.upperCase('--foo-bar'); * // => 'FOO BAR' * * _.upperCase('fooBar'); * // => 'FOO BAR' * * _.upperCase('__foo_bar__'); * // => 'FOO BAR' */ var upperCase = createCompounder(function (result, word, index) { return result + (index ? ' ' : '') + word.toUpperCase(); }); /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); } return string.match(pattern) || []; } /*------------------------------------------------------------------------*/ /** * Attempts to invoke `func`, returning either the result or the caught error * object. Any additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Function} func The function to attempt. * @param {...*} [args] The arguments to invoke `func` with. * @returns {*} Returns the `func` result or error object. * @example * * // Avoid throwing errors for invalid selectors. * var elements = _.attempt(function(selector) { * return document.querySelectorAll(selector); * }, '>_>'); * * if (_.isError(elements)) { * elements = []; * } */ var attempt = baseRest(function (func, args) { try { return apply(func, undefined, args); } catch (e) { return isError(e) ? e : new Error(e); } }); /** * Binds methods of an object to the object itself, overwriting the existing * method. * * **Note:** This method doesn't set the "length" property of bound functions. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Object} object The object to bind and assign the bound methods to. * @param {...(string|string[])} methodNames The object method names to bind. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'click': function() { * console.log('clicked ' + this.label); * } * }; * * _.bindAll(view, ['click']); * jQuery(element).on('click', view.click); * // => Logs 'clicked docs' when clicked. */ var bindAll = flatRest(function (object, methodNames) { arrayEach(methodNames, function (key) { key = toKey(key); baseAssignValue(object, key, bind(object[key], object)); }); return object; }); /** * Creates a function that iterates over `pairs` and invokes the corresponding * function of the first predicate to return truthy. The predicate-function * pairs are invoked with the `this` binding and arguments of the created * function. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Array} pairs The predicate-function pairs. * @returns {Function} Returns the new composite function. * @example * * var func = _.cond([ * [_.matches({ 'a': 1 }), _.constant('matches A')], * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], * [_.stubTrue, _.constant('no match')] * ]); * * func({ 'a': 1, 'b': 2 }); * // => 'matches A' * * func({ 'a': 0, 'b': 1 }); * // => 'matches B' * * func({ 'a': '1', 'b': '2' }); * // => 'no match' */ function cond(pairs) { var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); pairs = !length ? [] : arrayMap(pairs, function (pair) { if (typeof pair[1] != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return [toIteratee(pair[0]), pair[1]]; }); return baseRest(function (args) { var index = -1; while (++index < length) { var pair = pairs[index]; if (apply(pair[0], this || _global, args)) { return apply(pair[1], this || _global, args); } } }); } /** * Creates a function that invokes the predicate properties of `source` with * the corresponding property values of a given object, returning `true` if * all predicates return truthy, else `false`. * * **Note:** The created function is equivalent to `_.conformsTo` with * `source` partially applied. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 2, 'b': 1 }, * { 'a': 1, 'b': 2 } * ]; * * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); * // => [{ 'a': 1, 'b': 2 }] */ function conforms(source) { return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function () { return value; }; } /** * Checks `value` to determine whether a default value should be returned in * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, * or `undefined`. * * @static * @memberOf _ * @since 4.14.0 * @category Util * @param {*} value The value to check. * @param {*} defaultValue The default value. * @returns {*} Returns the resolved value. * @example * * _.defaultTo(1, 10); * // => 1 * * _.defaultTo(undefined, 10); * // => 10 */ function defaultTo(value, defaultValue) { return value == null || value !== value ? defaultValue : value; } /** * Creates a function that returns the result of invoking the given functions * with the `this` binding of the created function, where each successive * invocation is supplied the return value of the previous. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flowRight * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flow([_.add, square]); * addSquare(1, 2); * // => 9 */ var flow = createFlow(); /** * This method is like `_.flow` except that it creates a function that * invokes the given functions from right to left. * * @static * @since 3.0.0 * @memberOf _ * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flow * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight([square, _.add]); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } /** * Creates a function that invokes `func` with the arguments of the created * function. If `func` is a property name, the created function returns the * property value for a given element. If `func` is an array or object, the * created function returns `true` for elements that contain the equivalent * source properties, otherwise it returns `false`. * * @static * @since 4.0.0 * @memberOf _ * @category Util * @param {*} [func=_.identity] The value to convert to a callback. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); * // => [{ 'user': 'barney', 'age': 36, 'active': true }] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, _.iteratee(['user', 'fred'])); * // => [{ 'user': 'fred', 'age': 40 }] * * // The `_.property` iteratee shorthand. * _.map(users, _.iteratee('user')); * // => ['barney', 'fred'] * * // Create custom iteratee shorthands. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { * return !_.isRegExp(func) ? iteratee(func) : function(string) { * return func.test(string); * }; * }); * * _.filter(['abc', 'def'], /ef/); * // => ['def'] */ function iteratee(func) { return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between a given * object and `source`, returning `true` if the given object has equivalent * property values, else `false`. * * **Note:** The created function is equivalent to `_.isMatch` with `source` * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); * // => [{ 'a': 4, 'b': 5, 'c': 6 }] */ function matches(source) { return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between the * value at `path` of a given object to `srcValue`, returning `true` if the * object value is equivalent, else `false`. * * **Note:** Partial comparisons will match empty array and empty object * `srcValue` values against any array or object value, respectively. See * `_.isEqual` for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.2.0 * @category Util * @param {Array|string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.find(objects, _.matchesProperty('a', 4)); * // => { 'a': 4, 'b': 5, 'c': 6 } */ function matchesProperty(path, srcValue) { return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); } /** * Creates a function that invokes the method at `path` of a given object. * Any additional arguments are provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var objects = [ * { 'a': { 'b': _.constant(2) } }, * { 'a': { 'b': _.constant(1) } } * ]; * * _.map(objects, _.method('a.b')); * // => [2, 1] * * _.map(objects, _.method(['a', 'b'])); * // => [2, 1] */ var method = baseRest(function (path, args) { return function (object) { return baseInvoke(object, path, args); }; }); /** * The opposite of `_.method`; this method creates a function that invokes * the method at a given path of `object`. Any additional arguments are * provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Object} object The object to query. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var array = _.times(3, _.constant), * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.methodOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); * // => [2, 0] */ var methodOf = baseRest(function (object, args) { return function (path) { return baseInvoke(object, path, args); }; }); /** * Adds all own enumerable string keyed function properties of a source * object to the destination object. If `object` is a function, then methods * are added to its prototype as well. * * **Note:** Use `_.runInContext` to create a pristine `lodash` function to * avoid conflicts caused by modifying the original. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options={}] The options object. * @param {boolean} [options.chain=true] Specify whether mixins are chainable. * @returns {Function|Object} Returns `object`. * @example * * function vowels(string) { * return _.filter(string, function(v) { * return /[aeiou]/i.test(v); * }); * } * * _.mixin({ 'vowels': vowels }); * _.vowels('fred'); * // => ['e'] * * _('fred').vowels().value(); * // => ['e'] * * _.mixin({ 'vowels': vowels }, { 'chain': false }); * _('fred').vowels(); * // => ['e'] */ function mixin(object, source, options) { var props = keys(source), methodNames = baseFunctions(source, props); if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { options = source; source = object; object = this || _global; methodNames = baseFunctions(source, keys(source)); } var chain = !(isObject(options) && 'chain' in options) || !!options.chain, isFunc = isFunction(object); arrayEach(methodNames, function (methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = function () { var chainAll = (this || _global).__chain__; if (chain || chainAll) { var result = object((this || _global).__wrapped__), actions = result.__actions__ = copyArray((this || _global).__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } return func.apply(object, arrayPush([this.value()], arguments)); }; } }); return object; } /** * Reverts the `_` variable to its previous value and returns a reference to * the `lodash` function. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { if (root._ === (this || _global)) { root._ = oldDash; } return this || _global; } /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() {} // No operation performed. /** * Creates a function that gets the argument at index `n`. If `n` is negative, * the nth argument from the end is returned. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [n=0] The index of the argument to return. * @returns {Function} Returns the new pass-thru function. * @example * * var func = _.nthArg(1); * func('a', 'b', 'c', 'd'); * // => 'b' * * var func = _.nthArg(-2); * func('a', 'b', 'c', 'd'); * // => 'c' */ function nthArg(n) { n = toInteger(n); return baseRest(function (args) { return baseNth(args, n); }); } /** * Creates a function that invokes `iteratees` with the arguments it receives * and returns their results. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to invoke. * @returns {Function} Returns the new function. * @example * * var func = _.over([Math.max, Math.min]); * * func(1, 2, 3, 4); * // => [4, 1] */ var over = createOver(arrayMap); /** * Creates a function that checks if **all** of the `predicates` return * truthy when invoked with the arguments it receives. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overEvery([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => false * * func(NaN); * // => false */ var overEvery = createOver(arrayEvery); /** * Creates a function that checks if **any** of the `predicates` return * truthy when invoked with the arguments it receives. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overSome([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => true * * func(NaN); * // => false */ var overSome = createOver(arraySome); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function that returns * the value at a given path of `object`. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function (path) { return object == null ? undefined : baseGet(object, path); }; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); /** * This method is like `_.range` except that it populates values in * descending order. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.range * @example * * _.rangeRight(4); * // => [3, 2, 1, 0] * * _.rangeRight(-4); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 5); * // => [4, 3, 2, 1] * * _.rangeRight(0, 20, 5); * // => [15, 10, 5, 0] * * _.rangeRight(0, -4, -1); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 4, 0); * // => [1, 1, 1] * * _.rangeRight(0); * // => [] */ var rangeRight = createRange(true); /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } /** * This method returns a new empty object. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Object} Returns the new empty object. * @example * * var objects = _.times(2, _.stubObject); * * console.log(objects); * // => [{}, {}] * * console.log(objects[0] === objects[1]); * // => false */ function stubObject() { return {}; } /** * This method returns an empty string. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {string} Returns the empty string. * @example * * _.times(2, _.stubString); * // => ['', ''] */ function stubString() { return ''; } /** * This method returns `true`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `true`. * @example * * _.times(2, _.stubTrue); * // => [true, true] */ function stubTrue() { return true; } /** * Invokes the iteratee `n` times, returning an array of the results of * each invocation. The iteratee is invoked with one argument; (index). * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} n The number of times to invoke `iteratee`. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of results. * @example * * _.times(3, String); * // => ['0', '1', '2'] * * _.times(4, _.constant(0)); * // => [0, 0, 0, 0] */ function times(n, iteratee) { n = toInteger(n); if (n < 1 || n > MAX_SAFE_INTEGER) { return []; } var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); iteratee = getIteratee(iteratee); n -= MAX_ARRAY_LENGTH; var result = baseTimes(length, iteratee); while (++index < n) { iteratee(index); } return result; } /** * Converts `value` to a property path array. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] */ function toPath(value) { if (isArray(value)) { return arrayMap(value, toKey); } return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); } /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } /*------------------------------------------------------------------------*/ /** * Adds two numbers. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {number} augend The first number in an addition. * @param {number} addend The second number in an addition. * @returns {number} Returns the total. * @example * * _.add(6, 4); * // => 10 */ var add = createMathOperation(function (augend, addend) { return augend + addend; }, 0); /** * Computes `number` rounded up to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round up. * @param {number} [precision=0] The precision to round up to. * @returns {number} Returns the rounded up number. * @example * * _.ceil(4.006); * // => 5 * * _.ceil(6.004, 2); * // => 6.01 * * _.ceil(6040, -2); * // => 6100 */ var ceil = createRound('ceil'); /** * Divide two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} dividend The first number in a division. * @param {number} divisor The second number in a division. * @returns {number} Returns the quotient. * @example * * _.divide(6, 4); * // => 1.5 */ var divide = createMathOperation(function (dividend, divisor) { return dividend / divisor; }, 1); /** * Computes `number` rounded down to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round down. * @param {number} [precision=0] The precision to round down to. * @returns {number} Returns the rounded down number. * @example * * _.floor(4.006); * // => 4 * * _.floor(0.046, 2); * // => 0.04 * * _.floor(4060, -2); * // => 4000 */ var floor = createRound('floor'); /** * Computes the maximum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * _.max([]); * // => undefined */ function max(array) { return array && array.length ? baseExtremum(array, identity, baseGt) : undefined; } /** * This method is like `_.max` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the maximum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.maxBy(objects, function(o) { return o.n; }); * // => { 'n': 2 } * * // The `_.property` iteratee shorthand. * _.maxBy(objects, 'n'); * // => { 'n': 2 } */ function maxBy(array, iteratee) { return array && array.length ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) : undefined; } /** * Computes the mean of the values in `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the mean. * @example * * _.mean([4, 2, 8, 6]); * // => 5 */ function mean(array) { return baseMean(array, identity); } /** * This method is like `_.mean` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be averaged. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the mean. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.meanBy(objects, function(o) { return o.n; }); * // => 5 * * // The `_.property` iteratee shorthand. * _.meanBy(objects, 'n'); * // => 5 */ function meanBy(array, iteratee) { return baseMean(array, getIteratee(iteratee, 2)); } /** * Computes the minimum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * _.min([]); * // => undefined */ function min(array) { return array && array.length ? baseExtremum(array, identity, baseLt) : undefined; } /** * This method is like `_.min` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the minimum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.minBy(objects, function(o) { return o.n; }); * // => { 'n': 1 } * * // The `_.property` iteratee shorthand. * _.minBy(objects, 'n'); * // => { 'n': 1 } */ function minBy(array, iteratee) { return array && array.length ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) : undefined; } /** * Multiply two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} multiplier The first number in a multiplication. * @param {number} multiplicand The second number in a multiplication. * @returns {number} Returns the product. * @example * * _.multiply(6, 4); * // => 24 */ var multiply = createMathOperation(function (multiplier, multiplicand) { return multiplier * multiplicand; }, 1); /** * Computes `number` rounded to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round. * @param {number} [precision=0] The precision to round to. * @returns {number} Returns the rounded number. * @example * * _.round(4.006); * // => 4 * * _.round(4.006, 2); * // => 4.01 * * _.round(4060, -2); * // => 4100 */ var round = createRound('round'); /** * Subtract two numbers. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {number} minuend The first number in a subtraction. * @param {number} subtrahend The second number in a subtraction. * @returns {number} Returns the difference. * @example * * _.subtract(6, 4); * // => 2 */ var subtract = createMathOperation(function (minuend, subtrahend) { return minuend - subtrahend; }, 0); /** * Computes the sum of the values in `array`. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. * @example * * _.sum([4, 2, 8, 6]); * // => 20 */ function sum(array) { return array && array.length ? baseSum(array, identity) : 0; } /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return array && array.length ? baseSum(array, getIteratee(iteratee, 2)) : 0; } /*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences. lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.assignIn = assignIn; lodash.assignInWith = assignInWith; lodash.assignWith = assignWith; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.castArray = castArray; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.concat = concat; lodash.cond = cond; lodash.conforms = conforms; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defaultsDeep = defaultsDeep; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.differenceBy = differenceBy; lodash.differenceWith = differenceWith; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatMap = flatMap; lodash.flatMapDeep = flatMapDeep; lodash.flatMapDepth = flatMapDepth; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flattenDepth = flattenDepth; lodash.flip = flip; lodash.flow = flow; lodash.flowRight = flowRight; lodash.fromPairs = fromPairs; lodash.functions = functions; lodash.functionsIn = functionsIn; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.intersectionBy = intersectionBy; lodash.intersectionWith = intersectionWith; lodash.invert = invert; lodash.invertBy = invertBy; lodash.invokeMap = invokeMap; lodash.iteratee = iteratee; lodash.keyBy = keyBy; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapKeys = mapKeys; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.mergeWith = mergeWith; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.nthArg = nthArg; lodash.omit = omit; lodash.omitBy = omitBy; lodash.once = once; lodash.orderBy = orderBy; lodash.over = over; lodash.overArgs = overArgs; lodash.overEvery = overEvery; lodash.overSome = overSome; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pickBy = pickBy; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAll = pullAll; lodash.pullAllBy = pullAllBy; lodash.pullAllWith = pullAllWith; lodash.pullAt = pullAt; lodash.range = range; lodash.rangeRight = rangeRight; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.reverse = reverse; lodash.sampleSize = sampleSize; lodash.set = set; lodash.setWith = setWith; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortedUniq = sortedUniq; lodash.sortedUniqBy = sortedUniqBy; lodash.split = split; lodash.spread = spread; lodash.tail = tail; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.toArray = toArray; lodash.toPairs = toPairs; lodash.toPairsIn = toPairsIn; lodash.toPath = toPath; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.unary = unary; lodash.union = union; lodash.unionBy = unionBy; lodash.unionWith = unionWith; lodash.uniq = uniq; lodash.uniqBy = uniqBy; lodash.uniqWith = uniqWith; lodash.unset = unset; lodash.unzip = unzip; lodash.unzipWith = unzipWith; lodash.update = update; lodash.updateWith = updateWith; lodash.values = values; lodash.valuesIn = valuesIn; lodash.without = without; lodash.words = words; lodash.wrap = wrap; lodash.xor = xor; lodash.xorBy = xorBy; lodash.xorWith = xorWith; lodash.zip = zip; lodash.zipObject = zipObject; lodash.zipObjectDeep = zipObjectDeep; lodash.zipWith = zipWith; // Add aliases. lodash.entries = toPairs; lodash.entriesIn = toPairsIn; lodash.extend = assignIn; lodash.extendWith = assignInWith; // Add methods to `lodash.prototype`. mixin(lodash, lodash); /*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences. lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.ceil = ceil; lodash.clamp = clamp; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; lodash.cloneWith = cloneWith; lodash.conformsTo = conformsTo; lodash.deburr = deburr; lodash.defaultTo = defaultTo; lodash.divide = divide; lodash.endsWith = endsWith; lodash.eq = eq; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.floor = floor; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.get = get; lodash.gt = gt; lodash.gte = gte; lodash.has = has; lodash.hasIn = hasIn; lodash.head = head; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.invoke = invoke; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isArrayBuffer = isArrayBuffer; lodash.isArrayLike = isArrayLike; lodash.isArrayLikeObject = isArrayLikeObject; lodash.isBoolean = isBoolean; lodash.isBuffer = isBuffer; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isEqualWith = isEqualWith; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isInteger = isInteger; lodash.isLength = isLength; lodash.isMap = isMap; lodash.isMatch = isMatch; lodash.isMatchWith = isMatchWith; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNil = isNil; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isObjectLike = isObjectLike; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isSafeInteger = isSafeInteger; lodash.isSet = isSet; lodash.isString = isString; lodash.isSymbol = isSymbol; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.isWeakMap = isWeakMap; lodash.isWeakSet = isWeakSet; lodash.join = join; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.lowerCase = lowerCase; lodash.lowerFirst = lowerFirst; lodash.lt = lt; lodash.lte = lte; lodash.max = max; lodash.maxBy = maxBy; lodash.mean = mean; lodash.meanBy = meanBy; lodash.min = min; lodash.minBy = minBy; lodash.stubArray = stubArray; lodash.stubFalse = stubFalse; lodash.stubObject = stubObject; lodash.stubString = stubString; lodash.stubTrue = stubTrue; lodash.multiply = multiply; lodash.nth = nth; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padEnd = padEnd; lodash.padStart = padStart; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.replace = replace; lodash.result = result; lodash.round = round; lodash.runInContext = runInContext; lodash.sample = sample; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedIndexBy = sortedIndexBy; lodash.sortedIndexOf = sortedIndexOf; lodash.sortedLastIndex = sortedLastIndex; lodash.sortedLastIndexBy = sortedLastIndexBy; lodash.sortedLastIndexOf = sortedLastIndexOf; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.subtract = subtract; lodash.sum = sum; lodash.sumBy = sumBy; lodash.template = template; lodash.times = times; lodash.toFinite = toFinite; lodash.toInteger = toInteger; lodash.toLength = toLength; lodash.toLower = toLower; lodash.toNumber = toNumber; lodash.toSafeInteger = toSafeInteger; lodash.toString = toString; lodash.toUpper = toUpper; lodash.trim = trim; lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; // Add aliases. lodash.each = forEach; lodash.eachRight = forEachRight; lodash.first = head; mixin(lodash, function () { var source = {}; baseForOwn(lodash, function (func, methodName) { if (!hasOwnProperty.call(lodash.prototype, methodName)) { source[methodName] = func; } }); return source; }(), { 'chain': false }); /*------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type {string} */ lodash.VERSION = VERSION; // Assign default placeholders. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function (methodName) { lodash[methodName].placeholder = lodash; }); // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. arrayEach(['drop', 'take'], function (methodName, index) { LazyWrapper.prototype[methodName] = function (n) { n = n === undefined ? 1 : nativeMax(toInteger(n), 0); var result = (this || _global).__filtered__ && !index ? new LazyWrapper(this || _global) : this.clone(); if (result.__filtered__) { result.__takeCount__ = nativeMin(n, result.__takeCount__); } else { result.__views__.push({ 'size': nativeMin(n, MAX_ARRAY_LENGTH), 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') }); } return result; }; LazyWrapper.prototype[methodName + 'Right'] = function (n) { return this.reverse()[methodName](n).reverse(); }; }); // Add `LazyWrapper` methods that accept an `iteratee` value. arrayEach(['filter', 'map', 'takeWhile'], function (methodName, index) { var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; LazyWrapper.prototype[methodName] = function (iteratee) { var result = this.clone(); result.__iteratees__.push({ 'iteratee': getIteratee(iteratee, 3), 'type': type }); result.__filtered__ = result.__filtered__ || isFilter; return result; }; }); // Add `LazyWrapper` methods for `_.head` and `_.last`. arrayEach(['head', 'last'], function (methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); LazyWrapper.prototype[methodName] = function () { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.tail`. arrayEach(['initial', 'tail'], function (methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); LazyWrapper.prototype[methodName] = function () { return (this || _global).__filtered__ ? new LazyWrapper(this || _global) : this[dropName](1); }; }); LazyWrapper.prototype.compact = function () { return this.filter(identity); }; LazyWrapper.prototype.find = function (predicate) { return this.filter(predicate).head(); }; LazyWrapper.prototype.findLast = function (predicate) { return this.reverse().find(predicate); }; LazyWrapper.prototype.invokeMap = baseRest(function (path, args) { if (typeof path == 'function') { return new LazyWrapper(this || _global); } return this.map(function (value) { return baseInvoke(value, path, args); }); }); LazyWrapper.prototype.reject = function (predicate) { return this.filter(negate(getIteratee(predicate))); }; LazyWrapper.prototype.slice = function (start, end) { start = toInteger(start); var result = this || _global; if (result.__filtered__ && (start > 0 || end < 0)) { return new LazyWrapper(result); } if (start < 0) { result = result.takeRight(-start); } else if (start) { result = result.drop(start); } if (end !== undefined) { end = toInteger(end); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } return result; }; LazyWrapper.prototype.takeRightWhile = function (predicate) { return this.reverse().takeWhile(predicate).reverse(); }; LazyWrapper.prototype.toArray = function () { return this.take(MAX_ARRAY_LENGTH); }; // Add `LazyWrapper` methods to `lodash.prototype`. baseForOwn(LazyWrapper.prototype, function (func, methodName) { var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? 'take' + (methodName == 'last' ? 'Right' : '') : methodName], retUnwrapped = isTaker || /^find/.test(methodName); if (!lodashFunc) { return; } lodash.prototype[methodName] = function () { var value = (this || _global).__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); var interceptor = function (value) { var result = lodashFunc.apply(lodash, arrayPush([value], args)); return isTaker && chainAll ? result[0] : result; }; if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { // Avoid lazy use if the iteratee has a "length" value other than `1`. isLazy = useLazy = false; } var chainAll = (this || _global).__chain__, isHybrid = !!(this || _global).__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; if (!retUnwrapped && useLazy) { value = onlyLazy ? value : new LazyWrapper(this || _global); var result = func.apply(value, args); result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(result, chainAll); } if (isUnwrapped && onlyLazy) { return func.apply(this || _global, args); } result = this.thru(interceptor); return isUnwrapped ? isTaker ? result.value()[0] : result.value() : result; }; }); // Add `Array` methods to `lodash.prototype`. arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function (methodName) { var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:pop|shift)$/.test(methodName); lodash.prototype[methodName] = function () { var args = arguments; if (retUnwrapped && !(this || _global).__chain__) { var value = this.value(); return func.apply(isArray(value) ? value : [], args); } return this[chainName](function (value) { return func.apply(isArray(value) ? value : [], args); }); }; }); // Map minified method names to their real names. baseForOwn(LazyWrapper.prototype, function (func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = lodashFunc.name + ''; if (!hasOwnProperty.call(realNames, key)) { realNames[key] = []; } realNames[key].push({ 'name': methodName, 'func': lodashFunc }); } }); realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }]; // Add methods to `LazyWrapper`. LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; // Add chain sequence methods to the `lodash` wrapper. lodash.prototype.at = wrapperAt; lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.next = wrapperNext; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; // Add lazy aliases. lodash.prototype.first = lodash.prototype.head; if (symIterator) { lodash.prototype[symIterator] = wrapperToIterator; } return lodash; }; /*--------------------------------------------------------------------------*/ // Export lodash. var _ = runInContext(); // Some AMD build optimizers, like r.js, check for condition patterns like: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // Expose Lodash on the global object to prevent errors when Lodash is // loaded by a script tag in the presence of an AMD loader. // See http://requirejs.org/docs/errors.html#mismatch for more details. // Use `_.noConflict` to remove Lodash from the global object. root._ = _; // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. define(function () { return _; }); } // Check for `exports` after `define` in case a build optimizer adds it. else if (freeModule) { // Export for Node.js. (freeModule.exports = _)._ = _; // Export for CommonJS support. freeExports._ = _; } else { // Export to the global object. root._ = _; } }).call(exports); return module.exports; }
the_stack
import {Component, Output, EventEmitter, Inject, ElementRef} from "@angular/core"; import {REACT_NATIVE_WRAPPER} from "../../renderer/renderer"; import {Node} from "../../renderer/node"; import {ReactNativeWrapper, isAndroid} from "../../wrapper/wrapper"; import {HighLevelComponent, GENERIC_INPUTS, GENERIC_BINDINGS} from "./component"; var ANDROID_INPUTS: Array<string> = ['endFillColor']; var IOS_INPUTS: Array<string> = ['alwaysBounceHorizontal', 'alwaysBounceVertical', 'automaticallyAdjustContentInsets', 'bounces', 'bouncesZoom', 'canCancelContentTouches', 'centerContent', 'contentInset', 'contentOffset', 'decelerationRate', 'directionalLockEnabled', 'indicatorStyle', 'maximumZoomScale', 'minimumZoomScale', 'scrollEventThrottle', 'scrollIndicatorInsets', 'scrollsToTop', 'snapToAlignment', 'snapToInterval', 'stickyHeaderIndices', 'zoomScale']; var ANDROID_BINDINGS: string = `[endFillColor]="_endFillColor"`; var IOS_BINDINGS: string = `[alwaysBounceHorizontal]="_alwaysBounceHorizontal" [alwaysBounceVertical]="_alwaysBounceVertical" [automaticallyAdjustContentInsets]="_automaticallyAdjustContentInsets" [bounces]="_bounces" [bouncesZoom]="_bouncesZoom" [canCancelContentTouches]="_canCancelContentTouches" [centerContent]="_centerContent" [contentInset]="_contentInset" [contentOffset]="_contentOffset" [decelerationRate]="_decelerationRate" [directionalLockEnabled]="_directionalLockEnabled" [indicatorStyle]="_indicatorStyle" [maximumZoomScale]="_maximumZoomScale" [minimumZoomScale]="_minimumZoomScale" [scrollEventThrottle]="_scrollEventThrottle" [scrollIndicatorInsets]="_scrollIndicatorInsets" [scrollsToTop]="_scrollsToTop" [snapToAlignment]="_snapToAlignment" [snapToInterval]="_snapToInterval" [stickyHeaderIndices]="_stickyHeaderIndices" [zoomScale]="_zoomScale"`; //TODO: refreshControl, onContentSizeChange, onScrollAnimationEnd /** * A component for displaying a scrollview. * * ``` @Component({ selector: 'sample', template: `<ScrollView horizontal="true"> <View></View> <View></View> </ScrollView>` }) export class Sample {} * ``` * * TODO: document usage of RefreshControl on Android and iOS * * @style https://facebook.github.io/react-native/docs/view.html#style */ @Component({ selector: 'ScrollView', inputs: [ 'contentContainerStyle', 'horizontal', 'keyboardDismissMode', 'keyboardShouldPersistTaps', 'pagingEnabled', 'scrollEnabled', 'sendMomentumEvents', 'showsHorizontalScrollIndicator', 'showsVerticalScrollIndicator' ].concat(GENERIC_INPUTS).concat(isAndroid() ? ANDROID_INPUTS : IOS_INPUTS), template: ` <native-scrollview [horizontal]="_horizontal" [keyboardDismissMode]="_keyboardDismissMode" [keyboardShouldPersistTaps]="_keyboardShouldPersistTaps" [pagingEnabled]="_pagingEnabled" [scrollEnabled]="_scrollEnabled" [sendMomentumEvents]="_sendMomentumEvents" [showsHorizontalScrollIndicator]="_showsHorizontalScrollIndicator" [showsVerticalScrollIndicator]="_showsVerticalScrollIndicator" (topScroll)="_handleScroll($event)" (topScrollBeginDrag)="_handleScrollBeginDrag($event)" (topScrollEndDrag)="_handleScrollEndDrag($event)" (topMomentumScrollBegin)="_handleMomentumScrollBegin($event)" (topMomentumScrollEnd)="_handleMomentumScrollEnd($event)" [flexDirection]="_horizontal ? 'row' : 'column'" ${GENERIC_BINDINGS} ${isAndroid() ? ANDROID_BINDINGS : IOS_BINDINGS}> ${isAndroid() ? '' : '<ng-content select="RefreshControl"></ng-content>'} <native-view [removeClippedSubviews]="_removeClippedSubviews" [style]="_contentContainerStyle" collapsable="false" [flexDirection]="_horizontal ? 'row' : null"> <ng-content></ng-content></native-view> </native-scrollview>` }) export class ScrollView extends HighLevelComponent{ private _nativeElement: Node; constructor(@Inject(REACT_NATIVE_WRAPPER) wrapper: ReactNativeWrapper, el: ElementRef) { super(wrapper); this.setDefaultStyle({overflow: 'scroll'}); this._nativeElement = el.nativeElement; } //Events /** * To be documented */ @Output() scroll: EventEmitter<any> = new EventEmitter(); /** * To be documented */ @Output() scrollBeginDrag: EventEmitter<any> = new EventEmitter(); /** * To be documented */ @Output() scrollEndDrag: EventEmitter<any> = new EventEmitter(); /** * To be documented */ @Output() momentumScrollBegin: EventEmitter<any> = new EventEmitter(); /** * To be documented */ @Output() momentumScrollEnd: EventEmitter<any> = new EventEmitter(); //Properties public _contentContainerStyle: any; public _horizontal: boolean; public _keyboardDismissMode: string; public _keyboardShouldPersistTaps: boolean; public _pagingEnabled: boolean; public _scrollEnabled: boolean; public _sendMomentumEvents: boolean; public _showsHorizontalScrollIndicator: boolean; public _showsVerticalScrollIndicator: boolean; /** * To be documented */ set contentContainerStyle(value: any) {this._contentContainerStyle = value;} /** * To be documented */ set horizontal(value: any) {this._horizontal = this.processBoolean(value);} /** * To be documented */ set keyboardDismissMode(value: any) {this._keyboardDismissMode = this.processEnum(value, ['none', 'on-drag', 'interactive']);} /** * To be documented */ set keyboardShouldPersistTaps(value: any) {this._keyboardShouldPersistTaps = this.processBoolean(value);} /** * To be documented */ set pagingEnabled(value: any) {this._pagingEnabled = this.processBoolean(value);} /** * To be documented */ set scrollEnabled(value: any) {this._scrollEnabled = this.processBoolean(value);} /** * To be documented */ set sendMomentumEvents(value: any) {this._sendMomentumEvents = this.processBoolean(value);} /** * To be documented */ set showsHorizontalScrollIndicator(value: any) {this._showsHorizontalScrollIndicator = this.processBoolean(value);} /** * To be documented */ set showsVerticalScrollIndicator(value: any) {this._showsVerticalScrollIndicator = this.processBoolean(value);} public _endFillColor: number; /** * To be documented * @platform android */ set endFillColor(value: string){this._endFillColor = this.processColor(value);} public _alwaysBounceHorizontal: boolean; public _alwaysBounceVertical: boolean; public _automaticallyAdjustContentInsets: boolean; public _bounces: boolean; public _bouncesZoom: boolean; public _canCancelContentTouches: boolean; public _centerContent: boolean; public _contentInset: any; //{0, 0, 0, 0} public _contentOffset: any; //{x: 0, y: 0} public _decelerationRate: number; public _directionalLockEnabled: boolean; public _indicatorStyle: string; public _maximumZoomScale: number; public _minimumZoomScale: number; public _scrollEventThrottle: number; public _scrollIndicatorInsets: any; //{0, 0, 0, 0} public _scrollsToTop: boolean; public _snapToAlignment: string; public _snapToInterval: number; public _stickyHeaderIndices: Array<number>; public _zoomScale: number; /** * To be documented * @platform ios */ set alwaysBounceHorizontal(value: any) {this._alwaysBounceHorizontal = this.processBoolean(value);} /** * To be documented * @platform ios */ set alwaysBounceVertical(value: any) {this._alwaysBounceVertical = this.processBoolean(value);} /** * To be documented * @platform ios */ set automaticallyAdjustContentInsets(value: any) {this._automaticallyAdjustContentInsets = this.processBoolean(value);} /** * To be documented * @platform ios */ set bounces(value: any) {this._bounces = this.processBoolean(value);} /** * To be documented * @platform ios */ set bouncesZoom(value: any) {this._bouncesZoom = this.processBoolean(value);} /** * To be documented * @platform ios */ set canCancelContentTouches(value: any) {this._canCancelContentTouches = this.processBoolean(value);} /** * To be documented * @platform ios */ set centerContent(value: any) {this._centerContent = this.processBoolean(value);} /** * To be documented * @platform ios */ set contentInset(value: any) {this._contentInset = value;} /** * To be documented * @platform ios */ set contentOffset(value: any) {this._contentOffset = value;} /** * To be documented * @platform ios */ set decelerationRate(value: string| number) { if (value === 'normal') { this.getUIManager().RCTScrollView.Constants.DecelerationRate.normal; } else if (value === 'fast') { this.getUIManager().RCTScrollView.Constants.DecelerationRate.fast; } else { this._decelerationRate = this.processNumber(value); } } /** * To be documented * @platform ios */ set directionalLockEnabled(value: any) {this._directionalLockEnabled = this.processBoolean(value);} /** * To be documented * @platform ios */ set indicatorStyle(value: string) {this._indicatorStyle = this.processEnum(value, ['default', 'black', 'white',]);} /** * To be documented * @platform ios */ set maximumZoomScale(value: any) {this._maximumZoomScale = this.processNumber(value);} /** * To be documented * @platform ios */ set minimumZoomScale(value: any) {this._minimumZoomScale = this.processNumber(value);} /** * To be documented * @platform ios */ set scrollEventThrottle(value: any) {this._scrollEventThrottle = this.processNumber(value);} /** * To be documented * @platform ios */ set scrollIndicatorInsets(value: any) {this._scrollIndicatorInsets = value;} /** * To be documented * @platform ios */ set scrollsToTop(value: any) {this._scrollsToTop = this.processBoolean(value);} /** * To be documented * @platform ios */ set snapToAlignment(value: any) {this._snapToAlignment = this.processEnum(value, ['start', 'center', 'end']);} /** * To be documented * @platform ios */ set snapToInterval(value: any) {this._snapToInterval = this.processNumber(value);} /** * To be documented * @platform ios */ set stickyHeaderIndices(value: Array<number>) {this._stickyHeaderIndices = value;} /** * To be documented * @platform ios */ set zoomScale(value: any) {this._zoomScale = this.processNumber(value);} //Event handlers _handleScroll(event: any) { // Event example: // {responderIgnoreScroll: true, layoutMeasurement: {height: 150, width: 400}, contentSize: {height: 150, width: 1200}, // contentOffset: {x: 399.3, y: 0}, contentInset: {bottom: 0, left: 0, right: 0, top: 0}} this.scroll.emit(event); } _handleScrollBeginDrag(event: any) { //Event example: see above this.scrollBeginDrag.emit(event); } _handleScrollEndDrag(event: any) { //Event example: see above this.scrollEndDrag.emit(event); } _handleMomentumScrollBegin(event: any) { //Event example: see above this.momentumScrollBegin.emit(event); } _handleMomentumScrollEnd(event: any) { //Event example: see above this.momentumScrollEnd.emit(event); } //Commands /** * To be documented */ scrollTo(x: number) { this._nativeElement.children[1].dispatchCommand('scrollTo', [x]); } /** * To be documented */ scrollWithoutAnimationTo(x: number) { this._nativeElement.children[1].dispatchCommand('scrollWithoutAnimationTo', [x]); } }
the_stack
import * as http from 'http'; import { parse as parseQueryString } from 'querystring'; import { parse as parseUrl } from 'url'; import { Socket } from 'net'; import { AsyncCreatable, set, toNumber, Env } from '@salesforce/kit'; import { Nullable, get, asString } from '@salesforce/ts-types'; import { OAuth2Options } from 'jsforce'; import { Logger } from './logger'; import { AuthInfo, DEFAULT_CONNECTED_APP_INFO, OAuth2WithVerifier } from './authInfo'; import { SfdxError } from './sfdxError'; import { Messages } from './messages'; import { SfdxProjectJson } from './sfdxProject'; const messages = Messages.loadMessages('@salesforce/core', 'auth'); /** * Handles the creation of a web server for web based login flows. * * Usage: * ``` * const oauthConfig = { * loginUrl: this.flags.instanceurl, * clientId: this.flags.clientid, * }; * * const oauthServer = await WebOAuthServer.create({ oauthConfig }); * await oauthServer.start(); * await open(oauthServer.getAuthorizationUrl(), { wait: false }); * const authInfo = await oauthServer.authorizeAndSave(); * ``` */ export class WebOAuthServer extends AsyncCreatable<WebOAuthServer.Options> { public static DEFAULT_PORT = 1717; private authUrl!: string; private logger!: Logger; private webServer!: WebServer; private oauth2!: OAuth2WithVerifier; private oauthConfig: OAuth2Options; public constructor(options: WebOAuthServer.Options) { super(options); this.oauthConfig = options.oauthConfig; } /** * Returns the configured oauthLocalPort or the WebOAuthServer.DEFAULT_PORT * * @returns {Promise<number>} */ public static async determineOauthPort(): Promise<number> { try { const sfdxProject = await SfdxProjectJson.create({}); return (sfdxProject.get('oauthLocalPort') as number) || WebOAuthServer.DEFAULT_PORT; } catch { return WebOAuthServer.DEFAULT_PORT; } } /** * Returns the authorization url that's used for the login flow * * @returns {string} */ public getAuthorizationUrl(): string { return this.authUrl; } /** * Executes the oauth request and creates a new AuthInfo when successful * * @returns {Promise<AuthInfo>} */ public async authorizeAndSave(): Promise<AuthInfo> { if (!this.webServer.server) await this.start(); return new Promise((resolve, reject) => { const handler = () => { this.logger.debug(`OAuth web login service listening on port: ${this.webServer.port}`); this.executeOauthRequest() .then(async (response) => { try { const authInfo = await AuthInfo.create({ oauth2Options: this.oauthConfig, oauth2: this.oauth2, }); await authInfo.save(); this.webServer.doRedirect(303, authInfo.getOrgFrontDoorUrl(), response); response.end(); resolve(authInfo); } catch (err) { this.webServer.reportError(err, response); reject(err); } }) .catch((err) => { this.logger.debug('error reported, closing server connection and re-throwing'); reject(err); }) .finally(() => { this.logger.debug('closing server connection'); this.webServer.close(); }); }; // if the server is already listening the listening event won't be fired anymore so execute handler() directly if (this.webServer.server.listening) { handler(); } else { this.webServer.server.once('listening', handler); } }); } /** * Starts the web server */ public async start() { await this.webServer.start(); } protected async init(): Promise<void> { this.logger = await Logger.child(this.constructor.name); const port = await WebOAuthServer.determineOauthPort(); if (!this.oauthConfig.clientId) this.oauthConfig.clientId = DEFAULT_CONNECTED_APP_INFO.clientId; if (!this.oauthConfig.loginUrl) this.oauthConfig.loginUrl = AuthInfo.getDefaultInstanceUrl(); if (!this.oauthConfig.redirectUri) this.oauthConfig.redirectUri = `http://localhost:${port}/OauthRedirect`; this.webServer = await WebServer.create({ port }); this.oauth2 = new OAuth2WithVerifier(this.oauthConfig); this.authUrl = AuthInfo.getAuthorizationUrl(this.oauthConfig, this.oauth2); } /** * Executes the oauth request * * @returns {Promise<AuthInfo>} */ private async executeOauthRequest(): Promise<http.ServerResponse> { return new Promise((resolve, reject) => { this.logger.debug('Starting web auth flow'); // eslint-disable-next-line @typescript-eslint/no-misused-promises this.webServer.server.on('request', async (request, response) => { const url = parseUrl(request.url); this.logger.debug(`processing request for uri: ${url.pathname as string}`); if (request.method === 'GET') { if (url.pathname && url.pathname.startsWith('/OauthRedirect')) { request.query = parseQueryString(url.query as string); if (request.query.error) { const err = new SfdxError(request.query.error_description || request.query.error, request.query.error); this.webServer.reportError(err, response); return reject(err); } this.logger.debug(`request.query.state: ${request.query.state as string}`); try { this.oauthConfig.authCode = asString(this.parseAuthCodeFromRequest(response, request)); resolve(response); } catch (err) { reject(err); } } else { this.webServer.sendError(404, 'Resource not found', response); reject(SfdxError.create('@salesforce/core', 'auth', 'invalidRequestUri', [url.pathname])); } } else { this.webServer.sendError(405, 'Unsupported http methods', response); reject(SfdxError.create('@salesforce/core', 'auth', 'invalidRequestMethod', [request.method])); } }); }); } /** * Parses the auth code from the request url * * @param response the http response * @param request the http request * @returns {Nullable<string>} */ private parseAuthCodeFromRequest(response: http.ServerResponse, request: WebOAuthServer.Request): Nullable<string> { if (!this.validateState(request)) { const error = new SfdxError('urlStateMismatch'); this.webServer.sendError(400, `${error.message}\n`, response); this.closeRequest(request); this.logger.warn('urlStateMismatchAttempt detected.'); if (!get(this.webServer.server, 'urlStateMismatchAttempt')) { this.logger.error(error.message); set(this.webServer.server, 'urlStateMismatchAttempt', true); } } else { const authCode = request.query.code; if (authCode && authCode.length > 4) { // AuthCodes are generally long strings. For security purposes we will just log the last 4 of the auth code. this.logger.debug(`Successfully obtained auth code: ...${authCode.substring(authCode.length - 5)}`); } else { this.logger.debug('Expected an auth code but could not find one.'); throw SfdxError.create('@salesforce/core', 'auth', 'missingAuthCode'); } this.logger.debug(`oauthConfig.loginUrl: ${this.oauthConfig.loginUrl}`); this.logger.debug(`oauthConfig.clientId: ${this.oauthConfig.clientId}`); this.logger.debug(`oauthConfig.redirectUri: ${this.oauthConfig.redirectUri}`); return authCode; } return null; } /** * Closes the request * * @param request the http request */ private closeRequest(request: WebOAuthServer.Request): void { request.connection.end(); request.connection.destroy(); } /** * Validates that the state param in the auth url matches the state * param in the http request * * @param request the http request */ private validateState(request: WebOAuthServer.Request): boolean { const state = request.query.state; const query = parseUrl(this.authUrl, true).query; return !!(state && state === query.state); } } export namespace WebOAuthServer { export interface Options { oauthConfig: OAuth2Options; } export type Request = http.IncomingMessage & { query: { code: string; state: string } }; } /** * Handles the actions specific to the http server */ export class WebServer extends AsyncCreatable<WebServer.Options> { public static DEFAULT_CLIENT_SOCKET_TIMEOUT = 20000; public server!: http.Server; public port = WebOAuthServer.DEFAULT_PORT; public host = 'localhost'; private logger!: Logger; private sockets: Socket[] = []; public constructor(options: WebServer.Options) { super(options); if (options.port) this.port = options.port; if (options.host) this.host = options.host; } /** * Starts the http server after checking that the port is open */ public async start(): Promise<void> { try { this.logger.debug('Starting web server'); await this.checkOsPort(); this.logger.debug(`Nothing listening on host: localhost port: ${this.port} - good!`); this.server = http.createServer(); this.server.on('connection', (socket) => { this.logger.debug(`socket connection initialized from ${socket.remoteAddress as string}`); this.sockets.push(socket); }); this.server.listen(this.port, this.host); } catch (err) { if (err.name === 'EADDRINUSE') { const error = SfdxError.create('@salesforce/core', 'auth', 'PortInUse', ['PortInUseAction']); error.actions = [messages.getMessage('PortInUseAction', [this.port])]; throw error; } else { throw err; } } } /** * Closes the http server and all open sockets */ public close(): void { this.sockets.forEach((socket) => { socket.end(); socket.destroy(); }); this.server.getConnections((_, num) => { this.logger.debug(`number of connections open: ${num}`); }); this.server.close(); } /** * sends a response error. * * @param statusCode he statusCode for the response. * @param message the message for the http body. * @param response the response to write the error to. */ public sendError(status: number, message: string, response: http.ServerResponse): void { response.statusMessage = message; response.statusCode = status; response.end(); } /** * sends a response redirect. * * @param statusCode the statusCode for the response. * @param url the url to redirect to. * @param response the response to write the redirect to. */ public doRedirect(status: number, url: string, response: http.ServerResponse): void { response.setHeader('Content-Type', 'text/plain'); const body = `${status} - Redirecting to ${url}`; response.setHeader('Content-Length', Buffer.byteLength(body)); response.writeHead(status, { Location: url }); response.end(body); } /** * sends a response to the browser reporting an error. * * @param error the error * @param response the response to write the redirect to. */ public reportError(error: Error, response: http.ServerResponse): void { response.setHeader('Content-Type', 'text/html'); const body = messages.getMessage('serverErrorHTMLResponse', [error.message]); response.setHeader('Content-Length', Buffer.byteLength(body)); response.end(body); } protected async init(): Promise<void> { this.logger = await Logger.child(this.constructor.name); } /** * Make sure we can't open a socket on the localhost/host port. It's important because we don't want to send * auth tokens to a random strange port listener. We want to make sure we can startup our server first. * * @private */ private async checkOsPort(): Promise<number> { return new Promise((resolve, reject) => { const clientConfig = { port: this.port, host: this.host }; const socket = new Socket(); socket.setTimeout(this.getSocketTimeout(), () => { socket.destroy(); const error = new SfdxError('timeout', 'SOCKET_TIMEOUT'); reject(error); }); // An existing connection, means that the port is occupied socket.connect(clientConfig, () => { socket.destroy(); const error = new SfdxError('Address in use', 'EADDRINUSE'); error.data = { port: clientConfig.port, address: clientConfig.host, }; reject(error); }); // An error means that no existing connection exists, which is what we want socket.on('error', () => { // eslint-disable-next-line no-console socket.destroy(); resolve(this.port); }); }); } /** * check and get the socket timeout form what was set in process.env.SFDX_HTTP_SOCKET_TIMEOUT * * @returns {number} - represents the socket timeout in ms * @private */ private getSocketTimeout(): number { const env = new Env(); const socketTimeout = toNumber(env.getNumber('SFDX_HTTP_SOCKET_TIMEOUT')); return Number.isInteger(socketTimeout) && socketTimeout > 0 ? socketTimeout : WebServer.DEFAULT_CLIENT_SOCKET_TIMEOUT; } } namespace WebServer { export interface Options { port?: number; host?: string; } }
the_stack
/// <reference path="./definitions/Q.d.ts" /> import Q = require('q'); import ctxm = require('./context'); import fs = require('fs'); var shell = require('shelljs'); var path = require('path'); var archiver = require('archiver'); export interface GetOrCreateResult<T> { created: boolean; result: T; } //converts inputString to titleCase string. For example, "abc def" is converted to "Abc Def" export function toTitleCase(inputString: string): string { if (inputString) { return inputString.replace(/\w\S*/g, function(str) { return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase(); }); } return inputString; } // returns a substring that is common from first. For example, for "abcd" and "abdf", "ab" is returned. export function sharedSubString(string1: string, string2: string): string { var ret = ""; var index = 1; while (string1.substring(0, index) == string2.substring(0, index)) { ret = string1.substring(0, index); index++; } return ret; } // sorts string array in ascending order export function sortStringArray(list): string[] { var sortedFiles: string[] = list.sort((a, b) => { if (a > b) { return 1; } else if (a < b) { return -1; } else { return 0; } }); return sortedFiles; } // returns true if path exists and it is a directory else false. export function isDirectoryExists(path: string): boolean { try { return fs.lstatSync(path).isDirectory(); } catch (error) { return false; } } // returns true if path exists and it is a file else false. export function isFileExists(path: string): boolean { try { return fs.lstatSync(path).isFile(); } catch (error) { return false; } } // TODO: offer these module level context-less helper functions in utilities below export function ensurePathExists(path: string): Q.Promise<void> { var defer = Q.defer<void>(); fs.exists(path, (exists) => { if (!exists) { shell.mkdir('-p', path); var errMsg = shell.error(); if (errMsg) { defer.reject(new Error('Could not create path (' + path + '): ' + errMsg)); } else { defer.resolve(null); } } else { defer.resolve(null); } }); return defer.promise; } export function readFileContents(filePath: string, encoding: string): Q.Promise<string> { var defer = Q.defer<string>(); fs.readFile(filePath, encoding, (err, data) => { if (err) { defer.reject(new Error('Could not read file (' + filePath + '): ' + err.message)); } else { defer.resolve(data); } }); return defer.promise; } export function fileExists(filePath: string): Q.Promise<boolean> { var defer = Q.defer<boolean>(); fs.exists(filePath, (exists) => { defer.resolve(exists); }); return <Q.Promise<boolean>>defer.promise; } export function objectToFile(filePath: string, obj: any): Q.Promise<void> { var defer = Q.defer<void>(); fs.writeFile(filePath, JSON.stringify(obj, null, 2), (err) => { if (err) { defer.reject(new Error('Could not save to file (' + filePath + '): ' + err.message)); } else { defer.resolve(null); } }); return defer.promise; } export function objectFromFile(filePath: string, defObj?: any): Q.Promise<any> { var defer = Q.defer<any>(); fs.exists(filePath, (exists) => { if (!exists && defObj) { defer.resolve(defObj); } else if (!exists) { defer.reject(new Error('File does not exist: ' + filePath)); } else { fs.readFile(filePath, (err, contents) => { if (err) { defer.reject(new Error('Could not read file (' + filePath + '): ' + err.message)); } else { var obj: any = JSON.parse(contents.toString()); defer.resolve(obj); } }); } }) return defer.promise; } export function getOrCreateObjectFromFile<T>(filePath: string, defObj: T): Q.Promise<GetOrCreateResult<T>> { var defer = Q.defer<GetOrCreateResult<T>>(); fs.exists(filePath, (exists) => { if (!exists) { fs.writeFile(filePath, JSON.stringify(defObj, null, 2), (err) => { if (err) { defer.reject(new Error('Could not save to file (' + filePath + '): ' + err.message)); } else { defer.resolve({ created: true, result: defObj }); } }); } else { fs.readFile(filePath, (err, contents) => { if (err) { defer.reject(new Error('Could not read file (' + filePath + '): ' + err.message)); } else { var obj: any = JSON.parse(contents.toString()); defer.resolve({ created: false, result: obj }); } }); } }) return defer.promise; } // ret is { output: string, code: number } export function exec(cmdLine: string): Q.Promise<any> { var defer = Q.defer<any>(); shell.exec(cmdLine, (code, output) => { defer.resolve({ code: code, output: output }); }); return defer.promise; } export enum SearchOption { TopDirectoryOnly = 0, AllDirectories = 1, } export function readDirectory(directory: string, includeFiles: boolean, includeFolders: boolean, searchOption?: SearchOption): Q.Promise<string[]> { var results: string[] = []; var deferred = Q.defer<string[]>(); if (includeFolders) { results.push(directory); } Q.nfcall(fs.readdir, directory) .then((files: string[]) => { var count = files.length; if (count > 0) { files.forEach((file: string, index: number) => { var fullPath = path.join(directory, file); Q.nfcall(fs.stat, fullPath) .then((stat: fs.Stats) => { if (stat && stat.isDirectory()) { if (SearchOption.TopDirectoryOnly === searchOption) { results.push(fullPath); if (--count === 0) { deferred.resolve(results); } } else { readDirectory(fullPath, includeFiles, includeFolders, searchOption) .then((moreFiles: string[]) => { results = results.concat(moreFiles); if (--count === 0) { deferred.resolve(results); } }, (error) => { deferred.reject(new Error(error.toString())); }); } } else { if (includeFiles) { results.push(fullPath); } if (--count === 0) { deferred.resolve(results); } } }); }); } else { deferred.resolve(results); } }, (error) => { deferred.reject(error); }); return deferred.promise; } export function archiveFiles(files: string[], archiveName: string): Q.Promise<string> { var defer = Q.defer<string>(); var archive = path.join(shell.tempdir(), archiveName); var output = fs.createWriteStream(archive); var zipper = archiver('zip'); output.on('close', function() { defer.resolve(archive); }); zipper.on('error', function(err) { defer.reject(err); }); zipper.pipe(output); zipper.bulk([{ src: files, expand: true }]); zipper.finalize(function(err, bytes) { if (err) { defer.reject(err); } }); return defer.promise; } // // Utilities passed to each task // which provides contextual logging to server etc... // also contains general utility methods that would be useful to all task authors // export class Utilities { constructor(context: ctxm.Context) { this.ctx = context; } private ctx: ctxm.Context; // // '-a -b "quoted b value" -c -d "quoted d value"' becomes // [ '-a', '-b', '"quoted b value"', '-c', '-d', '"quoted d value"' ] // public argStringToArray(argString: string): string[] { var args = argString.match(/([^" ]*("[^"]*")[^" ]*)|[^" ]+/g); //remove double quotes from each string in args as child_process.spawn() cannot handle literla quotes as part of arguments for (var i = 0; i < args.length; i++) { args[i] = args[i].replace(/"/g, ""); } return args; } // spawn a process with stdout/err piped to context's logger // callback(err) public spawn(name: string, args: string[], options, callback: (err: any, returnCode: number) => void) { var failed = false; options = options || {}; args = args || []; var ops = { cwd: process.cwd(), env: process.env, failOnStdErr: true, failOnNonZeroRC: true }; // write over specified options over default options (ops) for (var op in options) { ops[op] = options[op]; } this.ctx.verbose('cwd: ' + ops.cwd); this.ctx.verbose('args: ' + args.toString()); this.ctx.info('running: ' + name + ' ' + args.join(' ')); var cp = require('child_process').spawn; var runCP = cp(name, args, ops); runCP.stdout.on('data', (data) => { this.ctx.info(data.toString('utf8')); }); runCP.stderr.on('data', (data) => { failed = ops.failOnStdErr; if (ops.failOnStdErr) { this.ctx.error(data.toString('utf8')); } else { this.ctx.info(data.toString('utf8')); } }); runCP.on('exit', (code) => { if (failed) { callback(new Error('Failed with Error Output'), code); return; } if (code == 0 || !ops.failOnNonZeroRC) { callback(null, code); } else { var msg = path.basename(name) + ' returned code: ' + code; callback(new Error(msg), code); } }); } }
the_stack